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