dolibarr  19.0.0-dev
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) {
569  $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 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  foreach ($toselect as $toselectid) {
1051  $result = $objecttmp->fetch($toselectid);
1052  if ($result > 0) {
1053  // Refuse deletion for some objects/status
1054  if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
1055  $langs->load("errors");
1056  $nbignored++;
1057  $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1058  continue;
1059  }
1060 
1061  if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1062  $langs->load("errors");
1063  $nbignored++;
1064  $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1065  continue;
1066  }
1067 
1068  if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1069  $langs->load("errors");
1070  $nbignored++;
1071  $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1072  continue;
1073  }
1074 
1075  if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1076  $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1077  $res = $db->query($sql);
1078 
1079  if (!$res) {
1080  setEventMessage('ErrorRecordParentingNotModified', 'errors');
1081  $error++;
1082  }
1083  }
1084 
1085  if (in_array($objecttmp->element, array('societe', 'member'))) {
1086  $result = $objecttmp->delete($objecttmp->id, $user, 1);
1087  } elseif (in_array($objecttmp->element, array('action'))) {
1088  $result = $objecttmp->delete();
1089  } else {
1090  $result = $objecttmp->delete($user);
1091  }
1092 
1093  if (empty($result)) { // if delete returns 0, there is at least one object linked
1094  $TMsg = array_merge($objecttmp->errors, $TMsg);
1095  } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1096  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1097  $error++;
1098  break;
1099  } else {
1100  $nbok++;
1101  }
1102  } else {
1103  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1104  $error++;
1105  break;
1106  }
1107  }
1108 
1109  if (empty($error)) {
1110  // Message for elements well deleted
1111  if ($nbok > 1) {
1112  setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1113  } elseif ($nbok > 0) {
1114  setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1115  } else {
1116  setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1117  }
1118 
1119  // Message for elements which can't be deleted
1120  if (!empty($TMsg)) {
1121  sort($TMsg);
1122  setEventMessages('', array_unique($TMsg), 'warnings');
1123  }
1124 
1125  $db->commit();
1126  } else {
1127  $db->rollback();
1128  }
1129 
1130  //var_dump($listofobjectthirdparties);exit;
1131 }
1132 
1133 // Generate document foreach object according to model linked to object
1134 // @todo : propose model selection
1135 if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1136  $db->begin();
1137  $objecttmp = new $objectclass($db);
1138  $nbok = 0;
1139  foreach ($toselect as $toselectid) {
1140  $result = $objecttmp->fetch($toselectid);
1141  if ($result > 0) {
1142  $outputlangs = $langs;
1143  $newlang = '';
1144 
1145  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1146  $newlang = GETPOST('lang_id', 'aZ09');
1147  }
1148  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1149  $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1150  }
1151  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
1152  $newlang = $objecttmp->default_lang; // for thirdparty
1153  }
1154  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
1155  $objecttmp->fetch_thirdparty();
1156  $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1157  }
1158  if (!empty($newlang)) {
1159  $outputlangs = new Translate("", $conf);
1160  $outputlangs->setDefaultLang($newlang);
1161  }
1162 
1163  // To be sure vars is defined
1164  if (empty($hidedetails)) {
1165  $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
1166  }
1167  if (empty($hidedesc)) {
1168  $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
1169  }
1170  if (empty($hideref)) {
1171  $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
1172  }
1173  if (empty($moreparams)) {
1174  $moreparams = null;
1175  }
1176 
1177  $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1178 
1179  if ($result <= 0) {
1180  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1181  $error++;
1182  break;
1183  } else {
1184  $nbok++;
1185  }
1186  } else {
1187  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1188  $error++;
1189  break;
1190  }
1191  }
1192 
1193  if (!$error) {
1194  if ($nbok > 1) {
1195  setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1196  } else {
1197  setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1198  }
1199  $db->commit();
1200  } else {
1201  $db->rollback();
1202  }
1203 }
1204 
1205 if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
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 submited 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  $nbok = 0;
1228  if (!empty($to_affecttag_type_array)) {
1229  foreach ($to_affecttag_type_array as $categ_type) {
1230  $contcats = GETPOST('contcats_' . $categ_type, 'array');
1231  //var_dump($toselect);exit;
1232  foreach ($toselect as $toselectid) {
1233  $result = $object->fetch($toselectid);
1234  //var_dump($contcats);exit;
1235  if ($result > 0) {
1236  $result = $object->setCategoriesCommon($contcats, $categ_type, false);
1237  if ($result > 0) {
1238  $nbok++;
1239  } else {
1240  setEventMessages($object->error, $object->errors, 'errors');
1241  }
1242  } else {
1243  setEventMessages($object->error, $object->errors, 'errors');
1244  $error++;
1245  break;
1246  }
1247  }
1248  }
1249  }
1250  }
1251 
1252  if (!$error) {
1253  if ($nbok > 1) {
1254  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1255  } else {
1256  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1257  }
1258  $db->commit();
1259  $toselect=array();
1260  } else {
1261  $db->rollback();
1262  }
1263 }
1264 
1265 if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
1266  $db->begin();
1267  if (GETPOSTISSET('pricerate')) {
1268  $pricepercentage=GETPOST('pricerate', 'int');
1269  if ($pricepercentage == 0) {
1270  setEventMessages($langs->trans("RecordsModified", 0), null);
1271  } else {
1272  foreach ($toselect as $toselectid) {
1273  $result = $object->fetch($toselectid);
1274  //var_dump($contcats);exit;
1275  if ($result > 0) {
1276  if ($obj->price_base_type == 'TTC') {
1277  $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1278  $minprice = $object->price_min_ttc;
1279  } else {
1280  $newprice = $object->price * (100 + $pricepercentage) / 100;
1281  $minprice = $object->price_min;
1282  }
1283  $res = $object->updatePrice($newprice, $obj->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1284  if ($res > 0) {
1285  $nbok++;
1286  } else {
1287  setEventMessages($object->error, $object->errors, 'errors');
1288  }
1289  } else {
1290  setEventMessages($object->error, $object->errors, 'errors');
1291  $error++;
1292  break;
1293  }
1294  }
1295  }
1296  }
1297 
1298  if (!$error) {
1299  if ($nbok > 0) {
1300  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1301  }
1302  $db->commit();
1303  $toselect=array();
1304  } else {
1305  $db->rollback();
1306  }
1307 }
1308 
1309 if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1310  $db->begin();
1311  $supervisortoset=GETPOST('supervisortoset');
1312  if (!empty($supervisortoset)) {
1313  foreach ($toselect as $toselectid) {
1314  $result = $object->fetch($toselectid);
1315  //var_dump($contcats);exit;
1316  if ($result > 0) {
1317  $object->fk_user = $supervisortoset;
1318  $res = $object->update($user);
1319  if ($res > 0) {
1320  $nbok++;
1321  } else {
1322  setEventMessages($object->error, $object->errors, 'errors');
1323  }
1324  } else {
1325  setEventMessages($object->error, $object->errors, 'errors');
1326  $error++;
1327  break;
1328  }
1329  }
1330  } else {
1331  setEventMessage('UserNotFound', 'errors');
1332  $error++;
1333  }
1334 
1335  if (!$error) {
1336  if ($nbok > 1) {
1337  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1338  } else {
1339  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1340  }
1341  $db->commit();
1342  $toselect=array();
1343  } else {
1344  $db->rollback();
1345  }
1346 }
1347 
1348 if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1349  $db->begin();
1350 
1351  $usertoaffect=GETPOST('usertoaffect');
1352  $projectrole=GETPOST('projectrole');
1353  $tasksrole=GETPOST('tasksrole');
1354  if (!empty($usertoaffect)) {
1355  foreach ($toselect as $toselectid) {
1356  $result = $object->fetch($toselectid);
1357  //var_dump($contcats);exit;
1358  if ($result > 0) {
1359  $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1360  if ($res >= 0) {
1361  $taskstatic = new Task($db);
1362  $task_array = $taskstatic->getTasksArray(0, 0, $object->id, 0, 0);
1363 
1364  foreach ($task_array as $task) {
1365  $tasksToAffect = new Task($db);
1366  $result = $tasksToAffect->fetch($task->id);
1367  if ($result > 0) {
1368  $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1369  if ($res < 0) {
1370  setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1371  }
1372  }
1373  }
1374  $nbok++;
1375  } else {
1376  setEventMessages($object->error, $object->errors, 'errors');
1377  }
1378  } else {
1379  setEventMessages($object->error, $object->errors, 'errors');
1380  $error++;
1381  break;
1382  }
1383  }
1384  } else {
1385  setEventMessage('UserNotFound', 'errors');
1386  $error++;
1387  }
1388 
1389  if (!$error) {
1390  if ($nbok > 1) {
1391  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1392  } else {
1393  setEventMessages($langs->trans("RecordsModified", $nbok), null);
1394  }
1395  $db->commit();
1396  $toselect=array();
1397  } else {
1398  $db->rollback();
1399  }
1400 }
1401 
1402 if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1403  $db->begin();
1404 
1405  $objecttmp = new $objectclass($db);
1406  $nbok = 0;
1407  foreach ($toselect as $toselectid) {
1408  $result = $objecttmp->fetch($toselectid);
1409  if ($result>0) {
1410  if (in_array($objecttmp->element, array('societe'))) {
1411  $result =$objecttmp->setStatut(1);
1412  }
1413  if ($result <= 0) {
1414  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1415  $error++;
1416  break;
1417  } else {
1418  $nbok++;
1419  }
1420  } else {
1421  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1422  $error++;
1423  break;
1424  }
1425  }
1426 
1427  if (!$error) {
1428  if ($nbok > 1) {
1429  setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1430  } else {
1431  setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1432  }
1433  $db->commit();
1434  } else {
1435  $db->rollback();
1436  }
1437 }
1438 
1439 if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1440  $db->begin();
1441 
1442  $objecttmp = new $objectclass($db);
1443  $nbok = 0;
1444  foreach ($toselect as $toselectid) {
1445  $result = $objecttmp->fetch($toselectid);
1446  if ($result>0) {
1447  if (in_array($objecttmp->element, array('societe'))) {
1448  $result =$objecttmp->setStatut(0);
1449  }
1450  if ($result <= 0) {
1451  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1452  $error++;
1453  break;
1454  } else {
1455  $nbok++;
1456  }
1457  } else {
1458  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1459  $error++;
1460  break;
1461  }
1462  }
1463 
1464  if (!$error) {
1465  if ($nbok > 1) {
1466  setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1467  } else {
1468  setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1469  }
1470  $db->commit();
1471  } else {
1472  $db->rollback();
1473  }
1474 }
1475 
1476 if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1477  $db->begin();
1478 
1479  $objecttmp = new $objectclass($db);
1480  $e = new ExtraFields($db);// fetch optionals attributes and labels
1481  $e->fetch_name_optionals_label($objecttmp->table_element);
1482 
1483  $nbok = 0;
1484  $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1485 
1486 
1487  foreach ($toselect as $toselectid) {
1489  $objecttmp = new $objectclass($db); // to avoid ghost data
1490  $result = $objecttmp->fetch($toselectid);
1491  if ($result>0) {
1492  // Fill array 'array_options' with data from add form
1493  $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1494  if ($ret > 0) {
1495  $objecttmp->insertExtraFields();
1496  } else {
1497  $error++;
1498  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1499  }
1500  } else {
1501  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1502  $error++;
1503  break;
1504  }
1505  }
1506 
1507  if (!$error) {
1508  if ($nbok > 1) {
1509  setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1510  } else {
1511  setEventMessages($langs->trans("save"), null, 'mesgs');
1512  }
1513  $db->commit();
1514  } else {
1515  $db->rollback();
1516  }
1517 }
1518 
1519 if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
1520  $db->begin();
1521 
1522  $objecttmp = new $objectclass($db);
1523  $nbok = 0;
1524 
1525  foreach ($toselect as $toselectid) {
1526  $result = $objecttmp->fetch($toselectid);
1527  if ($result>0) {
1528  if (in_array($objecttmp->element, array('societe'))) {
1529  $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1530  }
1531  if ($result <= 0) {
1532  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1533  $error++;
1534  break;
1535  } else {
1536  $nbok++;
1537  }
1538  } else {
1539  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1540  $error++;
1541  break;
1542  }
1543  }
1544 
1545  if (!$error) {
1546  if ($nbok > 1) {
1547  setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1548  } else {
1549  setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1550  }
1551  $db->commit();
1552  } else {
1553  $db->rollback();
1554  }
1555 }
1556 
1557 // Approve for leave only
1558 if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1559  $db->begin();
1560 
1561  $objecttmp = new $objectclass($db);
1562  $nbok = 0;
1563  foreach ($toselect as $toselectid) {
1564  $result = $objecttmp->fetch($toselectid);
1565  if ($result > 0) {
1566  if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
1567  setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1568  continue;
1569  }
1570  if ($user->id == $objecttmp->fk_validator) {
1571  $objecttmp->oldcopy = dol_clone($objecttmp);
1572 
1573  $objecttmp->date_valid = dol_now();
1574  $objecttmp->fk_user_valid = $user->id;
1575  $objecttmp->statut = Holiday::STATUS_APPROVED;
1576 
1577  $verif = $objecttmp->approve($user);
1578 
1579  if ($verif <= 0) {
1580  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1581  $error++;
1582  }
1583 
1584  // If no SQL error, we redirect to the request form
1585  if (!$error) {
1586  // Calculcate number of days consumed
1587  $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
1588  $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1589  $newSolde = ($soldeActuel - $nbopenedday);
1590 
1591  // The modification is added to the LOG
1592  $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1593  if ($result < 0) {
1594  $error++;
1595  setEventMessages(null, $objecttmp->errors, 'errors');
1596  }
1597 
1598  // Update balance
1599  $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1600  if ($result < 0) {
1601  $error++;
1602  setEventMessages(null, $objecttmp->errors, 'errors');
1603  }
1604  }
1605 
1606  if (!$error) {
1607  // To
1608  $destinataire = new User($db);
1609  $destinataire->fetch($objecttmp->fk_user);
1610  $emailTo = $destinataire->email;
1611 
1612  if (!$emailTo) {
1613  dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1614  } else {
1615  // From
1616  $expediteur = new User($db);
1617  $expediteur->fetch($objecttmp->fk_validator);
1618  //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1619  $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
1620 
1621  // Subject
1622  $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
1623  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1624  $societeName = $conf->global->MAIN_APPLICATION_TITLE;
1625  }
1626 
1627  $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1628 
1629  // Content
1630  $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1631  $message .= "\n";
1632 
1633  $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1634 
1635  $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1636 
1637  $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1638  $message .= "\n";
1639 
1640  $trackid = 'leav'.$objecttmp->id;
1641 
1642  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1643  $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1644 
1645  // Sending email
1646  $result = $mail->sendfile();
1647 
1648  if (!$result) {
1649  setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1650  $action = '';
1651  }
1652  }
1653  }
1654  } else {
1655  $langs->load("errors");
1656  setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1657  }
1658  } else {
1659  setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1660  $error++;
1661  break;
1662  }
1663  }
1664 
1665  if (!$error) {
1666  if ($nbok > 1) {
1667  setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1668  } elseif ($nbok == 1) {
1669  setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1670  }
1671  $db->commit();
1672  } else {
1673  $db->rollback();
1674  }
1675 }
1676 
1677 if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
1678  $db->begin();
1679  $objecttmp = new $objectclass($db);
1680  $nbok = 0;
1681  $typeholiday = GETPOST('typeholiday', 'alpha');
1682  $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
1683 
1684  if ($nbdaysholidays <= 0) {
1685  setEventMessages($langs->trans("WrongAmount"), "", 'errors');
1686  $error++;
1687  }
1688 
1689  if (!$error) {
1690  foreach ($toselect as $toselectid) {
1691  $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1692  if (!empty($balancecpuser)) {
1693  $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1694  } else {
1695  $newnbdaysholidays = $nbdaysholidays;
1696  }
1697  $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1698  if ($result <= 0) {
1699  setEventMessages($holiday->error, $holiday->errors, 'errors');
1700  $error++;
1701  break;
1702  }
1703 
1704  $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1705  if ($result > 0) {
1706  $nbok++;
1707  } else {
1708  setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
1709  $error++;
1710  break;
1711  }
1712  }
1713  }
1714 
1715  if (!$error) {
1716  if ($nbok > 1) {
1717  setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1718  } elseif ($nbok == 1) {
1719  setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1720  }
1721  $db->commit();
1722  $toselect=array();
1723  } else {
1724  $db->rollback();
1725  }
1726 }
1727 
1728 //if (!$error && $massaction == 'clonetasks' && $user->rights->projet->creer) {
1729 if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) {
1730  $num = 0;
1731 
1732  dol_include_once('/projet/class/task.class.php');
1733 
1734  $origin_task = new Task($db);
1735  $clone_task = new Task($db);
1736 
1737  foreach (GETPOST('selected') as $task) {
1738  $origin_task->fetch($task, $ref = '', $loadparentdata = 0);
1739 
1740  $defaultref = '';
1741  $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
1742  if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . ".php")) {
1743  require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . '.php';
1744  $modTask = new $obj;
1745  $defaultref = $modTask->getNextValue(0, $clone_task);
1746  }
1747 
1748  if (!$error) {
1749  $clone_task->fk_project = GETPOST('projectid', 'int');
1750  $clone_task->ref = $defaultref;
1751  $clone_task->label = $origin_task->label;
1752  $clone_task->description = $origin_task->description;
1753  $clone_task->planned_workload = $origin_task->planned_workload;
1754  $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1755  $clone_task->date_c = dol_now();
1756  $clone_task->date_start = $origin_task->date_start;
1757  $clone_task->date_end = $origin_task->date_end;
1758  $clone_task->progress = $origin_task->progress;
1759 
1760  // Fill array 'array_options' with data from add form
1761  $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1762 
1763  $taskid = $clone_task->create($user);
1764 
1765  if ($taskid > 0) {
1766  $result = $clone_task->add_contact(GETPOST("userid", 'int'), 'TASKEXECUTIVE', 'internal');
1767  $num++;
1768  } else {
1769  if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1770  $langs->load("projects");
1771  setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings');
1772  $duplicate_code_error = true;
1773  } else {
1774  setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1775  }
1776  $action = 'list';
1777  $error++;
1778  }
1779  }
1780  }
1781 
1782  if (!$error) {
1783  setEventMessage($langs->trans('NumberOfTasksCloned', $num));
1784  header("Refresh: 1;URL=".DOL_URL_ROOT.'/projet/tasks.php?id=' . GETPOST('projectid', 'int'));
1785  }
1786 }
1787 
1788 $parameters['toselect'] = (empty($toselect) ? array() : $toselect);
1789 $parameters['uploaddir'] = $uploaddir;
1790 $parameters['massaction'] = $massaction;
1791 $parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
1792 
1793 $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1794 if ($reshook < 0) {
1795  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1796 }
$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:1015
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
Definition: files.lib.php:1334
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:2524
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.