This repository has been archived by the owner on Jun 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostie-functions.php
3565 lines (3219 loc) · 131 KB
/
postie-functions.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
/*
$Id: postie-functions.php 1025546 2014-11-14 06:40:07Z WayneAllen $
*/
//to turn on debug output add the following line to wp-config.php
//define('POSTIE_DEBUG', true);
class PostiePostModifiers {
var $PostFormat = 'standard';
function apply($postid) {
if ($this->PostFormat != 'standard') {
set_post_format($postid, $this->PostFormat);
}
}
}
if (!function_exists('mb_str_replace')) {
function mb_str_replace($search, $replace, $subject, &$count = 0) {
if (!is_array($subject)) {
// Normalize $search and $replace so they are both arrays of the same length
$searches = is_array($search) ? array_values($search) : array($search);
$replacements = array_pad(is_array($replace) ? array_values($replace) : array($replace), count($searches), '');
foreach ($searches as $key => $search) {
$parts = mb_split(preg_quote($search), $subject);
$count += count($parts) - 1;
$subject = implode($replacements[$key], $parts);
}
} else {
// Call mb_str_replace for each subject in array, recursively
foreach ($subject as $key => $value) {
$subject[$key] = mb_str_replace($search, $replace, $value, $count);
}
}
return $subject;
}
}
function postie_environment() {
DebugEcho("Postie Version: " . POSTIE_VERSION);
DebugEcho("Wordpress Version: " . get_bloginfo('version'));
DebugEcho("PHP Version: " . phpversion());
DebugEcho("OS: " . php_uname());
DebugEcho("Debug mode: " . (IsDebugMode() ? "On" : "Off"));
DebugEcho("Time: " . date('Y-m-d H:i:s', time()) . " GMT");
DebugEcho("Error log: " . ini_get('error_log'));
if (isMarkdownInstalled()) {
EchoInfo("You currently have the Markdown plugin installed. It will cause problems if you send in HTML email. Please turn it off if you intend to send email using HTML.");
}
if (!isPostieInCorrectDirectory()) {
EchoInfo("Warning! Postie expects to be in its own directory named postie.");
} else {
EchoInfo("Postie is in " . plugin_dir_path(__FILE__));
}
if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
EchoInfo("Alternate cron is enabled");
}
if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
EchoInfo("WordPress cron is disabled. Postie will not run unless you have an external cron set up.");
}
EchoInfo("Cron: " . (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON === true ? "Of" : "On"));
EchoInfo("Alternate Cron: " . (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON === true ? "On" : "Off"));
if (defined('WP_CRON_LOCK_TIMEOUT') && WP_CRON_LOCK_TIMEOUT === true) {
EchoInfo("Cron lock timeout is:" . WP_CRON_LOCK_TIMEOUT);
}
if (HasIconvInstalled()) {
EchoInfo("iconv: installed");
} else {
EchoInfo("Warning! Postie requires that iconv be enabled.");
}
if (function_exists('imap_mime_header_decode')) {
EchoInfo("imap: installed");
} else {
EchoInfo("Warning! Postie requires that imap be enabled if you are using IMAP, IMAP-SSL or POP3-SSL.");
}
if (HasMbStringInstalled()) {
EchoInfo("mbstring: installed");
} else {
EchoInfo("Warning! Postie requires that mbstring be enabled.");
}
}
function postie_disable_revisions($restore = false) {
global $_wp_post_type_features, $_postie_revisions;
if (!$restore) {
$_postie_revisions = false;
if (isset($_wp_post_type_features['post']) && isset($_wp_post_type_features['post']['revisions'])) {
$_postie_revisions = $_wp_post_type_features['post']['revisions'];
unset($_wp_post_type_features['post']['revisions']);
}
} else {
if ($_postie_revisions) {
$_wp_post_type_features['post']['revisions'] = $_postie_revisions;
}
}
}
/* this function is necessary for wildcard matching on non-posix systems */
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
$pattern = strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
return preg_match('/^' . strtr(addcslashes($pattern, '/\\.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string);
}
}
function LogInfo($v) {
error_log("Postie: $v");
}
function EchoInfo($v) {
if (php_sapi_name() == "cli") {
print( "$v\n");
} else {
//flush the buffers
while (ob_get_level() > 0) {
ob_end_flush();
}
print( "<pre>" . htmlspecialchars($v) . "</pre>\n");
}
LogInfo($v);
}
function DebugDump($v) {
if (IsDebugMode()) {
$o = print_r($v, true);
if (php_sapi_name() == "cli") {
print( "$o\n");
} else {
//flush the buffers
while (ob_get_level() > 0) {
ob_end_flush();
}
print( "<pre>\n");
EchoInfo($o);
print( "</pre>\n");
}
}
}
function DebugEcho($v) {
if (IsDebugMode()) {
EchoInfo($v);
}
}
function tag_Date(&$content, $message_date) {
//don't apply any offset here as it is accounted for later
$html = LoadDOM($content);
if ($html !== false) {
$es = $html->find('text');
DebugEcho("tag_Date: html " . count($es));
foreach ($es as $e) {
//DebugEcho("tag_Date: ".trim($e->plaintext));
$matches = array();
if (1 === preg_match("/^date:\s?(.*)$/im", trim($e->plaintext), $matches)) {
DebugEcho("tag_Date: found date tag $matches[1]");
$newdate = strtotime($matches[1]);
if (false !== $newdate) {
$t = date("H:i:s", $newdate);
DebugEcho("tag_Date: original time: $t");
$format = "Y-m-d";
if ($t != '00:00:00') {
$format.= " H:i:s";
}
$message_date = date($format, $newdate);
$content = str_replace($matches[0], '', $content);
break;
}
}
}
} else {
DebugEcho("tag_Date: not html");
}
return $message_date;
}
function CreatePost($poster, $mimeDecodedEmail, $post_id, &$is_reply, $config, $postmodifiers) {
$fulldebug = IsDebugMode();
$fulldebugdump = false;
extract($config);
$attachments = array(
"html" => array(), //holds the html for each image
"cids" => array(), //holds the cids for HTML email
"image_files" => array() //holds the files for each image
);
if (array_key_exists('message-id', $mimeDecodedEmail->headers)) {
DebugEcho("Message Id is :" . htmlentities($mimeDecodedEmail->headers["message-id"]));
if ($fulldebugdump) {
DebugDump($mimeDecodedEmail);
}
}
filter_PreferedText($mimeDecodedEmail, $config['prefer_text_type']);
if ($fulldebugdump) {
DebugDump($mimeDecodedEmail);
}
$content = GetContent($mimeDecodedEmail, $attachments, $post_id, $poster, $config);
if ($fulldebug) {
DebugEcho("the content is $content");
}
$subject = GetSubject($mimeDecodedEmail, $content, $config);
filter_RemoveSignature($content, $config);
if ($fulldebug) {
DebugEcho("post sig: $content");
}
$post_excerpt = tag_Excerpt($content, $config);
if ($fulldebug) {
DebugEcho("post excerpt: $content");
}
$postAuthorDetails = getPostAuthorDetails($subject, $content, $mimeDecodedEmail);
if ($fulldebug) {
DebugEcho("post author: $content");
}
$message_date = NULL;
if (array_key_exists("date", $mimeDecodedEmail->headers) && !empty($mimeDecodedEmail->headers["date"])) {
$cte = "";
$cs = "";
if (property_exists($mimeDecodedEmail, 'content-transfer-encoding') && array_key_exists('content-transfer-encoding', $mimeDecodedEmail->headers)) {
$cte = $mimeDecodedEmail->headers["content-transfer-encoding"];
}
if (property_exists($mimeDecodedEmail, 'ctype_parameters') && array_key_exists('charset', $mimeDecodedEmail->ctype_parameters)) {
$cs = $mimeDecodedEmail->ctype_parameters["charset"];
}
$message_date = HandleMessageEncoding($cte, $cs, $mimeDecodedEmail->headers["date"], $message_encoding, $message_dequote);
}
$message_date = tag_Date($content, $message_date);
list($post_date, $post_date_gmt, $delay) = filter_Delay($content, $message_date, $config['time_offset']);
if ($fulldebug) {
DebugEcho("post date: $content");
}
filter_Ubb2HTML($content);
if ($fulldebug) {
DebugEcho("post ubb: $content");
}
$post_categories = tag_Categories($subject, $config['default_post_category'], $config['category_match']);
if ($fulldebug) {
DebugEcho("post category: $content");
}
$post_tags = tag_Tags($content, $config['default_post_tags']);
if ($fulldebug) {
DebugEcho("post tag: $content");
}
$comment_status = tag_AllowCommentsOnPost($content);
if ($fulldebug) {
DebugEcho("post comment: $content");
}
$post_status = tag_Status($content, $post_status);
if ($fulldebug) {
DebugEcho("post status: $content");
}
if ($config['converturls']) {
$content = filter_Videos($content, $config['shortcode']); //videos first so linkify doesn't mess with them
if ($fulldebug) {
DebugEcho("post video: $content");
}
$content = filter_Linkify($content);
if ($fulldebug) {
DebugEcho("post linkify: $content");
}
}
filter_VodafoneHandler($content, $attachments);
if ($fulldebug) {
DebugEcho("post vodafone: $content");
}
filter_ReplaceImageCIDs($content, $attachments, $config);
if ($fulldebug) {
DebugEcho("post cid: $content");
}
$customImages = tag_CustomImageField($content, $attachments, $config);
if ($fulldebug) {
DebugEcho("post custom: $content");
}
$post_type = tag_PostType($subject, $postmodifiers, $config);
if ($fulldebug) {
DebugEcho("post type: $content");
}
$id = GetParentPostForReply($subject);
if (empty($id)) {
DebugEcho("Not a reply");
$id = $post_id;
$is_reply = false;
if ($config['add_meta'] == 'yes') {
DebugEcho("Adding meta");
if ($config['wrap_pre'] == 'yes') {
DebugEcho("Adding <pre>");
$content = $postAuthorDetails['content'] . "<pre>\n" . $content . "</pre>\n";
$content = "<pre>\n" . $content . "</pre>\n";
} else {
$content = $postAuthorDetails['content'] . $content;
$content = $content;
}
} else {
if ($config['wrap_pre'] == 'yes') {
DebugEcho("Adding <pre>");
$content = "<pre>\n" . $content . "</pre>\n";
}
}
} else {
DebugEcho("Reply detected");
$is_reply = true;
// strip out quoted content
$lines = explode("\n", $content);
$newContents = '';
foreach ($lines as $line) {
if (preg_match("/^>.*/i", $line) == 0 &&
preg_match("/^(from|subject|to|date):.*?/i", $line) == 0 &&
preg_match("/^-+.*?(from|subject|to|date).*?/i", $line) == 0 &&
preg_match("/^on.*?wrote:$/i", $line) == 0 &&
preg_match("/^-+\s*forwarded\s*message\s*-+/i", $line) == 0) {
$newContents.="$line\n";
}
}
$content = $newContents;
wp_delete_post($post_id);
}
if ($delay != 0 && $post_status == 'publish') {
$post_status = 'future';
}
filter_Newlines($content, $config);
if ($fulldebug) {
DebugEcho("post newline: $content");
}
filter_Start($content, $config);
if ($fulldebug) {
DebugEcho("post start: $content");
}
filter_End($content, $config);
if ($fulldebug) {
DebugEcho("post end: $content");
}
DebugEcho("prefer_text_type: " . $config['prefer_text_type']);
filter_ReplaceImagePlaceHolders($content, $attachments["html"], $config, $id, $config['image_placeholder'], true);
if ($fulldebug) {
DebugEcho("post body img: $content");
}
if ($post_excerpt) {
filter_ReplaceImagePlaceHolders($post_excerpt, $attachments["html"], $config, $id, "#eimg%#", false);
if ($fulldebug) {
DebugEcho("post excerpt img: $content");
}
}
DebugEcho("excerpt: $post_excerpt");
if (trim($subject) == "") {
$subject = $config['default_title'];
DebugEcho("post parsing subject is blank using: " . $config['default_title']);
}
$details = array(
'post_author' => $poster,
'comment_author' => $postAuthorDetails['author'],
'comment_author_url' => $postAuthorDetails['comment_author_url'],
'user_ID' => $postAuthorDetails['user_ID'],
'email_author' => $postAuthorDetails['email'],
'post_date' => $post_date,
'post_date_gmt' => $post_date_gmt,
'post_content' => $content,
'post_title' => $subject,
'post_type' => $post_type, /* Added by Raam Dev <[email protected]> */
'ping_status' => get_option('default_ping_status'),
'post_category' => $post_categories,
'tags_input' => $post_tags,
'comment_status' => $comment_status,
'post_name' => sanitize_title($subject),
'post_excerpt' => $post_excerpt,
'ID' => $id,
'customImages' => $customImages,
'post_status' => $post_status
);
return $details;
}
/**
* This is the main handler for all of the processing
*/
function PostEmail($poster, $mimeDecodedEmail, $config) {
postie_disable_revisions();
extract($config);
/* in order to do attachments correctly, we need to associate the
attachments with a post. So we add the post here, then update it */
$tmpPost = array('post_title' => 'tmptitle', 'post_content' => 'tmpPost', 'post_status' => 'draft');
$post_id = wp_insert_post($tmpPost);
DebugEcho("tmp post id is $post_id");
$is_reply = false;
$postmodifiers = new PostiePostModifiers();
$details = CreatePost($poster, $mimeDecodedEmail, $post_id, $is_reply, $config, $postmodifiers);
$details = apply_filters('postie_post', $details);
$details = apply_filters('postie_post_before', $details);
DebugEcho(("Post postie_post filter"));
DebugDump($details);
if (empty($details)) {
// It is possible that the filter has removed the post, in which case, it should not be posted.
// And if we created a placeholder post (because this was not a reply to an existing post),
// then it should be removed
if (!$is_reply) {
wp_delete_post($post_id);
EchoInfo("postie_post filter cleared the post, not saving.");
}
} else {
DisplayEmailPost($details);
$postid = PostToDB($details, $is_reply, $custom_image_field, $postmodifiers);
if ($confirmation_email != '') {
if ($confirmation_email == 'sender') {
$recipients = array($details['email_author']);
} elseif ($confirmation_email == 'admin') {
$recipients = array(get_option("admin_email"));
} elseif ($confirmation_email == 'both') {
$recipients = array($details['email_author'], get_option("admin_email"));
}
MailToRecipients($mimeDecodedEmail, false, $recipients, false, false, $postid);
}
}
postie_disable_revisions(true);
DebugEcho("Done");
}
/** FUNCTIONS * */
/*
* Added by Raam Dev <[email protected]>
* Adds support for handling Custom Post Types by adding the
* Custom Post Type name to the email subject separated by
* $custom_post_type_delim, e.g. "Movies // My Favorite Movie"
* Also supports setting the Post Format.
*/
function tag_PostType(&$subject, $postmodifiers, $config) {
$post_type = $config['post_type'];
$custom_post_type = $config['post_format'];
$separated_subject = array();
$separated_subject[0] = "";
$separated_subject[1] = $subject;
$custom_post_type_delim = "//";
if (strpos($subject, $custom_post_type_delim) !== FALSE) {
// Captures the custom post type in the subject before $custom_post_type_delim
$separated_subject = explode($custom_post_type_delim, $subject);
$custom_post_type = trim(strtolower($separated_subject[0]));
DebugEcho("post type: found possible type '$custom_post_type'");
}
$known_post_types = get_post_types();
if (in_array($custom_post_type, array_map('strtolower', $known_post_types))) {
DebugEcho("post type: found type '$post_type'");
$post_type = $custom_post_type;
$subject = trim($separated_subject[1]);
} elseif (in_array($custom_post_type, array_keys(get_post_format_slugs()))) {
DebugEcho("post type: found format '$custom_post_type'");
$postmodifiers->PostFormat = $custom_post_type;
$subject = trim($separated_subject[1]);
}
return $post_type;
}
function filter_Linkify($text) {
# It turns urls into links, and video urls into embedded players
//DebugEcho("begin: filter_linkify");
$html = LoadDOM($text);
if ($html) {
//DebugEcho("filter_linkify: " . $html->save());
foreach ($html->find('text') as $element) {
//DebugEcho("filter_linkify: " . $element->innertext);
$element->innertext = make_links($element->innertext);
}
$ret = $html->save();
} else {
$ret = make_links($text);
}
//DebugEcho("end: filter_linkify");
return $ret;
}
function LoadDOM($text) {
return str_get_html($text, true, true, DEFAULT_TARGET_CHARSET, false);
}
function filter_Videos($text, $shortcode = false) {
# It turns urls into links, and video urls into embedded players
//DebugEcho("begin: filter_Videos");
$html = LoadDOM($text);
if ($html) {
foreach ($html->find('text') as $element) {
$element->innertext = linkifyVideo($element->innertext, $shortcode);
}
$ret = $html->save();
} else {
$ret = linkifyVideo($text, $shortcode);
}
//DebugEcho("end: filter_Videos");
return $ret;
}
function linkifyVideo($text, $shortcode = false) {
//$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
//DebugEcho("linkify1: $text");
// pad it with a space so we can match things at the start of the 1st line.
$ret = ' ' . $text;
if (strpos($ret, 'youtube') !== false) {
// try to embed youtube videos
$youtube = "#(^|[\n ]|>)[\w]+?://(www\.)?youtube\.com/watch\?v=([_a-zA-Z0-9-]+).*?([ \n]|$|<)#is";
if ($shortcode) {
$youtube_replace = "\\1[youtube \\3]\\4";
} else {
$youtube_replace = "\\1<embed width='425' height='344' allowfullscreen='true' allowscriptaccess='always' type='application/x-shockwave-flash' src='http://www.youtube.com/v/\\3&hl=en&fs=1' />\\4";
}
$ret = preg_replace($youtube, $youtube_replace, $ret);
DebugEcho("youtube: $ret");
}
if (strpos($ret, 'vimeo') !== false) {
// try to embed vimeo videos
# : http://vimeo.com/6348141
$vimeo = "#(^|[\n ]|>)[\w]+?://(www\.)?vimeo\.com/([_a-zA-Z0-9-]+).*?([ \n]|$|<)#is";
if ($shortcode) {
$vimeo_replace = "\\1[vimeo \\3]\\4";
} else {
$vimeo_replace = "\\1<object width='400' height='300'><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id=\\3&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' /><embed src='http://vimeo.com/moogaloop.swf?clip_id=\\3&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='400' height='300'></embed></object>\\4";
}
$ret = preg_replace($vimeo, $vimeo_replace, $ret);
DebugEcho("vimeo: $ret");
}
// Remove our padding..
$ret = substr($ret, 1);
return $ret;
}
function make_links($text) {
return preg_replace(
array(
'/(?(?=<a[^>]*>.+<\/a>)
(?:<a[^>]*>.+<\/a>)
|
([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+)
)/iex',
'/<a([^>]*)target="?[^"\']+"?/i',
'/<a([^>]+)>/i',
'/(^|\s)(www.[^<> \n\r]+)/iex',
'/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
(\\.[A-Za-z0-9-]+)*)/iex'
), array(
"stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))",
'<a\\1',
'<a\\1 >',
"stripslashes((strlen('\\2')>0?'\\1<a href=\"http://\\2\">\\2</a>\\3':'\\0'))",
"stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))"
), $text
);
}
/* we check whether or not the email is a forwards or a redirect. If it is
* a fwd, then we glean the author details from the body of the post.
* Otherwise we get them from the headers
*/
function getPostAuthorDetails(&$subject, &$content, &$mimeDecodedEmail) {
$theDate = $mimeDecodedEmail->headers['date'];
$theEmail = RemoveExtraCharactersInEmailAddress($mimeDecodedEmail->headers["from"]);
$regAuthor = get_user_by('email', $theEmail);
if ($regAuthor) {
$theAuthor = $regAuthor->user_login;
$theUrl = $regAuthor->user_url;
$theID = $regAuthor->ID;
} else {
$theAuthor = GetNameFromEmail($theEmail);
$theUrl = '';
$theID = '';
}
// see if subject starts with Fwd:
$matches = array();
if (preg_match("/(^Fwd:) (.*)/", $subject, $matches)) {
DebugEcho("Fwd: detected");
$subject = trim($matches[2]);
if (preg_match("/\nfrom:(.*?)\n/i", $content, $matches)) {
$theAuthor = GetNameFromEmail($matches[1]);
$mimeDecodedEmail->headers['from'] = $theAuthor;
}
//TODO dosen't always work with HTML
if (preg_match("/\ndate:(.*?)\n/i", $content, $matches)) {
$theDate = $matches[1];
DebugEcho("date in Fwd: $theDate");
if (($timestamp = strtotime($theDate)) === false) {
DebugEcho("bad date found: $theDate");
} else {
$mimeDecodedEmail->headers['date'] = $theDate;
}
}
// now get rid of forwarding info in the content
$lines = preg_split("/\r\n/", $content);
$newContents = '';
foreach ($lines as $line) {
if (preg_match("/^(from|subject|to|date):.*?/i", $line, $matches) == 0 && preg_match("/^-+\s*forwarded\s*message\s*-+/i", $line, $matches) == 0) {
$newContents.=preg_replace("/\r/", "", $line) . "\n";
}
}
$content = $newContents;
}
$theDetails = array(
'content' => "<div class='postmetadata alt'>On $theDate, $theAuthor" . " posted:</div>",
'emaildate' => $theDate,
'author' => $theAuthor,
'comment_author_url' => $theUrl,
'user_ID' => $theID,
'email' => $theEmail
);
return $theDetails;
}
/* we check whether or not the email is a reply to a previously
* published post. First we check whether it starts with Re:, and then
* we see if the remainder matches an already existing post. If so,
* then we add that post id to the details array, which will cause the
* existing post to be overwritten, instead of a new one being
* generated
*/
function GetParentPostForReply(&$subject) {
global $wpdb;
$id = NULL;
DebugEcho("GetParentPostForReply: Looking for parent '$subject'");
// see if subject starts with Re:
$matches = array();
if (preg_match("/(^Re:)(.*)/i", $subject, $matches)) {
DebugEcho("GetParentPostForReply: Re: detected");
$subject = trim($matches[2]);
// strip out category info into temporary variable
$tmpSubject = $subject;
if (preg_match('/(.+): (.*)/', $tmpSubject, $matches)) {
$tmpSubject = trim($matches[2]);
$matches[1] = array($matches[1]);
} else if (preg_match_all('/\[(.[^\[]*)\]/', $tmpSubject, $matches)) {
$tmpSubject_matches = array();
preg_match("/](.[^\[]*)$/", $tmpSubject, $tmpSubject_matches);
$tmpSubject = trim($tmpSubject_matches[1]);
} else if (preg_match_all('/-(.[^-]*)-/', $tmpSubject, $matches)) {
preg_match("/-(.[^-]*)$/", $tmpSubject, $tmpSubject_matches);
$tmpSubject = trim($tmpSubject_matches[1]);
}
DebugEcho("GetParentPostForReply: tmpSubject: $tmpSubject");
$checkExistingPostQuery = "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_status = 'publish'";
if ($id = $wpdb->get_var($wpdb->prepare($checkExistingPostQuery, $tmpSubject))) {
if (is_array($id)) {
$id = $id[count($id) - 1];
DebugEcho("GetParentPostForReply: id: $id");
} else {
DebugEcho("GetParentPostForReply: No parent id found");
}
}
} else {
DebugEcho("GetParentPostForReply: No parent found");
}
return $id;
}
function postie_ShowReadMe() {
include(POSTIE_ROOT . DIRECTORY_SEPARATOR . "postie_read_me.php");
}
/**
* This sets up the configuration menu
*/
function PostieMenu() {
if (function_exists('add_options_page')) {
if (current_user_can('manage_options')) {
add_options_page("Postie", "Postie", 'manage_options', POSTIE_ROOT . "/postie.php", "ConfigurePostie");
}
}
}
/**
* This handles actually showing the form. Called by WordPress
*/
function ConfigurePostie() {
include(POSTIE_ROOT . DIRECTORY_SEPARATOR . "config_form.php");
}
/**
* This function handles determining the protocol and fetching the mail
* @return array
*/
function FetchMail($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0, $email_tls = false) {
$emails = array();
if (!$server || !$port || !$email) {
EchoInfo("Missing Configuration For Mail Server");
return $emails;
}
if ($server == "pop.gmail.com") {
EchoInfo("MAKE SURE POP IS TURNED ON IN SETTING AT Gmail");
}
switch (strtolower($protocol)) {
case 'smtp': //direct
$fd = fopen("php://stdin", "r");
$input = "";
while (!feof($fd)) {
$input .= fread($fd, 1024);
}
fclose($fd);
$emails[0] = $input;
break;
case 'imap':
case 'imap-ssl':
case 'pop3-ssl':
if (!HasIMAPSupport()) {
EchoInfo("Sorry - you do not have IMAP php module installed - it is required for this mail setting.");
} else {
$emails = IMAPMessageFetch($server, $port, $email, $password, $protocol, $offset, $test, $deleteMessages, $maxemails, $email_tls);
}
break;
case 'pop3':
default:
$emails = POP3MessageFetch($server, $port, $email, $password, $protocol, $offset, $test, $deleteMessages, $maxemails);
}
return $emails;
}
/**
* Handles fetching messages from an imap server
*/
function IMAPMessageFetch($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0, $tls = false) {
require_once("postieIMAP.php");
$emails = array();
$mail_server = &PostieIMAP::Factory($protocol);
if ($tls) {
$mail_server->TLSOn();
}
DebugEcho("Connecting to $server:$port ($protocol)" . ($tls ? " with TLS" : ""));
if ($mail_server->connect(trim($server), $port, $email, $password)) {
$msg_count = $mail_server->getNumberOfMessages();
} else {
EchoInfo("Mail Connection Time Out");
EchoInfo("Common Reasons: Server Down, Network Issue, Port/Protocol MisMatch ");
EchoInfo("The Server said:" . $mail_server->error());
$msg_count = 0;
}
// loop through messages
for ($i = 1; $i <= $msg_count; $i++) {
$emails[$i] = $mail_server->fetchEmail($i);
if ($deleteMessages) {
$mail_server->deleteMessage($i);
}
if ($maxemails != 0 && $i >= $maxemails) {
DebugEcho("Max emails ($maxemails)");
break;
}
}
if ($deleteMessages) {
$mail_server->expungeMessages();
}
//clean up
$mail_server->disconnect();
return $emails;
}
/**
* Retrieves email via POP3
*/
function POP3MessageFetch($server = NULL, $port = NULL, $email = NULL, $password = NULL, $protocol = NULL, $offset = NULL, $test = NULL, $deleteMessages = true, $maxemails = 0) {
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'class-pop3.php');
$emails = array();
$pop3 = new POP3();
if (defined('POSTIE_DEBUG')) {
$pop3->DEBUG = POSTIE_DEBUG;
}
DebugEcho("Connecting to $server:$port ($protocol)");
if ($pop3->connect(trim($server), $port)) {
$msg_count = $pop3->login($email, $password);
if ($msg_count === false) {
$msg_count = 0;
}
} else {
if (strpos($pop3->ERROR, "POP3: premature NOOP OK, NOT an RFC 1939 Compliant server") === false) {
EchoInfo("Mail Connection Time Out. Common Reasons: Server Down, Network Issue, Port/Protocol MisMatch");
}
EchoInfo("The Server said: $pop3->ERROR");
$msg_count = 0;
}
DebugEcho("message count: $msg_count");
// loop through messages
//$msgs = $pop3->pop_list();
//DebugEcho("POP3MessageFetch: messages");
//DebugDump($msgs);
for ($i = 1; $i <= $msg_count; $i++) {
$m = $pop3->get($i);
if ($m !== false) {
if (is_array($m)) {
$emails[$i] = implode('', $m);
if ($deleteMessages) {
if (!$pop3->delete($i)) {
EchoInfo("POP3MessageFetch: cannot delete message $i: " . $pop3->ERROR);
$pop3->reset();
exit;
}
}
} else {
DebugEcho("POP3MessageFetch: message $i not an array");
}
} else {
EchoInfo("POP3MessageFetch: message $i $pop3->ERROR");
}
if ($maxemails != 0 && $i >= $maxemails) {
DebugEcho("Max emails ($maxemails)");
break;
}
}
//clean up
$pop3->quit();
return $emails;
}
/**
* This function handles putting the actual entry into the database
* @param array - categories to be posted to
* @param array - details of the post
*/
function PostToDB($details, $isReply, $customImageField, $postmodifiers) {
$post_ID = 0;
if (!$isReply) {
$post_ID = wp_insert_post($details, true);
if (is_wp_error($post_ID)) {
EchoInfo("Error: " . $post_ID->get_error_message());
wp_delete_post($details['ID']);
}
//evidently post_category was depricated at some point.
//wp_set_post_terms($post_ID, $details['post_category']);
} else {
$comment = array(
'comment_author' => $details['comment_author'],
'comment_post_ID' => $details['ID'],
'comment_author_email' => $details['email_author'],
'comment_date' => $details['post_date'],
'comment_date_gmt' => $details['post_date_gmt'],
'comment_content' => $details['post_content'],
'comment_author_url' => $details['comment_author_url'],
'comment_author_IP' => '',
'comment_approved' => 1,
'comment_agent' => '',
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $details['user_ID']
);
$post_ID = wp_insert_comment($comment);
}
if ($post_ID) {
if ($customImageField) {
DebugEcho("Saving custom image fields");
//DebugDump($details['customImages']);
if (count($details['customImages']) > 1) {
$imageField = 1;
foreach ($details['customImages'] as $image) {
add_post_meta($post_ID, 'image' . $imageField, $image);
$imageField++;
}
}
}
$postmodifiers->apply($post_ID);
do_action('postie_post_after', $details);
}
return $post_ID;
}
/**
* This function determines if the mime attachment is on the BANNED_FILE_LIST
* @param string
* @return boolean
*/
function isBannedFileName($filename, $bannedFiles) {
if (empty($filename) || empty($bannedFiles)) {
return false;
}
foreach ($bannedFiles as $bannedFile) {
if (fnmatch($bannedFile, $filename)) {
EchoInfo("Ignoring attachment: $filename - it is on the banned files list.");
return true;
}
}
return false;
}
function GetContent($part, &$attachments, $post_id, $poster, $config) {
extract($config);
//global $charset, $encoding;
DebugEcho('GetContent: ---- start');
$meta_return = '';
if (property_exists($part, "ctype_primary")) {
DebugEcho("GetContent: primary= " . $part->ctype_primary . ", secondary = " . $part->ctype_secondary);
//DebugDump($part);
}
DecodeBase64Part($part);
//look for banned file names
if (property_exists($part, 'ctype_parameters') && is_array($part->ctype_parameters) && array_key_exists('name', $part->ctype_parameters)) {
if (isBannedFileName($part->ctype_parameters['name'], $banned_files_list)) {
DebugEcho("GetContent: found banned filename");
return NULL;
}
}
if (property_exists($part, "ctype_primary") && $part->ctype_primary == "application" && $part->ctype_secondary == "octet-stream") {
if (property_exists($part, 'disposition') && $part->disposition == "attachment") {
//nothing
} else {
DebugEcho("GetContent: decoding application/octet-stream");
$mimeDecodedEmail = DecodeMIMEMail($part->body);
filter_PreferedText($mimeDecodedEmail, $prefer_text_type);
foreach ($mimeDecodedEmail->parts as $section) {
$meta_return .= GetContent($section, $attachments, $post_id, $poster, $config);
}
}
}
if (property_exists($part, "ctype_primary") && $part->ctype_primary == "multipart" && $part->ctype_secondary == "appledouble") {
DebugEcho("GetContent: multipart appledouble");
$mimeDecodedEmail = DecodeMIMEMail("Content-Type: multipart/mixed; boundary=" . $part->ctype_parameters["boundary"] . "\n" . $part->body);
filter_PreferedText($mimeDecodedEmail, $prefer_text_type);
filter_AppleFile($mimeDecodedEmail);
foreach ($mimeDecodedEmail->parts as $section) {