forked from Dolibarr/dolibarr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions_massactions.inc.php
1796 lines (1610 loc) · 63.8 KB
/
actions_massactions.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2015-2017 Laurent Destailleur <[email protected]>
* Copyright (C) 2018-2021 Nicolas ZABOURI <[email protected]>
* Copyright (C) 2018 Juanjo Menent <[email protected]>
* Copyright (C) 2019 Ferran Marcet <[email protected]>
* Copyright (C) 2019-2021 Frédéric France <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* or see https://www.gnu.org/
*/
/**
* \file htdocs/core/actions_massactions.inc.php
* \brief Code for actions done with massaction button (send by email, merge pdf, delete, ...)
*/
// $massaction must be defined
// $objectclass and $objectlabel must be defined
// $parameters, $object, $action must be defined for the hook.
// $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
// $uploaddir may be defined (example to $conf->project->dir_output."/";)
// $toselect may be defined
// $diroutputmassaction may be defined
// Protection
if (empty($objectclass) || empty($uploaddir)) {
dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
exit;
}
if (empty($massaction)) {
$massaction = '';
}
$error = 0;
// For backward compatibility
if (!empty($permtoread) && empty($permissiontoread)) {
$permissiontoread = $permtoread;
}
if (!empty($permtocreate) && empty($permissiontoadd)) {
$permissiontoadd = $permtocreate;
}
if (!empty($permtodelete) && empty($permissiontodelete)) {
$permissiontodelete = $permtodelete;
}
// Mass actions. Controls on number of lines checked.
$maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
if ($massaction && is_array($toselect) && count($toselect) < 1) {
$error++;
setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
}
if (!$error && isset($toselect) && is_array($toselect) && count($toselect) > $maxformassaction) {
setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
$error++;
}
if (!$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
$massaction = 'presend';
}
if (!$error && $massaction == 'confirm_presend') {
$resaction = '';
$nbsent = 0;
$nbignored = 0;
$langs->load("mails");
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
$listofobjectid = array();
$listofobjectthirdparties = array();
$listofobjectcontacts = array();
$listofobjectref = array();
$contactidtosend = array();
$attachedfilesThirdpartyObj = array();
$oneemailperrecipient = (GETPOST('oneemailperrecipient', 'int') ? 1 : 0);
if (!$error) {
$objecttmp = new $objectclass($db);
// Define object $thirdparty (Societe or User, Adherent, ConferenceOrBoothAttendee...)
$thirdparty = new Societe($db);
if ($objecttmp->element == 'expensereport') {
$thirdparty = new User($db);
} elseif ($objecttmp->element == 'contact') {
$thirdparty = new Contact($db);
} elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
$thirdparty = new Adherent($db);
} elseif ($objecttmp->element == 'holiday') {
$thirdparty = new User($db);
} elseif ($objecttmp->element == 'conferenceorboothattendee') {
$thirdparty = new ConferenceOrBoothAttendee($db);
}
foreach ($toselect as $toselectid) {
$objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
$result = $objecttmp->fetch($toselectid);
if ($result > 0) {
$listofobjectid[$toselectid] = $toselectid;
$tmpobjectid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
if ($objecttmp->element == 'societe') {
$tmpobjectid = $objecttmp->id;
} elseif ($objecttmp->element == 'contact') {
$tmpobjectid = $objecttmp->id;
} elseif ($objecttmp->element == 'expensereport') {
$tmpobjectid = $objecttmp->fk_user_author;
} elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
$tmpobjectid = $objecttmp->fk_member;
} elseif ($objecttmp->element == 'holiday') {
$tmpobjectid = $objecttmp->fk_user;
} elseif ($objecttmp->element == 'conferenceorboothattendee') {
$tmpobjectid = $objecttmp->id;
}
if (empty($tmpobjectid)) {
$tmpobjectid = 0;
}
if ($objectclass == 'Facture') {
$tmparraycontact = array();
$tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
foreach ($tmparraycontact as $data_email) {
$listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
}
}
} elseif ($objectclass == 'CommandeFournisseur') {
$tmparraycontact = array();
$tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'CUSTOMER');
if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
foreach ($tmparraycontact as $data_email) {
$listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
}
}
}
$listofobjectthirdparties[$tmpobjectid] = $tmpobjectid;
$listofobjectref[$tmpobjectid][$toselectid] = $objecttmp;
}
}
}
// Check mandatory parameters
if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
$error++;
setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
$massaction = 'presend';
}
$receiver = GETPOST('receiver', 'alphawithlgt');
if (!is_array($receiver)) {
if (empty($receiver) || $receiver == '-1') {
$receiver = array();
} else {
$receiver = array($receiver);
}
}
if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
$error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
$massaction = 'presend';
}
if (!GETPOST('subject', 'restricthtml')) {
$error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
$massaction = 'presend';
}
// Loop on each recipient (may be a thirdparty but also a user, a conferenceorboothattendee, ...)
if (!$error) {
foreach ($listofobjectthirdparties as $thirdpartyid) {
$result = $thirdparty->fetch($thirdpartyid);
if ($result < 0) {
dol_print_error($db);
exit;
}
$sendto = '';
$sendtocc = '';
$sendtobcc = '';
//$sendtoid = array();
// Define $sendto
$tmparray = array();
if (trim($_POST['sendto'])) {
// Recipients are provided into free text
$tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
}
if (count($receiver) > 0) {
foreach ($receiver as $key => $val) {
// Recipient was provided from combo list
if ($val == 'thirdparty') { // Id of third party or user
$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
} elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
//$sendtoid[] = $val;
}
}
}
$sendto = implode(',', $tmparray);
// Define $sendtocc
$receivercc = GETPOST('receivercc', 'alphawithlgt');
if (!is_array($receivercc)) {
if ($receivercc == '-1') {
$receivercc = array();
} else {
$receivercc = array($receivercc);
}
}
$tmparray = array();
if (trim($_POST['sendtocc'])) {
$tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
}
if (count($receivercc) > 0) {
foreach ($receivercc as $key => $val) {
// Recipient was provided from combo list
if ($val == 'thirdparty') { // Id of third party
$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
} elseif ($val) { // Id du contact
$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
//$sendtoid[] = $val; TODO Add also id of contact in CC ?
}
}
}
$sendtocc = implode(',', $tmparray);
//var_dump($listofobjectref);exit;
$listofqualifiedobj = array();
$listofqualifiedref = array();
$thirdpartywithoutemail = array();
foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
//var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) {
$langs->load("errors");
$nbignored++;
$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
continue; // Payment done or started or canceled
}
if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) {
$langs->load("errors");
$nbignored++;
$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
continue;
}
if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) {
$langs->load("errors");
$nbignored++;
$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
continue; // Payment done or started or canceled
}
// Test recipient
if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
if ($objectobj->element == 'societe') {
$sendto = $objectobj->email;
} elseif ($objectobj->element == 'expensereport') {
$fuser = new User($db);
$fuser->fetch($objectobj->fk_user_author);
$sendto = $fuser->email;
} elseif ($objectobj->element == 'contact') {
$fcontact = new Contact($db);
$fcontact->fetch($objectobj->id);
$sendto = $fcontact->email;
} elseif ($objectobj->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
$fadherent = new Adherent($db);
$fadherent->fetch($objectobj->fk_member);
$sendto = $fadherent->email;
} elseif ($objectobj->element == 'holiday') {
$fuser = new User($db);
$fuser->fetch($objectobj->fk_user);
$sendto = $fuser->email;
} elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
$emails_to_sends = array();
$objectobj->fetch_thirdparty();
$contactidtosend = array();
foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
$emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
if (!in_array($contactemailid, $contactidtosend)) {
$contactidtosend[] = $contactemailid;
}
}
if (count($emails_to_sends) > 0) {
$sendto = implode(',', $emails_to_sends);
}
} elseif ($objectobj->element == 'order_supplier' && !empty($listofobjectcontacts[$objectid])) {
$emails_to_sends = array();
$objectobj->fetch_thirdparty();
$contactidtosend = array();
foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
$emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
if (!in_array($contactemailid, $contactidtosend)) {
$contactidtosend[] = $contactemailid;
}
}
if (count($emails_to_sends) > 0) {
$sendto = implode(',', $emails_to_sends);
}
} elseif ($objectobj->element == 'conferenceorboothattendee') {
$sendto = $objectobj->email;
} else {
$objectobj->fetch_thirdparty();
$sendto = $objectobj->thirdparty->email;
}
}
if (empty($sendto)) {
if ($objectobj->element == 'societe') {
$objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
}
//print "No recipient for thirdparty ".$objectobj->thirdparty->name;
$nbignored++;
if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
$resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
}
dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
$thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
continue;
}
if (GETPOST('addmaindocfile')) {
// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
// TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc.
$filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
$subdir = '';
// TODO Set subdir to be compatible with multi levels dir trees
// $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
$filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
$filepath = $filedir.'/'.$filename;
// For supplier invoices, we use the file provided by supplier, not the one we generate
if ($objectobj->element == 'invoice_supplier') {
$fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
$filepath = $fileparams['fullname'];
}
// try to find other files generated for this object (last_main_doc)
$filename_found = '';
$filepath_found = '';
$file_check_list = array();
$file_check_list[] = array(
'name' => $filename,
'path' => $filepath,
);
if (!empty($conf->global->MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND) && !empty($objectobj->last_main_doc)) {
$file_check_list[] = array(
'name' => basename($objectobj->last_main_doc),
'path' => DOL_DATA_ROOT . '/' . $objectobj->last_main_doc,
);
}
foreach ($file_check_list as $file_check_arr) {
if (dol_is_file($file_check_arr['path'])) {
$filename_found = $file_check_arr['name'];
$filepath_found = $file_check_arr['path'];
break;
}
}
if ($filepath_found) {
// Create form object
$attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
'paths'=>array($filepath_found),
'names'=>array($filename_found),
'mimes'=>array(dol_mimetype($filepath_found))
);
} else {
$nbignored++;
$langs->load("errors");
foreach ($file_check_list as $file_check_arr) {
$resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file_check_arr['path']).'</div><br>';
dol_syslog('Failed to read file: '.$file_check_arr['path'], LOG_WARNING);
}
continue;
}
}
// Object of thirdparty qualified, we add it
$listofqualifiedobj[$objectid] = $objectobj;
$listofqualifiedref[$objectid] = $objectobj->ref;
//var_dump($listofqualifiedref);
}
// Send email if there is at least one qualified object for current thirdparty
if (count($listofqualifiedobj) > 0) {
$langs->load("commercial");
$reg = array();
$fromtype = GETPOST('fromtype');
if ($fromtype === 'user') {
$from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
} elseif ($fromtype === 'company') {
$from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
} elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
$tmp = explode(',', $user->email_aliases);
$from = trim($tmp[($reg[1] - 1)]);
} elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
$tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
$from = trim($tmp[($reg[1] - 1)]);
} elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
$sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1];
$resql = $db->query($sql);
$obj = $db->fetch_object($resql);
if ($obj) {
$from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>';
}
} else {
$from = GETPOST('fromname').' <'.GETPOST('frommail').'>';
}
$replyto = $from;
$subject = GETPOST('subject', 'restricthtml');
$message = GETPOST('message', 'restricthtml');
$sendtobcc = GETPOST('sendtoccc');
if ($objectclass == 'Propal') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
}
if ($objectclass == 'Commande') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
}
if ($objectclass == 'Facture') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
}
if ($objectclass == 'Supplier_Proposal') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
}
if ($objectclass == 'CommandeFournisseur') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
}
if ($objectclass == 'FactureFournisseur') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
}
if ($objectclass == 'Project') {
$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
}
// $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)
// $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)
$looparray = array();
if (!$oneemailperrecipient) {
$looparray = $listofqualifiedobj;
foreach ($looparray as $key => $objecttmp) {
$looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
}
} else {
$objectforloop = new $objectclass($db);
$objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
$looparray[0] = $objectforloop;
}
//var_dump($looparray);exit;
dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
//var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
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
// Make substitution in email content
if (isModEnabled('project') && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) {
$objecttmp->fetch_projet();
}
$substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
$substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
$substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
$substitutionarray['__EMAIL__'] = $thirdparty->email;
$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"/>';
$parameters = array('mode'=>'formemail');
if (!empty($listofobjectthirdparties)) {
$parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
}
if (!empty($listofobjectref)) {
$parameters['listofobjectref'] = $listofobjectref;
}
complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
$subjectreplaced = make_substitutions($subject, $substitutionarray);
$messagereplaced = make_substitutions($message, $substitutionarray);
$attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
if ($oneemailperrecipient) {
// if "one email per recipient" is check we must collate $attachedfiles by thirdparty
if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) {
foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
// Create form object
$attachedfiles = array(
'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
'names'=>array_merge($attachedfiles['names'], $objAttachedFiles['names']),
'mimes'=>array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
);
}
}
} elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
// Create form object
// if "one email per recipient" isn't check we must separate $attachedfiles by object
$attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
}
$filepath = $attachedfiles['paths'];
$filename = $attachedfiles['names'];
$mimetype = $attachedfiles['mimes'];
// Define the trackid when emails sent from the mass action
if ($oneemailperrecipient) {
$trackid = 'thi'.$thirdparty->id;
if ($objecttmp->element == 'expensereport') {
$trackid = 'use'.$thirdparty->id;
} elseif ($objecttmp->element == 'contact') {
$trackid = 'ctc'.$thirdparty->id;
} elseif ($objecttmp->element == 'holiday') {
$trackid = 'use'.$thirdparty->id;
}
} else {
$trackid = strtolower(get_class($objecttmp));
if (get_class($objecttmp) == 'Contact') {
$trackid = 'ctc';
} elseif (get_class($objecttmp) == 'Contrat') {
$trackid = 'con';
} elseif (get_class($objecttmp) == 'Propal') {
$trackid = 'pro';
} elseif (get_class($objecttmp) == 'Commande') {
$trackid = 'ord';
} elseif (get_class($objecttmp) == 'Facture') {
$trackid = 'inv';
} elseif (get_class($objecttmp) == 'Supplier_Proposal') {
$trackid = 'spr';
} elseif (get_class($objecttmp) == 'CommandeFournisseur') {
$trackid = 'sor';
} elseif (get_class($objecttmp) == 'FactureFournisseur') {
$trackid = 'sin';
}
$trackid .= $objecttmp->id;
}
//var_dump($filepath);
//var_dump($trackid);exit;
//var_dump($subjectreplaced);
if (empty($sendcontext)) {
$sendcontext = 'standard';
}
// Set tmp user directory (used to convert images embedded as img src=data:image)
$vardir = $conf->user->dir_output."/".$user->id;
$upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
// Send mail (substitutionarray must be done just before this)
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
$mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, '', $upload_dir_tmp);
if ($mailfile->error) {
$resaction .= '<div class="error">'.$mailfile->error.'</div>';
} else {
$result = $mailfile->sendfile();
if ($result) {
$resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
$error = 0;
// Insert logs into agenda
foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
if ((!$oneemailperrecipient) && $objid2 != $objectid) {
continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
}
dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
/*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
if ($objectclass == 'Commande') $actiontypecode='AC_COM';
if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
$actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
if ($message) {
if ($sendtocc) {
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
}
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
$actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
}
$actionmsg2 = '';
// Initialisation donnees
$objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
$objectobj2->actionmsg = $actionmsg; // Long text
$objectobj2->actionmsg2 = $actionmsg2; // Short text
$objectobj2->fk_element = $objid2;
$objectobj2->elementtype = $objectobj2->element;
if (!empty($conf->global->MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT)) {
$objectobj2->actionmsg2 = $subjectreplaced; // Short text
}
$triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
if ($triggername == 'SOCIETE_SENTBYMAIL') {
$triggername = 'COMPANY_SENTBYMAIL';
}
if ($triggername == 'CONTRAT_SENTBYMAIL') {
$triggername = 'CONTRACT_SENTBYMAIL';
}
if ($triggername == 'COMMANDE_SENTBYMAIL') {
$triggername = 'ORDER_SENTBYMAIL';
}
if ($triggername == 'FACTURE_SENTBYMAIL') {
$triggername = 'BILL_SENTBYMAIL';
}
if ($triggername == 'EXPEDITION_SENTBYMAIL') {
$triggername = 'SHIPPING_SENTBYMAIL';
}
if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
$triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
}
if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
$triggername = 'BILL_SUPPLIER_SENTBYMAIL';
}
if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
$triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
}
if ($triggername == 'PROJET_SENTBYMAIL') {
$triggername = 'PROJECT_SENTBYMAIL';
}
if (!empty($triggername)) {
// Call trigger
$result = $objectobj2->call_trigger($triggername, $user);
if ($result < 0) {
$error++;
}
// End call triggers
if ($error) {
setEventMessages($db->lasterror(), $errors, 'errors');
dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
}
}
$nbsent++; // Nb of object sent
}
} else {
$langs->load("other");
if ($mailfile->error) {
$resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
$resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
} elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
$resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
} else {
$resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
}
}
}
}
}
}
$resaction .= ($resaction ? '<br>' : $resaction);
$resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
$resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
$resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
$resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
if ($nbsent) {
$action = ''; // Do not show form post if there was at least one successfull sent
//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
setEventMessages($resaction, null, 'mesgs');
} else {
//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
setEventMessages($resaction, null, 'warnings');
}
$action = 'list';
$massaction = '';
}
}
if (!$error && $massaction == 'cancelorders') {
$db->begin();
$nbok = 0;
$orders = GETPOST('toselect', 'array');
foreach ($orders as $id_order) {
$cmd = new Commande($db);
if ($cmd->fetch($id_order) <= 0) {
continue;
}
if ($cmd->statut != Commande::STATUS_VALIDATED) {
$langs->load('errors');
setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
$error++;
break;
} else {
// TODO We do not provide warehouse so no stock change here for the moment.
$result = $cmd->cancel();
}
if ($result < 0) {
setEventMessages($cmd->error, $cmd->errors, 'errors');
$error++;
break;
} else {
$nbok++;
}
}
if (!$error) {
if ($nbok > 1) {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
} else {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
}
$db->commit();
} else {
$db->rollback();
}
}
if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
if (empty($diroutputmassaction)) {
dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
exit;
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
$objecttmp = new $objectclass($db);
$listofobjectid = array();
$listofobjectthirdparties = array();
$listofobjectref = array();
foreach ($toselect as $toselectid) {
$objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
$result = $objecttmp->fetch($toselectid);
if ($result > 0) {
$listofobjectid[$toselectid] = $toselectid;
$thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
$listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
$listofobjectref[$toselectid] = $objecttmp->ref;
}
}
$arrayofinclusion = array();
foreach ($listofobjectref as $tmppdf) {
$arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
}
foreach ($listofobjectref as $tmppdf) {
$arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9\-\_\'\&\.]+\.pdf$'; // To include PDF generated from ODX files
}
$listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
// build list of files with full path
$files = array();
foreach ($listofobjectref as $basename) {
$basename = dol_sanitizeFileName($basename);
foreach ($listoffiles as $filefound) {
if (strstr($filefound["name"], $basename)) {
$files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
break;
}
}
}
// Define output language (Here it is not used because we do only merging existing PDF)
$outputlangs = $langs;
$newlang = '';
if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
$newlang = GETPOST('lang_id', 'aZ09');
}
//elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
// $newlang = $objecttmp->thirdparty->default_lang;
//}
if (!empty($newlang)) {
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
// Create output dir if not exists
dol_mkdir($diroutputmassaction);
// Defined name of merged file
$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
$filename = preg_replace('/\s/', '_', $filename);
// Save merged file
if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
if ($option == 'late') {
$filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
} else {
$filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
}
}
if ($year) {
$filename .= '_'.$year;
}
if ($month) {
$filename .= '_'.$month;
}
if (count($files) > 0) {
$now = dol_now();
$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
$input_files = '';
foreach ($files as $f) {
$input_files .= ' '.escapeshellarg($f);
}
$cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
exec($cmd);
// check if pdftk is installed
if (file_exists($file)) {
dolChmod($file);
$langs->load("exports");
setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
} else {
setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
}
} else {
setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
}
} else {
// Create empty PDF
$formatarray = pdf_getFormat();
$page_largeur = $formatarray['width'];
$page_hauteur = $formatarray['height'];
$format = array($page_largeur, $page_hauteur);
$pdf = pdf_getInstance($format);
if (class_exists('TCPDF')) {
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
}
$pdf->SetFont(pdf_getPDFFont($outputlangs));
if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
$pdf->SetCompression(false);
}
// Add all others
foreach ($files as $file) {
// Charge un document PDF depuis un fichier.
$pagecount = $pdf->setSourceFile($file);
for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $pdf->importPage($i);
$s = $pdf->getTemplatesize($tplidx);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
$pdf->useTemplate($tplidx);
}
}
// Create output dir if not exists
dol_mkdir($diroutputmassaction);
// Defined name of merged file
$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
$filename = preg_replace('/\s/', '_', $filename);
// Save merged file
if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
if ($option == 'late') {
$filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
} else {
$filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
}
}
if ($year) {
$filename .= '_'.$year;
}
if ($month) {
$filename .= '_'.$month;
}
if ($pagecount) {
$now = dol_now();
$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
$pdf->Output($file, 'F');
dolChmod($file);
$langs->load("exports");
setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
} else {
setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
}
}
}
// Remove a file from massaction area
if ($action == 'remove_file') {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$langs->load("other");
$upload_dir = $diroutputmassaction;
$file = $upload_dir.'/'.GETPOST('file');
$ret = dol_delete_file($file);
if ($ret) {
setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
} else {
setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
}
$action = '';
}
// Validate records
if (!$error && $massaction == 'validate' && $permissiontoadd) {
$objecttmp = new $objectclass($db);
if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
$langs->load("errors");
setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
$error++;
}
if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
$langs->load("errors");
setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
$error++;
}
if ($objecttmp->element == 'facture') {
if (!empty($toselect) && !empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
// order $toselect by date
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
$sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
$sql .= " ORDER BY datef";
$resql = $db->query($sql);
if ($resql) {
$toselectnew = [];
while ( !empty($arr = $db->fetch_row($resql))) {
$toselectnew[] = $arr[0];
}
$toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
} else {
dol_print_error($db);
$error++;
}
}
}
if (!$error) {
$db->begin();
$nbok = 0;
foreach ($toselect as $toselectid) {
$result = $objecttmp->fetch($toselectid);
if ($result > 0) {
if (method_exists($objecttmp, 'validate')) {
$result = $objecttmp->validate($user);
} elseif (method_exists($objecttmp, 'setValid')) {
$result = $objecttmp->setValid($user);
} else {
$objecttmp->error = 'No method validate or setValid on this object';
$result = -1;
}
if ($result == 0) {
$langs->load("errors");
setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
$error++;
break;
} elseif ($result < 0) {
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++;
break;
} else {
// validate() rename pdf but do not regenerate
// Define output language
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
$outputlangs = $langs;
$newlang = '';
if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
$newlang = GETPOST('lang_id', 'aZ09');
}
if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
$objecttmp->fetch_thirdparty();
}
if (!empty($objecttmp->thirdparty)) {
$newlang = $objecttmp->thirdparty->default_lang;
}
}
if (!empty($newlang)) {