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