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