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