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