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