-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmailing.php
1809 lines (1483 loc) · 62.6 KB
/
mailing.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 notice
*
* (c) 2003-2017 Renzo Lauper ([email protected])
* (c) 2019-2020 Daniel Lerch
* All rights reserved
*
* This script is part of the kOOL project. The kOOL project 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 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
* kOOL 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
// return warning if called from console
if (isset($argc) && $argc >= 1) {
if ($argv[1] == '-t') {
$mail_id_in = trim($argv[2]);
$recipient_in = trim($argv[3]);
if (!$mail_id_in || !$recipient_in || !is_numeric($mail_id_in)) {
die("This script can only be called from console for testing purposes. Usage >> php mailing.php -t <mail_id> <recipient_mail|recipient_id> \n");
} else {
$ko_path = './';
require_once('inc/ko.inc');
print (ko_mailing_main (true, $mail_id_in, $recipient_in)."\n");
exit;
}
} else {
die("This script can only be called from console for testing purposes. Usage >> php mailing.php -t <mail_id> <recipient_mail|recipient_id> \n");
}
}
// Constants: Mailing status
define('MAILING_STATUS_OPEN', 1);
define('MAILING_STATUS_CONFIRMED', 2);
define('MAILING_STATUS_SENT', 3);
define('MAILING_MAX_RECIPIENTS_FOR_SUMMARY', 20);
//Contants: Errors
define('MAILING_ERROR_INVALID_GROUP_ID', 1);
define('MAILING_ERROR_INVALID_SMALLGROUP_ID', 2);
define('MAILING_ERROR_INVALID_SENDER', 3);
define('MAILING_ERROR_INVALID_CODE', 4);
define('MAILING_ERROR_NO_ALIAS_FOUND', 5);
define('MAILING_ERROR_INVALID_RECIPIENT', 6);
define('MAILING_ERROR_NON_UNIQUE_ALIAS', 7);
define('MAILING_ERROR_TOO_MANY_RECIPIENTS', 8);
define('MAILING_ERROR_NO_ACCESS', 9);
define('MAILING_ERROR_GROUP_NO_ACCESS', 10);
define('MAILING_ERROR_SMALLGROUP_NO_ACCESS', 11);
define('MAILING_ERROR_MYLIST_NO_ACCESS', 12);
define('MAILING_ERROR_ONLY_ALIAS', 13);
define('MAILING_ERROR_LEUTE_NO_ACCESS', 14);
define('MAILING_ERROR_CODE_ALREADY_CONFIRMED', 15);
define('MAILING_ERROR_GROUP_NO_ACCESS_EMAIL', 16);
define('MAILING_ERROR_MODERATION_EMAIL', 17);
define('MAILING_ERROR_MYLIST_EMPTY', 18);
define('MAILING_ERROR_FILTER_EMPTY', 19);
define('MAILING_ERROR_INVALID_GROUP_ROLE_ID', 20);
define('MAILING_ERROR_NO_RECIPIENTS', 21);
define('MAILING_ERROR_CRM_NO_USER', 22);
define('MAILING_ERROR_CRM_NO_ACCESS', 23);
define('MAILING_ERROR_CRM_NO_PROJECT', 24);
define('MAILING_ERROR_CRM_PROJECT_NO_ACCESS', 25);
define('MAILING_ERROR_BCC_HINT', 26);
function ko_mailing_main ($test = false, $mail_id_in = null, $recipient_in = null) {
global $MAILING_PARAMETER,$BASE_PATH,$domain,$edit_base_link,$done_error_mails,$return_path,$imap,$max_recipients,$ko_menu_akt,$access,$verbose;
error_reporting(E_ALL);
define ('CRLF', "\r\n");
//Get ko_path from server settings
$ko_path = $BASE_PATH;
if(isset($_POST['GLOBALS']) || isset($_GET['GLOBALS'])) {
ko_log('mailing_error', 'You cannot set the GLOBALS-array from outside this script.');
return;
}
$ko_menu_akt = 'mailing';
//Basic checks
if(defined('ALLOW_SEND_EMAIL') && ALLOW_SEND_EMAIL === FALSE) return;
if(!is_array($MAILING_PARAMETER) || sizeof($MAILING_PARAMETER) < 3) return;
//Get mailing parameters from ko-config and ko_settings
$host = $MAILING_PARAMETER['host'];
$port = $MAILING_PARAMETER['port'];
$user = $MAILING_PARAMETER['user'];
$pass = $MAILING_PARAMETER['pass'];
$domain = $MAILING_PARAMETER['domain'];
$ssl = $MAILING_PARAMETER['ssl'];
$cert = $MAILING_PARAMETER['validate-cert'];
$folder = $MAILING_PARAMETER['folder'];
$edit_base_link = $MAILING_PARAMETER['edit_base_link'];
$bulk_header = $MAILING_PARAMETER['set_bulk_header'];
//Number of email to be sent by cycle
$mails_per_cycle = ko_get_setting('mailing_mails_per_cycle');
if($mails_per_cycle < 1) $mails_per_cycle = 30;
if($mails_per_cycle > 100) $mails_per_cycle = 100;
//Maximum number of recipients
$max_recipients = ko_get_setting('mailing_max_recipients');
if($max_recipients == '') $max_recipients = 0;
//Set Return-Path for sent emails
if(check_email($MAILING_PARAMETER['return_path'])) {
$return_path = '-f'.$MAILING_PARAMETER['return_path'];
} else if($MAILING_PARAMETER['return_path'] == 'USER') {
$return_path = 'USER';
} else if(defined('EMAIL_SET_RETURN_PATH') && EMAIL_SET_RETURN_PATH == TRUE) {
$return_path = '-f'.ko_get_setting('info_email');
} else {
$return_path = '';
}
require($ko_path . 'inc/class.rawSmtpMailer.php');
$mailer = new RawSmtpMailer(true);
/** TESTING
* Allows to send a stored mailing email to a specified recipient
* Call with php5 mailing.php test ID RECIPIENT
* Where ID is the ID of the mailing email from DB table ko_mailing_mails and RECIPIENT is the email address to send this email to
*/
if($test) {
$mail_id = $mail_id_in;
$recipient = $recipient_in;
if (is_numeric($recipient)) {
$rec = db_select_data('ko_leute', "WHERE `id` = '{$recipient}'", '*', '', '', TRUE, TRUE);
if (!$rec ) {
return "ERROR: Invalid recipient ID: {$recipient}.\n";
}
$recipient = $rec ['email'];
$recipient_id = $rec ['id'];
} else {
$rec = FALSE;
$recipient_id = 1;
}
if(!$mail_id || !$recipient || !check_email($recipient)) {
return "ERROR: Invalid mailID or recipient.\nCall as follows: php5 mailing.php test ID RECIPIENT.\n";
}
$mail = db_select_data('ko_mailing_mails', "WHERE `id` = '$mail_id'", '*', '', '', TRUE);
if($mail_id != $mail['id'] || $mail['id'] <= 0) {
return "ERROR: Invalid mailID. Could not find any mailing with the given ID.\n";
}
//Find quoted-printable in header
if(FALSE !== strpos(strtolower($mail['header']), 'content-transfer-encoding: quoted-printable')) $qp = TRUE;
else $qp = FALSE;
//Find utf-8 encoding. If set then encode recipient's name
//if(FALSE !== strpos(strtolower($mail['header']), 'charset=utf-8')) $utf8 = TRUE;
//else $utf8 = FALSE;
if (trim(ko_get_setting('mailing_from_email'))) {
$sender = trim(ko_get_setting('mailing_from_email'));
} else {
$sender = $mail['from'];
}
$to = "To: ".mb_encode_mimeheader($rec['name'], 'UTF-8', 'Q')." <".$recipient.">" . CRLF;
$subject = "Subject: " . ko_mailing_markers($mail['subject'], $recipient_id, $recipient) . CRLF;
$message = ko_emailtext(trim($mail['header'])).$to.$subject.CRLF.ko_emailtext(ko_mailing_markers($mail['body'], $recipient_id, $recipient, $qp));
$mailer->removeAddresses();
try {
$mailer->setSender($sender);
$mailer->addAddress($recipient);
$mailer->setMessage($message);
$mailer->send();
} catch (Exception $e) {
return('ERROR: mailing_smtp_error: '. $e->getMessage());
}
return "okay";
}//if(TEST)
//Create POP3 connection
$ssl = ($ssl==true) ? '/ssl' : '';
$cert = ($cert==true) ? '' : '/novalidate-cert';
$folder = $folder ? $folder : 'INBOX';
$imap = imap_open('{'."$host:$port/pop3$ssl$cert"."}$folder",$user,$pass);
//Exit if connection to IMAP failed
if($imap == FALSE) {
$last_error = imap_last_error();
$comment = getLL('mailing_error_imap') . (($last_error == false) ? getLL('mailing_error_imap_default') : $last_error);
if ($verbose) print $comment . PHP_EOL;
db_insert_data('ko_log', array('type' => 'mailing_error', 'comment' => getLL('mailing_error_imap'), 'date' => date('Y-m-d H:i:s')));
return;
}
$done_error_mails = array();
// try to extract BCC recipients for these address prefixes:
$bcc_prefixes = array('crm');
// handler function for mails
// each handler function is called for each message, regardless of the return value of previous handlers
// if all handlers return false, an error is reported (as email reply)
$mail_handlers = array(
'ko_mailing_handle_mail_crm',
'ko_mailing_handle_mail_group',
);
//Get emails from pop account
$imap_status = imap_check($imap);
$num_mails = $imap_status->Nmsgs;
if($num_mails > 0) {
ko_log('mailing_started', "There are $num_mails unread messages for further processing");
//Get mails
$mails = array();
$response = imap_fetch_overview($imap,'1:'.$num_mails);
foreach ($response as $msg) $mails[$msg->msgno] = (array)$msg;
//Group mail receivers by message_id
//If one mail has two or more recipients, the same mail will be stored multiple times, so we group all receivers by message_id
//For each mail all recipients will be handled below, so no need to work through all copies
$unique_mails = array();
foreach($mails as $mail) {
if ($verbose) print "Parsing message from $mail[from]..." . PHP_EOL;
$rawheader = imap_fetchheader($imap, $mail['msgno']);
if(!isset($unique_mails[$mail['message_id']])) {
//Get all recipients of this email
$header = imap_rfc822_parse_headers($rawheader);
$mail_recipients = array();
foreach($header->to as $obj) {
$mail_recipients['to'][] = format_userinput($obj->mailbox.'@'.$obj->host, 'email');
}
foreach($header->cc as $obj) {
$mail_recipients['cc'][] = format_userinput($obj->mailbox.'@'.$obj->host, 'email');
}
$unique_mails[$mail['message_id']] = array(
'mail' => $mail,
'recipients' => $mail_recipients,
);
} else {
$mail_recipients = $unique_mails[$mail['message_id']];
}
// try to resolve bcc receiver address from bcc header
foreach(preg_split("/\\n(?!\\s)/",$rawheader) as $headerLine) {
list($name,$value) = explode(':',$headerLine,2);
if(in_array(strtolower($name),array('envelope-to','x-envelope-to','delivered-to','x-delivered-to'))) {
foreach($bcc_prefixes as $prefix) {
if(preg_match('/^([0-9a-z]+-)?('.preg_quote($prefix).'([^@]+)@'.preg_quote($domain).')$/i',trim($value),$matches)) {
$mail_address = $matches[2];
foreach($unique_mails[$mail['message_id']]['recipients'] as $recipients) {
if(in_array($mail_address,$recipients)) {
continue 2;
}
}
$unique_mails[$mail['message_id']]['recipients']['bcc'][] = format_userinput($mail_address, 'email');
}
}
}
}
}
foreach($unique_mails as $unique_mail) {
$mail = $unique_mail['mail'];
$mail_recipients = $unique_mail['recipients'];
//Check sender email and find corresponding kOOL login
$access = array();
$login_id = ko_mailing_get_sender_login($mail['from']);
if($login_id) {
if ($verbose) print "Found a login (id $login_id) for $mail[from]" . PHP_EOL;
ko_get_login($login_id,$login);
} else {
$login = null;
}
$handeled = false;
foreach($mail_handlers as $handler) {
$handeled |= $handler($mail,$mail_recipients,$login);
}
//None of the email addresses have been recognized and processed: Return failure notice
if(!$handeled) {
if(preg_match('/^(x-)?envelope-to:\s*([^\s@]*@'.preg_quote($domain).')\s*$/im',$rawheader,$m)) {
if(!in_array($m[2],$mail_recipients['to']) && !in_array($m[2],$mail_recipients['cc'])) {
ko_mailing_error($login, MAILING_ERROR_BCC_HINT, $mail, $m[2]);
$handeled = true;
}
}
if(!$handeled) {
foreach($mail_recipients as $recipients) {
foreach($recipients as $recipient) {
if(substr($recipient,-strlen($domain)-1) == '@'.$domain) {
$to = $recipient;
break 2;
}
}
}
ko_mailing_error($login, MAILING_ERROR_INVALID_RECIPIENT, $mail, $to);
}
}
//Delete message after it has been processed
if ($verbose) print "Processing finished. Deleting message $mail[message_id]..." . PHP_EOL;
imap_delete($imap, $mail['msgno']);
}//foreach(mails as mail)
}
//Close connection and expunge
imap_close($imap, CL_EXPUNGE);
ko_mailing_send_mails($mailer,$mails_per_cycle);
//Check for old non-confirmed mails and delete them
$limit = add2date(date('Y-m-d'), 'day', '-5', TRUE).' 00:00:00';
$old_mails = db_select_data('ko_mailing_mails', "WHERE `status` = '".MAILING_STATUS_OPEN."' AND `crdate` < '".$limit."'",'*, NULL AS body');
foreach($old_mails as $mail) {
$log = '';
$logcols = array('id', 'crdate', 'recipient', 'from', 'subject');
foreach($logcols as $c) $log .= (getLL('mailing_header_'.$c) ? getLL('mailing_header_'.$c) : $c).': '.$mail[$c].', ';
db_insert_data('ko_log', array('type' => 'mailing_delete_old', 'comment' => substr($log, 0, -2), 'user_id' => $mail['user_id'], 'date' => date('Y-m-d H:i:s')));
db_delete_data('ko_mailing_mails', "WHERE `id` = '".$mail['id']."'");
}
}//ko_mailing_main()
function ko_mailing_handle_mail_group(&$mail,$mail_recipients,$login) {
global $access,$domain,$imap,$sender_email,$RECTYPES;
if($login) {
$no_access = FALSE;
//Check access rights for found user
//Access to the mailing module
if(!ko_module_installed('mailing', $login['id'])) {
$no_access = TRUE;
}
//Access to people module
ko_get_access('leute', $login['id']);
if(!ko_module_installed('leute', $login['id']) || $access['leute']['MAX'] < 1) {
$no_access = TRUE;
}
// unset login_id, so that the following test will only consider the sender_email
if ($no_access) {
unset($login);
unset($login['id']);
}
//Access rights for groups and smallgroups, check will be done further down
ko_get_access('groups', $login['id']);
ko_get_access('kg', $login['id']);
}
// continue also with sender email. Maybe it is allowed to send email to it's own group
$sender_email = $mail['from'];
$found_any = false;
$crmProjects = ko_mailing_find_crm_projects($mail,$mail_recipients,$login,false);
$crmProjectIds = array_column($crmProjects,'id');
//flatten recipients array
$mail_recipients = array_reduce($mail_recipients,'array_merge',array());
foreach($mail_recipients as $mail_recipient) {
$error = 0;
$to = str_replace('@'.$domain, '', $mail_recipient);
if($to == $mail_recipient) {
// not the handeled domain -> ignore
continue;
}
$unsetLogin = FALSE;
// check if a rectype was specified in receiver address
$recType = '';
if (preg_match('/^.*\+[a-z]$/', $to)) {
$x = explode('+', $to);
$recType = array_pop($x);
$to = implode('+', $x);
if (!is_array($RECTYPES[$recType])) $recType = '';
}
//Check for automatically authorized emails
$auto_confirmed = FALSE;
if(FALSE !== strpos($to, '+')) {
list($to, $auth) = explode('+', $to);
if(KOOL_ENCRYPTION_KEY != '' && strlen($auth) == 32) {
$auto_confirmed = md5(date('d').$to.KOOL_ENCRYPTION_KEY) == $auth;
}
}
$new_code = false;
$found = false;
//Allow sending to groups without moderation. Will be set to TRUE in ko_mailing_check_group()
$no_mod = FALSE;
//Find mails sent to noreply (e.g. autoresponders)
if($to == 'noreply') {
$found = TRUE;
}
//Find confirm emails
else if(substr($to, 0, strlen('confirm-')) == 'confirm-') {
$found = TRUE;
$code = substr($to, strlen('confirm-'));
$error = ko_mailing_check_code($code, $mail2);
if($error) {
ko_mailing_error($login, $error, (is_array($mail2) ? $mail2 : $mail), $to);
} else {
ko_mailing_mail_confirmed($login, $code);
}
}
//Find group with id
else if(1 == preg_match('/^gr([0-9.]*$)/', $to, $m)) {
$found = TRUE;
list($all, $data) = $m;
list($gid, $rid) = explode('.', $data);
$error = ko_mailing_check_group($login, $gid, $rid, $no_mod, $unsetLogin);
//Don't allow sender if setting prohibits addresses with no alias
if(ko_get_setting('mailing_only_alias')) $error = MAILING_ERROR_ONLY_ALIAS;
$mail['_recipient'] = 'gr'.$gid.($rid ? '.'.$rid : '');
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$use_group = db_select_data('ko_groups', "WHERE `id` = '$gid'", '*', '', '', TRUE);
// apply rectype of group if no recype was specified in receiver address
if (!$recType) $recType = $use_group['mailing_rectype'];
if (!is_array($RECTYPES[$recType])) $recType = '';
$mail['_rectype'] = $recType;
$mail['_reply_to'] = $use_group['mailing_reply_to'];
$modifyRcpts = $use_group['mailing_modify_rcpts'];
$mail['_to'] = ($recType ? $recType . '+' : '') . $to.'@'.$domain;
// add prefix to email subject
$prefix = trim($use_group['mailing_prefix']);
if ($prefix != '' && strpos($mail['subject'], $prefix) === false)
$mail['subject'] = $prefix . ' ' . trim($mail['subject']);
if($use_group['mailing_crm_project_id']) {
$crmProjectIds[] = $use_group['mailing_crm_project_id'];
}
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, $modifyRcpts, $crmProjectIds);
}
}
//Find smallgroup with id
else if(1 == preg_match('/^sg([0-9]{4})([a-zA-Z.]*)$/', $to, $m)) {
$found = TRUE;
list($all, $sgid, $rid) = $m;
$error = ko_mailing_check_smallgroup($login, $sgid, $rid, $unsetLogin);
//Don't allow sender if setting prohibits addresses with no alias
if(ko_get_setting('mailing_only_alias')) $error = MAILING_ERROR_ONLY_ALIAS;
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$mail['_recipient'] = 'sg'.$sgid.($rid?'.'.$rid:'');
$mail['_rectype'] = $recType;
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, TRUE, $crmProjectIds);
}
}
//My List
else if($to == 'ml') {
$found = TRUE;
$error = ko_mailing_check_mylist($login, $unsetLogin);
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$mail['_recipient'] = 'ml';
$mail['_rectype'] = $recType;
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, TRUE, $crmProjectIds);
}
}
//Find filter preset with id
else if(1 == preg_match('/^fp([0-9]*$)/', $to, $m)) {
$found = TRUE;
list($all, $data) = $m;
$fid = intval($data);
$error = ko_mailing_check_filter($login, $fid, $unsetLogin);
//Don't allow sender if setting prohibits addresses with no alias
if(ko_get_setting('mailing_only_alias')) $error = MAILING_ERROR_ONLY_ALIAS;
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$mail['_rectype'] = $recType;
$mail['_recipient'] = 'fp'.$fid;
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, TRUE, $crmProjectIds);
}
}
//Find mailing alias
else if(!ko_mailing_check_disallowed_alias_patterns(strtolower($to))) {
//Find group or small group with this alias
$groups = db_select_data('ko_groups', "WHERE LOWER(`mailing_alias`) = '".mysqli_real_escape_string(db_get_link(), strtolower($to))."'");
$smallgroups = db_select_data('ko_kleingruppen', "WHERE LOWER(`mailing_alias`) = '".mysqli_real_escape_string(db_get_link(), strtolower($to))."'");
$filters = db_select_data('ko_userprefs', "WHERE LOWER(`mailing_alias`) = '".mysqli_real_escape_string(db_get_link(), strtolower($to))."'");
$num_found = sizeof($groups)+sizeof($smallgroups)+sizeof($filters);
if($num_found == 0) {
ko_mailing_error($login, MAILING_ERROR_NO_ALIAS_FOUND, $mail, $to);
} else if($num_found > 1) {
ko_mailing_error($login, MAILING_ERROR_NON_UNIQUE_ALIAS, $mail, $to);
} else {
if(sizeof($groups) == 1) {
$group = array_shift($groups);
if ($verbose) print "Mail alias matches group $group[name] (id $group[id])" . PHP_EOL;
$error = ko_mailing_check_group($login, $group['id'], '', $no_mod, $unsetLogin);
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
// apply rectype of group if no recype was specified in receiver address
if (!$recType) $recType = $group['mailing_rectype'];
if (!is_array($RECTYPES[$recType])) $recType = '';
$mail['_rectype'] = $recType;
$mail['_recipient'] = 'gr'.$group['id'];
$mail['_reply_to'] = $group['mailing_reply_to'];
$mail['_to'] = ($recType ? $recType . '+' : '') . $to.'@'.$domain;
// add prefix to email subject
$prefix = trim($group['mailing_prefix']);
if ($prefix != '' && strpos($mail['subject'], $prefix) === false)
$mail['subject'] = $prefix . ' ' . trim($mail['subject']);
$modifyRcpts = $group['mailing_modify_rcpts'];
if($group['mailing_crm_project_id']) {
$crmProjectIds[] = $group['mailing_crm_project_id'];
}
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, $modifyRcpts, $crmProjectIds);
$found = TRUE;
}
} else if(sizeof($smallgroups) == 1) {
$sg = array_shift($smallgroups);
if ($verbose) print "Mail alias matches smallgroup $sg[id]" . PHP_EOL;
$error = ko_mailing_check_smallgroup($login, $sg['id'], NULL, $unsetLogin);
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$mail['_rectype'] = $recType;
$mail['_recipient'] = 'sg'.$sg['id'];
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, TRUE, $crmProjectIds);
$found = TRUE;
}
} else if(sizeof($filters) == 1) {
$fp = array_shift($filters);
if ($verbose) print "Mail alias matches filter preset $fp[id]" . PHP_EOL;
$error = ko_mailing_check_filter($login, $fp['id'], $unsetLogin);
if($error) {
ko_mailing_error($login, $error, $mail, $to);
} else {
$mail['_rectype'] = $recType;
$mail['_recipient'] = 'fp'.$fp['id'];
list($new_id, $new_code) = ko_mailing_store_moderation($imap, $mail, $login, TRUE, $crmProjectIds);
$found = TRUE;
}
}
}
}
if($new_id) {
$mail['_id'] = $new_id;
}
if($new_code) {
//Auto confirm email if auth check above passed
if($auto_confirmed || $no_mod) {
ko_mailing_mail_confirmed($unsetLogin?NULL:$login, $new_code);
} else {
$error = ko_mailing_send_moderation_mail($unsetLogin?NULL:$login, $new_id, $mail, $sender_email);
if($error) ko_mailing_error($login, $error, $mail, $to);
}
}
$found_any |= $found;
}//foreach(mail_recipients)
return $found_any;
}
/**
* @param $mailer RawSmtpMailer
* @param $mails_per_cycle
*
* @throws Exception
*/
function ko_mailing_send_mails($mailer,$mails_per_cycle) {
global $MODULES,$return_path,$MAIL_TRANSPORT,$domain;
//Check db for mails to be sent
$sent_mails = 0;
$mails = db_select_data('ko_mailing_mails', "WHERE `status` = '".MAILING_STATUS_CONFIRMED."'");
foreach($mails as $mail) {
if($mail['size']) {
$mail['body'] = gzinflate($mail['body']);
}
$done_names = array();
if ($sent_mails == $mails_per_cycle) break;
//Find quoted-printable in header
//Find utf-8 encoding. If set then encode recipient's name
//if(FALSE !== strpos(strtolower($mail['header']), 'charset=utf-8')) $utf8 = TRUE;
//else $utf8 = FALSE;
//Get next recipients and send emails
$recipients = db_select_data('ko_mailing_recipients', "WHERE `mail_id` = '".$mail['id']."'", '*', '', 'LIMIT 0,'.($mails_per_cycle - $sent_mails > 0 ? ($mails_per_cycle - $sent_mails) : 0));
$crmContactIds = array();
if($recipients) {
$crmProjectIds = explode(',',$mail['crm_project_ids']);
$subject = iconv_mime_decode($mail['subject'],0,'latin1');
foreach($crmProjectIds as $crmProjectId) {
if(!$crmProjectId) continue;
$contact = ko_mailing_store_crm_contact($mail['header'].CRLF.CRLF.$mail['body'],$crmProjectId,$mail['user_id'],null,$mail['id'],$subject);
$crmContactIds[] = $contact['id'];
}
}
//Set return path to sender's email
$_return_path = ($return_path == 'USER') ? '-f'.$mail['from'] : $return_path;
foreach($recipients as $rec) {
if ($sent_mails == $mails_per_cycle) break;
if(!$rec['id']) continue;
if ($mail['modify_rcpts']) {
$to = "To: ".mb_encode_mimeheader($rec['name'], 'UTF-8', 'Q')." <".$rec['email'].">" . CRLF;
}
else {
$to = "";
}
$subject = "Subject: " . ko_mailing_markers($mail['subject'], $rec['leute_id'], $rec['email'], FALSE, $rec['placeholder_data']) . CRLF;
$bulkHeader = ($bulk_header === true ? 'Precedence: bulk' . CRLF : '');
$log_to = $rec['name']." (".$rec['email'].")";
if (trim(ko_get_setting('mailing_from_email'))) {
$sender = trim(ko_get_setting('mailing_from_email'));
} else {
$sender = $mail['from'];
}
$rcpt = $rec['email'];
$mailContent = $mail['header'] . CRLF.CRLF . $mail['body'];
$mailContent = ko_mailing_markers_by_part($mailContent, $rec);
$parts = explode(CRLF.CRLF, $mailContent);
array_shift($parts);
$body = implode(CRLF.CRLF, $parts);
$message = ko_emailtext(trim($mail['header'])).$to.$bulkHeader.$subject.CRLF.ko_emailtext($body);
$mailer->removeAddresses();
try {
$mailer->setSender($sender);
$mailer->addAddress($rcpt);
$mailer->setMessage($message);
$mailer->send();
db_delete_data('ko_mailing_recipients', "WHERE `id` = '" . $rec['id'] . "'");
$done[] = $rec['id'];
$doneLeuteIds[] = $rec['leute_id'];
$done_names[] = $log_to;
$sent_mails++;
foreach ($crmContactIds as $crmContactId) {
db_insert_data('ko_crm_mapping', array('contact_id' => $crmContactId, 'leute_id' => $rec['leute_id']));
}
} catch (Exception $e) {
ko_log('mailing_smtp_error', $e->getMessage());
if(stristr($e->getMessage(), "SMTP Error: The following recipients failed:")) {
// try to send mail a few times. after this: remove from queue and contact sender
if ($rec['delivery_attempts'] >= ko_get_setting('mailing_max_attempts')) {
$mailsubject = getLL("admin_mailing_max_attempts_subject");
$mailtext = getLL("mailing_errormail_text_intro");
$mailtext.= sprintf(getLL('admin_mailing_max_attempts_mailbody'), $domain)."\n";
$mailtext.= "<strong>" . getLL('mailing_header_date') . "</strong>: " . sql2datetime($mail['crdate']) ."\n";
$mailtext.= "<strong>" . getLL('mailing_header_subject') . "</strong>: " . $mail['subject'] ."\n";
$mailtext.= "<strong>" . getLL('mailing_header_recipient') . "</strong>: " . $log_to ."\n";
preg_match_all('/Reply-To: (.*)\r/', $mail['header'], $reply_to, PREG_SET_ORDER, 0);
$reply_address = (!empty($reply_to[0][1]) ? $reply_to[0][1] : $mail['from']);
ko_send_html_mail(ko_mail_get_from(), $reply_address, $mailsubject, ko_emailtext(nl2br($mailtext)));
$where = "WHERE id = " . $rec['id'];
db_delete_data("ko_mailing_recipients", $where);
} else {
$where = "WHERE id = " . $rec['id'];
$data = ["delivery_attempts" => ($rec['delivery_attempts'] + 1)];
db_update_data("ko_mailing_recipients", $where, $data);
}
}
}
}
//Create log entry with all recipients
db_insert_data('ko_log', array('type' => 'mailing_sent', 'comment' => $mail['id'].': '.implode(', ', $done_names), 'user_id' => $mail['user_id'], 'date' => date('Y-m-d H:i:s')));
//Check recipients, mark mail as sent if none left
$num = db_get_count('ko_mailing_recipients', 'id', "AND `mail_id` = '".$mail['id']."'");
if($num == 0) {
db_update_data('ko_mailing_mails', "WHERE `id` = '".$mail['id']."'", array('status' => MAILING_STATUS_SENT));
//Add log entry after finishing mailing
$log = $mail['id'].': '.'Subject: '.$mail['subject'].', From: '.$mail['from'].', To: '.$mail['recipient'];
db_insert_data('ko_log', array('type' => 'mailing_done', 'comment' => $log, 'user_id' => $mail['user_id'], 'date' => date('Y-m-d H:i:s')));
}
}
}
function ko_mailing_find_crm_projects(&$mail,$mail_recipients,$login,$report_errors = true) {
global $domain,$access;
if($login) {
ko_get_access('crm',$login['id']);
}
$projects = array();
foreach($mail_recipients as $recipients) {
foreach($recipients as $recipient) {
$at = strrpos($recipient,'@');
$to = substr($recipient,0,$at);
$host = substr($recipient,$at+1);
if($host == $domain && substr($to,0,3) == 'crm') {
$project = ko_mailing_parse_crm_project(substr($to,3));
if($project) {
if(!$login) {
if($report_errors) ko_mailing_error($login,MAILING_ERROR_CRM_NO_USER,$mail);
return array();
}
if(!ko_module_installed('crm', $login['id'])) {
if($report_errors) ko_mailing_error($login,MAILING_ERROR_CRM_NO_ACCESS,$mail);
return array();
}
if(max($access['crm'][$project['id']],$access['crm']['ALL']) >= 2) {
$projects[$recipient] = $project;
} else if($report_errors) {
ko_mailing_error($login,MAILING_ERROR_CRM_PROJECT_NO_ACCESS,$mail,$to);
}
} else if($report_errors) {
ko_mailing_error($login,MAILING_ERROR_CRM_NO_PROJECT,$mail,$to);
ko_log('mailing_crm_project_not_found', "could not find crm project by pattern ".substr($to,4).".");
}
}
}
}
return $projects;
}
function ko_mailing_handle_mail_crm(&$mail,$mail_recipients,$login) {
global $domain,$imap;
$crmProjects = ko_mailing_find_crm_projects($mail,$mail_recipients,$login);
$crmRecipientIds = array();
foreach($mail_recipients as $recipients) {
foreach($recipients as $recipient) {
if(!isset($crmProjects[$recipient]) && substr($recipient,strrpos($recipient,'@')+1) != $domain) {
$crmRec = ko_get_person_by_email($recipient);
if ($crmRec) {
$crmRecipientIds[] = $crmRec['id'];
}
}
}
}
if(empty($crmProjects)) {
return false;
}
foreach($crmProjects as $project) {
$contact = ko_mailing_store_crm_contact(
imap_fetchheader($imap,$mail['msgno']).CRLF.CRLF.imap_body($imap,$mail['msgno']),
$project['id'],
$login['id'],
$mail['msgno'],
isset($mail['_id']) ? $mail['_id'] : null
);
foreach($crmRecipientIds as $recId) {
db_insert_data('ko_crm_mapping', array('contact_id' => $contact['id'], 'leute_id' => $recId));
}
}
return true;
}
function ko_mailing_parse_crm_project($pattern) {
if (!$pattern) return FALSE;
if($pattern[0] == '-') {
$pattern = substr($pattern,1);
}
$project = NULL;
if (preg_match('/\d+/', $pattern)) {
$project = db_select_data('ko_crm_projects', "WHERE `id` = {$pattern}", '*', '', '', TRUE);
if ($project['id'] != $pattern) $project = NULL;
}
if (!$project && strpos($pattern, '-') !== FALSE) {
$project = db_select_data('ko_crm_projects', "WHERE `number` = '{$pattern}'", '*', '', '', TRUE);
if ($project['number'] != $pattern) $project = NULL;
}
if (!$project) {
$title = str_replace(array(',', '.', '@', ' ', 'ä', 'ö', 'ü'), array('', '', '', '', 'ae', 'oe', 'ue'), strtolower($pattern));
$project = db_select_data('ko_crm_projects', "WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(`title`), ' ', ''), ',', ''), '@', ''), '.', ''), 'ä', 'ae'), 'ü', 'ue'), 'ö', 'oe') = '{$title}'", '*', '', '', TRUE);
if (str_replace(array(',', '.', '@', ' ', 'ä', 'ö', 'ü'), array('', '', '', '', 'ae', 'oe', 'ue'), strtolower($project['title'])) != $title) $project = NULL;
}
return $project;
}
function ko_mailing_get_sender_login(&$from) {
global $LEUTE_EMAIL_FIELDS;
//Find sender email address
$pos1 = strrpos($from, '<');
if(FALSE !== $pos1) {
$pos2 = strpos($from, '>', $pos1);
$from = substr($from, $pos1 + 1, ($pos2 ? $pos2 : strlen($from)) - $pos1 - 1);
}
if(!check_email($from)) return FALSE;
$from = strtolower($from);
//email fields
$where_email = '';
foreach($LEUTE_EMAIL_FIELDS as $field) {
$where_email .= " LOWER(l.$field) = '".$from."' OR ";
}
$logins = db_select_data("ko_admin AS a LEFT JOIN ko_leute as l ON a.leute_id = l.id",
"WHERE ($where_email LOWER(a.email) = '".mysqli_real_escape_string(db_get_link(), $from)."') AND (a.disabled = '0' OR a.disabled = '')",
"a.id AS id");
$login = array_shift($logins);
return $login['id'];
}//ko_mailing_get_sender_login()
/**
* Mark mail as confirmed and create recipient entries for all recipients in queue
* @param $login
* @param $code code of th email that was confirmed
*/
function ko_mailing_mail_confirmed($login, $code) {
$mail = db_select_data('ko_mailing_mails', "WHERE `code` = '$code' AND `status` = '".MAILING_STATUS_OPEN."'", '*, NULL AS body', '', '', TRUE);
//Get recipients
$recipients = ko_mailing_get_recipients($login, $mail['recipient'], $dummy);
//Create db entries
$done_emails = array();
foreach($recipients as $r) {
$emails = NULL;
// apply rectype if specified
if ($mail['rectype']) {
$p = ko_apply_rectype($r, $mail['rectype']);
if ($p['email']) $emails = array($p['email']);
}
if (!is_array($emails)) ko_get_leute_email($r, $emails);
foreach($emails as $email) { //Include all email addresses, if several are set as preferred
$email = trim($email);
if(!check_email($email)) continue;
//Don't send mail to same address twice
if(!ko_get_setting('mailing_allow_double') && in_array($email, $done_emails)) continue;
$done_emails[] = $email;
$entry = array('mail_id' => $mail['id'], 'name' => $r['vorname'].' '.$r['nachname'], 'email' => $email, 'leute_id' => $r['id']);
db_insert_data('ko_mailing_recipients', $entry);
}
}
//Set status of mail to confirmed
db_update_data('ko_mailing_mails', "WHERE `id` = '".$mail['id']."'", array('status' => MAILING_STATUS_CONFIRMED));
//Create log entry
$log = $mail['id'].': '.'Subject: '.$mail['subject'].', From: '.$mail['from'].', To: '.$mail['recipient'].', Recipients: '.sizeof($recipients).', Modify Recipients: ' . $mail['modify_recipients'] . ', RecType: ' . $mail['rectype'];
db_insert_data('ko_log', array('type' => 'mailing_confirmed', 'comment' => $log, 'user_id' => $login['id'], 'date' => date('Y-m-d H:i:s')));
}//ko_mailing_mail_confirmed()
/**
* Return a list of entries from ko_leute who are recipients of the given mailinglist
* @param $rec sgXXXX[.Y], grXXXXXX.YYYYYY, fpX or ml
*/
function ko_mailing_get_recipients($login, $rec, &$accessError = null) {
global $access, $sender_email;
$mode = substr($rec, 0, 2);
$data = substr($rec, 2);
$_recipients = array();
$allow = false;
$accessError = FALSE;
switch($mode) {
case 'gr':
$parts = explode('.', $data);
$gid = array_shift($parts);
$rid = array_shift($parts);
$group = 'g'.$gid.($rid ? '[g:0-9]*r'.$rid : '');
$where = "WHERE `groups` REGEXP '$group' AND `deleted` = '0' AND `hidden` = '0'";
$_recipients = db_select_data('ko_leute', $where);
$g = db_select_data('ko_groups', 'where id = ' . $gid, '*', '', '', TRUE, TRUE);
ko_mailing_check_sender_email_access($g, $sender_email, $allow, $allow_without_mod);
break;
case 'ml':
$ids = unserialize(ko_get_userpref($login['id'], 'leute_my_list'));
if(sizeof($ids) > 0) {
$_recipients = db_select_data('ko_leute', "WHERE `id` IN ('".implode("','", $ids)."') AND `deleted` = '0' AND `hidden` = '0'");
}
break;
case 'sg':
$parts = explode('.', $data);
$sgid = array_shift($parts);
$rid = array_shift($parts);
$_recipients = db_select_data('ko_leute', "WHERE `smallgroups` REGEXP '".$sgid.($rid?':'.$rid:'')."' AND `deleted` = '0' AND `hidden` = '0'");
break;
case 'fp':
$fid = intval($data);
$filterPreset = db_select_data('ko_userprefs', "WHERE `type` = 'filterset' AND `id` = '$fid'", '*', '', '', TRUE);
$filter = unserialize($filterPreset['value']);
if(!$filter) $where = 'AND 1=2';
else apply_leute_filter($filter, $where);
$_recipients = db_select_data('ko_leute', "WHERE 1=1 ".$where." AND `deleted` = '0' AND `hidden` = '0'");
break;
}
//Perform tests
ko_get_access('leute', $login['id']);
$recipients = array();
foreach($_recipients as $r) {
//Check for access to this single address
if($login['id'] > 0 && $access['leute']['ALL'] < 1 && $access['leute'][$r['id']] < 1) {
$accessError = TRUE;
continue;
}
//Check for valid email
if(FALSE === ko_get_leute_email($r, $emails)) continue;
$recipients[] = $r;
}
return $recipients;
}//ko_mailing_get_recipients()
/**
* Retrieve a human readable name of a given recipient (gr000001, sg000001, ml)
*/