-
Notifications
You must be signed in to change notification settings - Fork 3
/
envelope_card.php
1986 lines (1675 loc) · 83.2 KB
/
envelope_card.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) 2021 EOXIA <[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/>.
*/
/**
* \file envelope_card.php
* \ingroup envelope
* \brief Page to create/edit/view envelope
*/
// Load Dolibarr environment
$res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
// Try main.inc.php using relative path
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
if (!$res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
require_once './class/envelope.class.php';
require_once './class/letter_sending.class.php';
require_once './class/email_sending.class.php';
require_once './core/modules/doliletter/mod_envelope_standard.php';
require_once './lib/doliletter_envelope.lib.php';
require_once './lib/doliletter.lib.php';
require_once './lib/doliletter_function.lib.php';
global $db, $conf, $langs, $user, $hookmanager;
// Load translation files required by the page
$langs->loadLangs(array("doliletter@doliletter", "other"));
// Get parameters
$id = GETPOST('id', 'int');
$action = GETPOST('action', 'aZ09');
$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
$confirm = GETPOST('confirm', 'alpha');
$cancel = GETPOST('cancel', 'aZ09');
$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'riskcard'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha');
// Initialize technical objects
$object = new Envelope($db);
$contact = new Contact($db);
$project = new Project($db);
$signatory = new EnvelopeSignature($db);
$refEnvelopeMod = new $conf->global->DOLILETTER_ENVELOPE_ADDON();
$extrafields = new ExtraFields($db);
$usertmp = new User($db);
$letter = new LetterSending($db);
$ecmfile = new EcmFiles($db);
$thirdparty = new Societe($db);
$object->fetch($id);
if ($object->fk_contact > 0) {
$linked_contact = $contact;
$linked_contact->fetch($object->fk_contact);
}
$hookmanager->initHooks(array('lettercard', 'globalcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha');
$search = array();
foreach ($object->fields as $key => $val) {
if (GETPOST('search_'.$key, 'alpha')) {
$search[$key] = GETPOST('search_'.$key, 'alpha');
}
}
if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
$upload_dir = $conf->doliletter->multidir_output[$conf->entity ?: $conf->entity]."/envelope/".get_exdir(0, 0, 0, 1, $object);
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
$permissiontoread = $user->rights->doliletter->envelope->read;
$permissiontoadd = $user->rights->doliletter->envelope->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
$permissiontodelete = $user->rights->doliletter->envelope->delete || ($permissiontoadd && isset($object->status));
$permissionnote = $user->rights->doliletter->envelope->write; // Used by the include of actions_setnotes.inc.php
$permissiondellink = $user->rights->envelope->letter->write; // Used by the include of actions_dellink.inc.php
$upload_dir = $conf->doliletter->multidir_output[$conf->entity];
$thirdparty->fetch($object->fk_soc);
// Security check (enable the most restrictive one)
if ($user->socid > 0) accessforbidden();
if ($user->socid > 0) $socid = $user->socid;
if (empty($conf->doliletter->enabled)) accessforbidden();
if (!$permissiontoread) accessforbidden();
/*
* Actions
*/
//cancelling current action
if (GETPOST('cancel')) $action = null;
//action to send Email
$parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if ($action == 'remove_file') {
if (!empty($upload_dir)) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$langs->load("other");
$filetodelete = GETPOST('file', 'alpha');
$file = $upload_dir.'/'.$filetodelete;
$ret = dol_delete_file($file, 0, 0, 0, $object);
if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors');
// Make a redirect to avoid to keep the remove_file into the url that create side effects
$urltoredirect = $_SERVER['REQUEST_URI'];
$urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
$urltoredirect = preg_replace('/action=remove_file&?/', '', $urltoredirect);
header('Location: '.$urltoredirect);
exit;
}
else {
setEventMessages('BugFoundVarUploaddirnotDefined', null, 'errors');
}
}
if (empty($reshook)) {
$error = 0;
$backurlforlist = dol_buildpath('/doliletter/envelope_list.php', 1);
if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
$backtopage = $backurlforlist;
} else {
$backtopage = dol_buildpath('/doliletter/envelope_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
}
}
}
// Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
//include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
// Action to add record
if ($action == 'add' && $permissiontoadd) {
// Get parameters
$society_id = GETPOST('fk_soc');
$content = GETPOST('content', 'restricthtml');
$note_private = GETPOST('note_private');
$note_public = GETPOST('note_public');
$label = GETPOST('label');
$contact_id = GETPOST('fk_contact');
$project_id = GETPOST('fk_project');
// Initialize object
$now = dol_now();
$object->ref = $refEnvelopeMod->getNextValue($object);
$object->ref_ext = 'doliletter_' . $object->ref;
$object->date_creation = $object->db->idate($now);
$object->tms = $now;
$object->import_key = "";
$object->note_private = $note_private;
$object->note_public = $note_public;
$object->label = $label;
$object->fk_soc = $society_id;
$object->fk_contact = $contact_id;
$object->fk_project = $project_id;
$object->content = $content;
$object->entity = $conf->entity ?: 1;
$object->fk_user_creat = $user->id ? $user->id : 1;
// Check parameters
if (empty($society_id) || $society_id == -1) {
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Society')), null, 'errors');
$error++;
}
if (empty($label)) {
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')), null, 'errors');
$error++;
}
if (empty($contact_id)) {
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Contact')), null, 'errors');
$error++;
}
if (!$error) {
$result = $object->create($user, false);
if ($result > 0) {
// Creation envelope OK
$urltogo = str_replace('__ID__', $result, $backtopage);
$urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation
header("Location: " . $urltogo);
exit;
}
else {
// Creation envelope KO
if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
else setEventMessages($object->error, null, 'errors');
}
} else {
$action = 'create';
}
}
// Action to update record
if ($action == 'update' && $permissiontoadd) {
$society_id = GETPOST('fk_soc');
$content = GETPOST('content', 'restricthtml');
$label = GETPOST('label');
$contact_id = GETPOST('fk_contact');
$project_id = GETPOST('fk_project');
$object->label = $label;
$object->fk_soc = $society_id;
$object->content = $content;
$object->fk_contact = $contact_id;
$object->fk_project = $project_id;
$object->fk_user_creat = $user->id ? $user->id : 1;
if (!$error) {
$result = $object->update($user, false);
if ($result > 0) {
$signatory->deleteSignatoriesSignatures($object->id, 0);
$object->setStatusCommon($user, 0);
$urltogo = str_replace('__ID__', $result, $backtopage);
$urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation
header("Location: " . $urltogo);
exit;
}
else
{
if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
else setEventMessages($object->error, null, 'errors');
}
} else {
$action = 'edit';
}
}
if ($action == 'confirm_delete' && GETPOST("confirm") == "yes")
{
$object->setStatusCommon($user, -1);
$urltogo = DOL_URL_ROOT . '/custom/doliletter/envelope_list.php';
header("Location: " . $urltogo);
exit;
}
if ($action == 'confirm_setLocked' && GETPOST('confirm') == 'yes') {
$extintervenant_id = $object->fk_contact;
//Check email of intervenants
$contact->fetch($extintervenant_id);
if (!dol_strlen($contact->email)) {
setEventMessages($langs->trans('ErrorNoEmailForExtIntervenant', $langs->transnoentitiesnoconv('ExtIntervenant')), null, 'errors');
$error++;
}
if (!$error) {
$result = $signatory->setSignatory($object->id,'socpeople', array($extintervenant_id), 'E_RECEIVER', 1);
if ($result > 0) {
$contact->fetch($extintervenant_id);
setEventMessages($langs->trans('AddAttendantMessage') . ' ' . $contact->firstname . ' ' . $contact->lastname, array());
$object->call_trigger('ENVELOPE_LOCK', $user);
// Creation attendant OK
$object->setStatusCommon($user, 2);
$urltogo = str_replace('__ID__', $result, $backtopage);
$urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation
header("Location: " . $urltogo);
exit;
}
else
{
// Creation attendant KO
if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
else setEventMessages($object->error, null, 'errors');
}
}
}
// Actions when linking object each other
include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
// Actions when printing a doc from card
include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
// Action to move up and down lines of object
//include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';
// Action to build doc
// include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
if ($action == 'builddoc' && $permissiontoadd) {
if (is_numeric(GETPOST('model', 'alpha'))) {
$error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model"));
} else {
// Reload to get all modified line records and be ready for hooks
$ret = $object->fetch($id);
$ret = $object->fetch_thirdparty();
/*if (empty($object->id) || ! $object->id > 0)
{
dol_print_error('Object must have been loaded by a fetch');
exit;
}*/
// Save last template used to generate document
if (GETPOST('model', 'alpha')) {
$object->setDocModel($user, GETPOST('model', 'alpha'));
}
// Special case to force bank account
//if (property_exists($object, 'fk_bank'))
//{
if (GETPOST('fk_bank', 'int')) {
// this field may come from an external module
$object->fk_bank = GETPOST('fk_bank', 'int');
} elseif (!empty($object->fk_account)) {
$object->fk_bank = $object->fk_account;
}
//}
$outputlangs = $langs;
$newlang = '';
if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
$newlang = GETPOST('lang_id', 'aZ09');
}
if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) {
$newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ...
}
if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) {
$newlang = $object->default_lang; // for thirdparty
}
if (!empty($newlang)) {
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
// To be sure vars is defined
if (empty($hidedetails)) {
$hidedetails = 0;
}
if (empty($hidedesc)) {
$hidedesc = 0;
}
if (empty($hideref)) {
$hideref = 0;
}
if (empty($moreparams)) {
$moreparams = null;
}
$result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
if ($result <= 0) {
setEventMessages($object->error, $object->errors, 'errors');
$action = '';
} else {
if ($conf->global->DOLILETTER_SHOW_DOCUMENTS_ON_PUBLIC_INTERFACE) {
$filedir = $conf->doliletter->dir_output.'/'.$object->element.'/'.$object->ref;
$filelist = dol_dir_list($filedir, 'files');
if (!empty($filelist)) {
foreach ($filelist as $file) {
if (!preg_match('/specimen/', $file['name'])) {
$fileurl = $file['fullname'];
$filename = $file['name'];
}
}
}
$ecmfile->fetch(0, '', 'doliletter/envelope/'.$object->ref.'/'.$filename, '', '', 'doliletter_envelope', $id);
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$ecmfile->share = getRandomPassword(true);
$ecmfile->update($user);
}
if (empty($donotredirect)) { // This is set when include is done by bulk action "Bill Orders"
setEventMessages($langs->trans("FileGenerated"), null);
$urltoredirect = $_SERVER['REQUEST_URI'];
$urltoredirect = preg_replace('/#builddoc$/', '', $urltoredirect);
$urltoredirect = preg_replace('/action=builddoc&?/', '', $urltoredirect); // To avoid infinite loop
header('Location: '.$urltoredirect.'#builddoc');
exit;
}
}
}
}
// Actions to send emails
$triggersendname = 'DOLILETTER_ENVELOPE_SENTBYMAIL';
$autocopy = 'MAIN_MAIL_AUTOCOPY_ENVELOPE_TO';
$trackid = 'envelope'.$object->id;
/*
* Send mail
*/
if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST['removAll'] && !$_POST['removedfile'] && !$_POST['cancel'] && !$_POST['modelselected']) {
if (empty($trackid)) {
$trackid = GETPOST('trackid', 'aZ09');
}
$subject = '';
$actionmsg = '';
$actionmsg2 = '';
$langs->load('mails');
if (is_object($object)) {
$result = $object->fetch($id);
$sendtosocid = 0; // Id of related thirdparty
if (method_exists($object, "fetch_thirdparty") && !in_array($object->element, array('member', 'user', 'expensereport', 'societe', 'contact'))) {
$resultthirdparty = $object->fetch_thirdparty();
$thirdparty = $object->thirdparty;
if (is_object($thirdparty)) {
$sendtosocid = $thirdparty->id;
}
} elseif ($object->element == 'member' || $object->element == 'user') {
$thirdparty = $object;
if ($object->socid > 0) {
$sendtosocid = $object->socid;
}
} elseif ($object->element == 'expensereport') {
$tmpuser = new User($db);
$tmpuser->fetch($object->fk_user_author);
$thirdparty = $tmpuser;
if ($object->socid > 0) {
$sendtosocid = $object->socid;
}
} elseif ($object->element == 'societe') {
$thirdparty = $object;
if (is_object($thirdparty) && $thirdparty->id > 0) {
$sendtosocid = $thirdparty->id;
}
} elseif ($object->element == 'contact') {
$contact = $object;
if ($contact->id > 0) {
$contact->fetch_thirdparty();
$thirdparty = $contact->thirdparty;
if (is_object($thirdparty) && $thirdparty->id > 0) {
$sendtosocid = $thirdparty->id;
}
}
} else {
dol_print_error('', "Use actions_sendmails.in.php for an element/object '".$object->element."' that is not supported");
}
if (is_object($hookmanager)) {
$parameters = array();
$reshook = $hookmanager->executeHooks('initSendToSocid', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
}
} else {
$thirdparty = $mysoc;
}
if ($result > 0) {
$sendto = '';
$sendtocc = '';
$sendtobcc = '';
$sendtoid = array();
$sendtouserid = array();
$sendtoccuserid = array();
// Define $sendto
$receiver = $_POST['receiver'];
if (!is_array($receiver)) {
if ($receiver == '-1') {
$receiver = array();
} else {
$receiver = array($receiver);
}
}
$tmparray = array();
if (trim($_POST['sendto'])) {
// Recipients are provided into free text field
$tmparray[] = trim($_POST['sendto']);
}
if (trim($_POST['tomail'])) {
// Recipients are provided into free hidden text field
$tmparray[] = trim($_POST['tomail']);
}
if (count($receiver) > 0) {
// Recipient was provided from combo list
foreach ($receiver as $key => $val) {
if ($val == 'thirdparty') { // Key selected means current third party ('thirdparty' may be used for current member or current user too)
$tmparray[] = dol_string_nospecial($thirdparty->getFullName($langs), ' ', array(",")).' <'.$thirdparty->email.'>';
} elseif ($val == 'contact') { // Key selected means current contact
$tmparray[] = dol_string_nospecial($contact->getFullName($langs), ' ', array(",")).' <'.$contact->email.'>';
$sendtoid[] = $contact->id;
} elseif ($val) { // $val is the Id of a contact
$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
$sendtoid[] = ((int) $val);
}
}
}
if (!empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
$receiveruser = $_POST['receiveruser'];
if (is_array($receiveruser) && count($receiveruser) > 0) {
$fuserdest = new User($db);
foreach ($receiveruser as $key => $val) {
$tmparray[] = $fuserdest->user_get_property($val, 'email');
$sendtouserid[] = $val;
}
}
}
$sendto = implode(',', $tmparray);
// Define $sendtocc
$receivercc = $_POST['receivercc'];
if (!is_array($receivercc)) {
if ($receivercc == '-1') {
$receivercc = array();
} else {
$receivercc = array($receivercc);
}
}
$tmparray = array();
if (trim($_POST['sendtocc'])) {
$tmparray[] = trim($_POST['sendtocc']);
}
if (count($receivercc) > 0) {
foreach ($receivercc as $key => $val) {
if ($val == 'thirdparty') { // Key selected means current thirdparty (may be usd for current member or current user too)
// Recipient was provided from combo list
$tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>';
} elseif ($val == 'contact') { // Key selected means current contact
// Recipient was provided from combo list
$tmparray[] = dol_string_nospecial($contact->name, ' ', array(",")).' <'.$contact->email.'>';
//$sendtoid[] = $contact->id; TODO Add also id of contact in CC ?
} elseif ($val) { // $val is the Id of a contact
$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
//$sendtoid[] = ((int) $val); TODO Add also id of contact in CC ?
}
}
}
if (!empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
$receiverccuser = $_POST['receiverccuser'];
if (is_array($receiverccuser) && count($receiverccuser) > 0) {
$fuserdest = new User($db);
foreach ($receiverccuser as $key => $val) {
$tmparray[] = $fuserdest->user_get_property($val, 'email');
$sendtoccuserid[] = $val;
}
}
}
$sendtocc = implode(',', $tmparray);
if (dol_strlen($sendto)) {
// Define $urlwithroot
$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
$langs->load("commercial");
$reg = array();
$fromtype = GETPOST('fromtype', 'alpha');
if ($fromtype === 'robot') {
$from = dol_string_nospecial($conf->global->MAIN_MAIL_EMAIL_FROM, ' ', array(",")).' <'.$conf->global->MAIN_MAIL_EMAIL_FROM.'>';
} elseif ($fromtype === 'user') {
$from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
} elseif ($fromtype === 'company') {
$from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")).' <'.$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';
$sql .= ' 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 = dol_string_nospecial($_POST['fromname'], ' ', array(",")).' <'.$_POST['frommail'].'>';
}
$replyto = dol_string_nospecial($_POST['replytoname'], ' ', array(",")).' <'.$_POST['replytomail'].'>';
$message = GETPOST('message', 'restricthtml');
$subject = GETPOST('subject', 'restricthtml');
// Make a change into HTML code to allow to include images from medias directory with an external reabable URL.
// <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&entity=1&file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
// become
// <img alt="" src="'.$urlwithroot.'viewimage.php?modulepart=medias&entity=1&file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
$message = preg_replace('/(<img.*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/>)/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $message);
$sendtobcc = GETPOST('sendtoccc');
// Autocomplete the $sendtobcc
// $autocopy can be MAIN_MAIL_AUTOCOPY_PROPOSAL_TO, MAIN_MAIL_AUTOCOPY_ORDER_TO, MAIN_MAIL_AUTOCOPY_INVOICE_TO, MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO...
if (!empty($autocopy)) {
$sendtobcc .= (empty($conf->global->$autocopy) ? '' : (($sendtobcc ? ", " : "").$conf->global->$autocopy));
}
$deliveryreceipt = $_POST['deliveryreceipt'];
if ($action == 'send' || $action == 'relance') {
$actionmsg2 = $langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from, 4, 0, 1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto, 4, 0, 1);
if ($message) {
$actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
if ($sendtocc) {
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc));
}
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
$actionmsg = dol_concatdesc($actionmsg, $message);
}
}
// Create form object
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
$formmail->trackid = $trackid; // $trackid must be defined
$attachedfiles = $formmail->get_attached_files();
$filepath = $attachedfiles['paths'];
$filename = $attachedfiles['names'];
$mimetype = $attachedfiles['mimes'];
// Make substitution in email content
$substitutionarray = getCommonSubstitutionArray($langs, 0, null, $object);
$substitutionarray['__EMAIL__'] = $sendto;
$substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.urlencode($object->thirdparty->tag).'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>' : '';
$parameters = array('mode'=>'formemail');
complete_substitutions_array($substitutionarray, $langs, $object, $parameters);
$subject = make_substitutions($subject, $substitutionarray);
$message = make_substitutions($message, $substitutionarray);
if (is_object($object) && method_exists($object, 'makeSubstitution')) {
$subject = $object->makeSubstitution($subject);
$message = $object->makeSubstitution($message);
}
// Send mail (substitutionarray must be done just before this)
if (empty($sendcontext)) {
$sendcontext = 'standard';
}
$mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext);
if ($mailfile->error) {
setEventMessages($mailfile->error, $mailfile->errors, 'errors');
$action = 'presend';
} else {
$result = $mailfile->sendfile();
if ($result) {
// Initialisation of datas of object to call trigger
if (is_object($object)) {
if (empty($actiontypecode)) {
$actiontypecode = 'AC_OTH_AUTO'; // Event insert into agenda automatically
}
$object->socid = $sendtosocid; // To link to a company
$object->sendtoid = $sendtoid; // To link to contact-addresses. This is an array.
$object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
$object->actionmsg = $actionmsg; // Long text (@todo Replace this with $message, we already have details of email in dedicated properties)
$object->actionmsg2 = $actionmsg2; // Short text ($langs->transnoentities('MailSentBy')...);
$object->trackid = $trackid;
$object->fk_element = $object->id;
$object->elementtype = $object->element;
if (is_array($attachedfiles) && count($attachedfiles) > 0) {
$object->attachedfiles = $attachedfiles;
}
if (is_array($sendtouserid) && count($sendtouserid) > 0 && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
$object->sendtouserid = $sendtouserid;
}
$object->email_msgid = $mailfile->msgid; // @todo Set msgid into $mailfile after sending
$object->email_from = $from;
$object->email_subject = $subject;
$object->email_to = $sendto;
$object->email_tocc = $sendtocc;
$object->email_tobcc = $sendtobcc;
$object->email_msgid = $mailfile->msgid;
$object->message = $message;
// Call of triggers (you should have set $triggersendname to execute trigger. $trigger_name is deprecated)
if (!empty($triggersendname) || !empty($trigger_name)) {
// Call trigger
$result = $object->call_trigger(empty($triggersendname) ? $trigger_name : $triggersendname, $user);
if ($result < 0) {
$error++;
}
// End call triggers
if ($error) {
setEventMessages($object->error, $object->errors, 'errors');
} else {
$object->setStatusCommon($user, 4);
$signatory->fetchSignatory('E_RECEIVER', $id);
$signatory->last_email_sent_date = dol_now();
$signatory->update($user);
}
}
// End call of triggers
}
// Redirect here
// This avoid sending mail twice if going out and then back to page
$mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2));
setEventMessages($mesg, null, 'mesgs');
$moreparam = '';
if (isset($paramname2) || isset($paramval2)) {
$moreparam .= '&'.($paramname2 ? $paramname2 : 'mid').'='.$paramval2;
}
header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname ? $paramname : 'id').'='.(is_object($object) ? $object->id : '').$moreparam);
exit;
} else {
$langs->load("other");
$mesg = '<div class="error">';
if ($mailfile->error) {
$mesg .= $langs->transnoentities('ErrorFailedToSendMail', dol_escape_htmltag($from), dol_escape_htmltag($sendto));
$mesg .= '<br>'.$mailfile->error;
} else {
$mesg .= $langs->transnoentities('ErrorFailedToSendMail', dol_escape_htmltag($from), dol_escape_htmltag($sendto));
if (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
$mesg .= '<br>Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
} else {
$mesg .= '<br>Unkown Error, please refers to your administrator';
}
}
$mesg .= '</div>';
setEventMessages($mesg, null, 'warnings');
$action = 'presend';
}
}
} else {
$langs->load("errors");
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("MailTo")), null, 'warnings');
dol_syslog('Try to send email with no recipient defined', LOG_WARNING);
$action = 'presend';
}
} else {
$langs->load("errors");
setEventMessages($langs->trans('ErrorFailedToReadObject', $object->element), null, 'errors');
dol_syslog('Failed to read data of object id='.$object->id.' element='.$object->element);
$action = 'presend';
}
}
if ($action == 'lettersend') {
$error = 0;
$receiver = GETPOST('receiver');
$lettercode = GETPOST('lettercode');
$letter->fk_envelope = $object->id;
$letter->date_creation = $letter->db->idate($now);
$letter->status = 1;
$letter->fk_user = $user->id;
$letter->entity = $object->entity;
$letter->sender_fullname = $user->firstname . ' ' . $user->lastname;
$letter->fk_socpeople = $receiver;
$contact->fetch($receiver);
$letter->recipient_address = $contact->address;
$letter->contact_fullname = $contact->firstname . ' ' . $contact->lastname;
$letter->letter_code = $lettercode;
$result = $letter->create($user);
if ($result > 0) {
$object->setStatusCommon($user, 3);
$object->call_trigger('ENVELOPE_LETTER', $user);
// Submit file
if ( ! empty($conf->global->MAIN_UPLOAD_DOC)) {
if ( ! empty($_FILES)) {
if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name'];
else $userfiles = array($_FILES['userfile']['tmp_name']);
foreach ($userfiles as $key => $userfile) {
if (empty($_FILES['userfile']['tmp_name'][$key])) {
$error++;
if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
}
}
}
if ( ! $error) {
$filedir = $upload_dir . '/' . $object->element . '/' . $object->ref;
if (!is_dir($filedir)) {
dol_mkdir($filedir);
}
$TNdir = $filedir . '/trackingnumber';
if (!is_dir($TNdir)) {
dol_mkdir($TNdir);
}
$LFdir = $TNdir . '/uploaded_file';
if (!is_dir($LFdir)) {
dol_mkdir($LFdir);
}
$result = dol_add_file_process($LFdir, 0, 1, 'userfile', '', null, '', 0, $object);
}
}
}
$forcebuilddoc = true;
if ($forcebuilddoc) // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation
{
if (method_exists($object, 'generateDocument'))
{
$result = $object->generateDocument('nerio', $langs, $hidedetails, $hidedesc, $hideref);
if ($result < 0) {
dol_print_error($db, $object->error, $object->errors);
exit();
}
if ($conf->global->DOLILETTER_SHOW_DOCUMENTS_ON_PUBLIC_INTERFACE) {
$filedir = $conf->doliletter->dir_output.'/'.$object->element.'/'.$object->ref . '/trackingnumber';
$filelist = dol_dir_list($filedir, 'files');
if (!empty($filelist)) {
foreach ($filelist as $file) {
if (!preg_match('/specimen/', $file['name'])) {
$fileurl = $file['fullname'];
$filename = $file['name'];
}
}
}
$ecmfile->fetch(0, '', 'doliletter/envelope/'.$object->ref.'/trackingnumber/'.$filename, '', '', 'doliletter_envelope', $id);
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$ecmfile->share = getRandomPassword(true);
$ecmfile->update($user);
}
}
}
}
unset($action);
}
if ($action == 'stockTmpFile') {
$type = GETPOST('type');
if ( ! empty($conf->global->MAIN_UPLOAD_DOC)) {
if ( ! empty($_FILES)) {
if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name'];
else $userfiles = array($_FILES['userfile']['tmp_name']);
foreach ($userfiles as $key => $userfile) {
if (empty($_FILES['userfile']['tmp_name'][$key])) {
$error++;
if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
}
}
}
if ( ! $error) {
$filedir = $upload_dir . '/' . $object->element . '/' . $object->ref;
if (!is_dir($filedir)) {
dol_mkdir($filedir);
}
$SPDir = $filedir . '/' . strtolower($type);
if (!is_dir($SPDir)) {
dol_mkdir($SPDir);
}
$SP_sub_dir = $SPDir . '/uploaded_file';
if (!is_dir($SP_sub_dir)) {
dol_mkdir($SP_sub_dir);
}
$SP_tmp_dir = $SP_sub_dir . '/tmp';
if (!is_dir($SP_tmp_dir)) {
dol_mkdir($SP_tmp_dir);
}
$tmp_files = dol_dir_list($SP_tmp_dir);
if (!empty($tmp_files)) {
foreach ($tmp_files as $tmp_file) {
unlink($tmp_file['fullname']);
}
}
$result = dol_add_file_process($SP_tmp_dir, 0, 1, 'userfile', '', null, '', 0, $object);
}
}
}
}
if ($action == 'addAcknowledgementReceipt') {
$filedir = $upload_dir . '/' . $object->element . '/' . $object->ref . '/acknowledgementreceipt/uploaded_file';
$tmp_filedir = $filedir . '/tmp';
$tmp_files = dol_dir_list($tmp_filedir);
if (!empty($tmp_files)) {
foreach ($tmp_files as $tmp_file) {
$result = rename($tmp_file['fullname'], $filedir.'/'. $tmp_file['name']);
// Submit file
if ($result > 0) {
// Presend form
$modelmail = 'envelope';
$defaulttopic = 'InformationMessage';
$diroutput = $upload_dir . '/' . $object->element;
$trackid = 'envelope'.$object->id;
$ref = dol_sanitizeFileName($object->ref);
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$fileparams = dol_most_recent_file($diroutput.'/'.$ref, '');
$file = $fileparams['fullname'];
// Build document if it not exists
$allspecimen = true;
$fileslist = dol_dir_list($fileparams['path']);
foreach($fileslist as $item) {
if (!preg_match('/specimen/', $item['name'])){
$allspecimen = false;
}
}
$needcreate = empty($file) || $allspecimen;
$forcebuilddoc = true;
$object->call_trigger('ENVELOPE_ACKNOWLEDGEMENT_RECEIPT', $user);
$object->setStatusCommon($user, 6);
if ($forcebuilddoc) // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation
{
if (method_exists($object, 'generateDocument'))
{
$result = $object->generateDocument('deimos', $langs, $hidedetails, $hidedesc, $hideref);
if ($result < 0) {
dol_print_error($db, $object->error, $object->errors);
exit();
}
if ($conf->global->DOLILETTER_SHOW_DOCUMENTS_ON_PUBLIC_INTERFACE) {
$filedir = $conf->doliletter->dir_output.'/'.$object->element.'/'.$object->ref . '/acknowledgementreceipt';
$filelist = dol_dir_list($filedir, 'files');
if (!empty($filelist)) {
foreach ($filelist as $file) {
if (!preg_match('/specimen/', $file['name'])) {