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