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