-
Notifications
You must be signed in to change notification settings - Fork 0
/
wpmandrill.php
1973 lines (1622 loc) · 82 KB
/
wpmandrill.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
/*
Plugin Name: wpMandrill - MULTISITE
Description: wpMandrill sends emails, generated by WordPress using Mandrill. "NETWORK ENABLE" THE PLUGIN. THEN, CONFIGURE IT FROM YOUR MAIN SITE
Author: Mandrill
Author URI: http://mandrillapp.com/
Plugin URI: http://connect.mailchimp.com/integrations/transactional-emails-from-wordpress
Version: 1.33
Text Domain: wpmandrill
*/
/*
THIS FILE WAS MODIFIED ON 10/2/2013 TO ALLOW FOR SINGLE-POINT CONFIG IN MULTISITE.
SIMPLY DROP THIS IN YOUR PLUGINS FOLDER AND "NETWORK ENABLE" THE PLUGIN. THEN, CONFIGURE
IT FROM YOUR MAIN SITE
*/
/* Copyright 2012 MailChimp (email : [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 using version 2 of the License.
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
wpMandrill::on_load();
class wpMandrill {
const DEBUG = false;
static $settings;
static $report;
static $stats;
static $mandrill;
static $conflict;
static $error;
static function on_load() {
define('WPMANDRILL_API_VERSION', '1.0');
add_action('admin_init', array(__CLASS__, 'adminInit'));
add_action('admin_menu', array(__CLASS__, 'adminMenu'));
add_filter('contextual_help', array(__CLASS__, 'showContextualHelp'), 10, 3);
add_action('admin_print_footer_scripts', array(__CLASS__,'openContextualHelp'));
add_action('wp_ajax_get_mandrill_stats', array(__CLASS__,'getAjaxStats'));
add_action('wp_ajax_get_dashboard_widget_stats', array(__CLASS__,'showDashboardWidget'));
load_plugin_textdomain('wpmandrill', false, dirname( plugin_basename( __FILE__ ) ).'/lang');
if( function_exists('wp_mail') ) {
self::$conflict = true;
add_action('admin_notices', array(__CLASS__, 'adminNotices'));
return;
}
self::$conflict = false;
if( self::isConfigured() ) {
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
try {
$sent = wpMandrill::mail( $to, $subject, $message, $headers, $attachments );
if ( is_wp_error($sent)
|| !isset($sent[0]['status'])
|| ($sent[0]['status'] != 'sent' && $sent[0]['status'] != 'queued') ) {
return wpMandrill::wp_mail_native( $to, $subject, $message, $headers, $attachments );
}
return true;
} catch ( Exception $e ) {
return wpMandrill::wp_mail_native( $to, $subject, $message, $headers, $attachments );
}
}
}
}
/**
* Sets up options page and sections.
*/
static function adminInit() {
add_filter('plugin_action_links',array(__CLASS__,'showPluginActionLinks'), 10,5);
add_action('admin_enqueue_scripts', array(__CLASS__,'showAdminEnqueueScripts'));
register_setting('wpmandrill', 'wpmandrill', array(__CLASS__,'formValidate'));
add_action( 'network_admin_notices', array( __CLASS__, 'network_connect_notice' ) );
// SMTP Settings
add_settings_section('wpmandrill-api', __('API Settings', 'wpmandrill'), '__return_false', 'wpmandrill');
add_settings_field('api-key', __('API Key', 'wpmandrill'), array(__CLASS__, 'askAPIKey'), 'wpmandrill', 'wpmandrill-api');
if( self::getAPIKey() ) {
if (current_user_can('manage_options')) add_action('wp_dashboard_setup', array( __CLASS__,'addDashboardWidgets') );
// Verified Addresses
add_settings_section('wpmandrill-addresses', __('Sender Settings', 'wpmandrill'), '__return_false', 'wpmandrill');
add_settings_field('from-name', __('FROM Name', 'wpmandrill'), array(__CLASS__, 'askFromName'), 'wpmandrill', 'wpmandrill-addresses');
add_settings_field('from-email', __('FROM Email', 'wpmandrill'), array(__CLASS__, 'askFromEmail'), 'wpmandrill', 'wpmandrill-addresses');
add_settings_field('reply-to', __('Reply-To Email', 'wpmandrill'), array(__CLASS__, 'askReplyTo'), 'wpmandrill', 'wpmandrill-addresses');
// Tracking
add_settings_section('wpmandrill-tracking', __('Tracking', 'wpmandrill'), '__return_false', 'wpmandrill');
add_settings_field('trackopens', __('Track opens', 'wpmandrill'), array(__CLASS__, 'askTrackOpens'), 'wpmandrill', 'wpmandrill-tracking');
add_settings_field('trackclicks', __('Track clicks', 'wpmandrill'), array(__CLASS__, 'askTrackClicks'), 'wpmandrill', 'wpmandrill-tracking');
// Template
add_settings_section('wpmandrill-templates', __('General Design', 'wpmandrill'), '__return_false', 'wpmandrill');
add_settings_field('template', __('Template', 'wpmandrill'), array(__CLASS__, 'askTemplate'), 'wpmandrill', 'wpmandrill-templates');
add_settings_field('nl2br', __('Content', 'wpmandrill'), array(__CLASS__, 'asknl2br'), 'wpmandrill', 'wpmandrill-templates');
// Tags
add_settings_section('wpmandrill-tags', __('General Tags', 'wpmandrill'), '__return_false', 'wpmandrill');
add_settings_field('tags', __(' ', 'wpmandrill'), array(__CLASS__, 'askTags'), 'wpmandrill', 'wpmandrill-tags');
if ( self::isConfigured() ) {
// Email Test
register_setting('wpmandrill-test', 'wpmandrill-test', array(__CLASS__, 'sendTestEmail'));
add_settings_section('mandrill-email-test', __('Send a test email using these settings', 'wpmandrill'), '__return_false', 'wpmandrill-test');
add_settings_field('email-to', __('Send to', 'wpmandrill'), array(__CLASS__, 'askTestEmailTo'), 'wpmandrill-test', 'mandrill-email-test');
add_settings_field('email-subject', __('Subject', 'wpmandrill'), array(__CLASS__, 'askTestEmailSubject'), 'wpmandrill-test', 'mandrill-email-test');
add_settings_field('email-message', __('Message', 'wpmandrill'), array(__CLASS__, 'askTestEmailMessage'), 'wpmandrill-test', 'mandrill-email-test');
}
}
// Activate the cron job that will update the stats
add_action('wpm_update_stats', array(__CLASS__,'saveProcessedStats'));
if ( !wp_next_scheduled( 'wpm_update_stats' ) ) {
wp_schedule_event( current_time( 'timestamp', 1 ), 'hourly', 'wpm_update_stats');
}
register_deactivation_hook( __FILE__, array(__CLASS__,'deactivate') );
}
static public function deactivate() {
wp_clear_scheduled_hook('wpm_update_stats');
}
/**
* Creates option page's entry in Settings section of menu.
*/
static function adminMenu() {
global $blog_id;
// only main blog gets the options
if( $blog_id != 1 ) {
return;
}
self::$settings = add_options_page(
__('Mandrill Settings', 'wpmandrill'),
__('Mandrill', 'wpmandrill'),
'manage_options',
'wpmandrill',
array(__CLASS__,'showOptionsPage')
);
if( self::isConfigured() ) {
if (current_user_can('manage_options')) self::$report = add_dashboard_page(
__('Mandrill Reports', 'wpmandrill'),
__('Mandrill Reports', 'wpmandrill'),
'manage_options',
'wpmandrill'.'-reports',
array(__CLASS__,'showReportPage')
);
if ( self::isPluginPage('-reports') ) {
wp_register_script('flot', plugins_url('/js/flot/jquery.flot.js', __FILE__), array('jquery'), null, true);
wp_register_script('flotstack', plugins_url('/js/flot/jquery.flot.stack.js', __FILE__), array('flot'), null, true);
wp_register_script('flotresize', plugins_url('/js/flot/jquery.flot.resize.js', __FILE__), array('flot'), null, true);
wp_enqueue_script('flot');
wp_enqueue_script('flotstack');
wp_enqueue_script('flotresize');
wp_enqueue_script('mandrill-report-export');
}
}
wp_register_style( 'mandrill_stylesheet', plugins_url('/css/mandrill.css', __FILE__) );
wp_enqueue_style( 'mandrill_stylesheet' );
wp_register_script('mandrill', plugins_url('/js/mandrill.js', __FILE__), array(), null, true);
wp_enqueue_script('mandrill');
}
static function network_connect_notice() {
$shown = get_site_option('wpmandrill_notice_shown');
if ( empty($shown) ) {
?>
<div id="message" class="updated wpmandrill-message">
<div class="squeezer">
<h4><?php _e( '<strong>wpMandrill is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'wpmandrill' ) ?></h4>
</div>
</div>
<?php
update_site_option('wpmandrill_notice_shown',true);
}
}
static function adminNotices() {
if ( self::$conflict ) {
echo '<div class="error"><p>'.__('Mandrill: wp_mail has been declared by another process or plugin, so you won\'t be able to use Mandrill until the problem is solved.', 'wpmandrill') . '</p></div>';
}
}
static function showAdminEnqueueScripts($hook_suffix) {
if( $hook_suffix == self::$report && self::isConnected() ) {
wp_register_script('mandrill-report-script', plugins_url("js/mandrill.js", __FILE__), array('flot'), null, true);
wp_enqueue_script('mandrill-report-script');
}
}
/**
* Generates source of contextual help panel.
*/
static function showContextualHelp($contextual_help, $screen_id, $screen) {
if ($screen_id == self::$settings) {
self::getConnected();
$ok = array();
$ok['account'] = ( !self::isConnected() ) ? ' class="missing"' : '';
$ok['email'] = ( $ok['account'] != '' || !self::getFromEmail() ) ? ' class="missing"' : '';
$requirements = '';
if ($ok['account'] . $ok['email'] != '' ) {
$requirements = '<p>' . __('To use this plugin you will need:', 'wpmandrill') . '</p>'
. '<ol>'
. '<li'.$ok['account'].'>'. __('Your Mandrill account.', 'wpmandrill') . '</li>'
. '<li'.$ok['email'].'>' . __('A valid sender email address.', 'wpmandrill') . '</li>'
. '</ol>';
}
return $requirements
. '<p>' . __('Once you have properly configured the settings, the plugin will take care of all the emails sent through your WordPress installation.', 'wpmandrill').'</p>'
. '<p>' . __('However, if you need to customize any part of the email before sending, you can do so by using the WordPress filter <strong>mandrill_payload</strong>.', 'wpmandrill').'</p>'
. '<p>' . __('This filter has the same structure as Mandrill\'s API call <a href="http://mandrillapp.com/api/docs/messages.html#method=send" target="_blank">/messages/send</a>, except that it can have one additional parameter when the email is based on a template. The parameter is called "<em>template</em>", which is an associative array of two elements (the first element, a string whose key is "<em>template_name</em>", and a second parameter whose key is "<em>template_content</em>". Its value is an array with the same structure of the parameter "<em>template_content</em>" in the call <a href="http://mandrillapp.com/api/docs/messages.html#method=send-template" target="_blank">/messages/send-template</a>.)', 'wpmandrill').'</p>'
. '<p>' . __('Note that if you\'re sending additional headers in your emails, the only valid headers are <em>From:</em>, <em>Reply-To:</em>, and <em>X-*:</em>. <em>Bcc:</em> is also valid, but Mandrill will send the blind carbon copy to only the first address, and the remaining will be silently discarded.', 'wpmandrill').'</p>'
. '<p>' . __('Also note that if any error occurs while sending the email, the plugin will try to send the message again using the native WordPress mailing capabilities.', 'wpmandrill').'</p>'
. '<p>' . __('Confirm that any change you made to the payload is in line with the <a href="http://mandrillapp.com/api/docs/" target="_blank">Mandrill\'s API\'s documentation</a>. Also, the <em>X-*:</em> headers, must be in line with the <a href="http://help.mandrill.com/forums/20689696-smtp-integration" target="_blank">SMTP API documentation</a>. By using this plugin, you agree that you and your website will adhere to <a href="http://www.mandrill.com/terms/" target="_blank">Mandrill\'s Terms of Use</a> and <a href="http://mandrill.com/privacy/" target="_blank">Privacy Policy</a>.', 'wpmandrill').'</p>'
. '<p>' . __('if you have any question about Mandrill or this plugin, visit the <a href="http://help.mandrill.com/" target="_blank">Mandrill\'s Support Center</a>.', 'wpmandrill').'</p>'
;
}
return $contextual_help;
}
/**
* Adds link to settings page in list of plugins
*/
static function showPluginActionLinks($actions, $plugin_file) {
static $plugin;
if (!isset($plugin))
$plugin = plugin_basename(__FILE__);
if ($plugin == $plugin_file) {
$settings = array('settings' => '<a href="options-general.php?page=wpmandrill">' . __('Settings', 'wpmandrill') . '</a>');
if ( self::isConnected() ) {
$report = array('report' => '<a href="index.php?page=wpmandrill-reports">' . __('Reports', 'wpmandrill') . '</a>');
$actions = array_merge($settings, $actions, $report);
} else {
$actions = array_merge($settings, $actions);
}
}
return $actions;
}
/**
* Generates source of options page.
*/
static function showOptionsPage() {
if (!current_user_can('manage_options'))
wp_die( __('You do not have sufficient permissions to access this page.') );
if ( isset($_GET['show']) && $_GET['show'] == 'how-tos' ) {
self::showHowTos();
return;
}
self::getConnected();
?>
<div class="wrap">
<div class="icon32" style="background: url('<?php echo plugins_url('images/mandrill-head-icon.png',__FILE__); ?>');"><br /></div>
<h2><?php _e('Mandrill Settings', 'wpmandrill'); ?> <small><a href="options-general.php?page=<?php echo 'wpmandrill'; ?>&show=how-tos">view how-tos</a></small></h2>
<div style="float: left;width: 70%;">
<form method="post" action="options.php">
<div class="stuffbox">
<?php settings_fields('wpmandrill'); ?>
<?php do_settings_sections('wpmandrill'); ?>
</div>
<p class="submit"><input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" /></p>
</form>
<?php if( self::isConnected() ) { ?>
<form method="post" action="options.php">
<div class="stuffbox" style="max-width: 90% !important;">
<?php settings_fields('wpmandrill-test'); ?>
<?php do_settings_sections('wpmandrill-test'); ?>
</div>
<p class="submit"><input type="submit" name="Submit" class="button-primary" value="<?php _e('Send Test', 'wpmandrill') ?>" /></p>
</form>
<?php } ?>
</div>
<div style="float: left;width: 20%;">
<?php
$rss = fetch_feed('http://blog.mandrill.com/feeds/all.atom.xml');
$maxitems = 0;
if (!is_wp_error( $rss ) ) {
$maxitems = $rss->get_item_quantity(5);
$rss_items = $rss->get_items(0, $maxitems);
}
if ( $maxitems > 0 ) {
?>
<div class="mcnews mandrill">
<h3 class="mcnews_header"><?php _e('Latest from Mandrill...', 'wpmandrill'); ?></h3>
<ul>
<?php
foreach ( $rss_items as $item ) { ?>
<li>
<a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
<div class="mcnews">
<h3 class="mcnews_header"><?php _e('News from MailChimp...', 'wpmandrill'); ?></h3><?php
$rss = fetch_feed('http://mailchimp.com/blog/feed');
if (!is_wp_error( $rss ) ) {
$maxitems = $rss->get_item_quantity(5);
$rss_items = $rss->get_items(0, $maxitems);
} ?>
<ul>
<?php if ($maxitems == 0) echo '<li>No news!</li>';
else
foreach ( $rss_items as $item ) { ?>
<li>
<a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
<?php
}
static function showHowTos() {
self::getConnected();
?>
<div class="wrap">
<div class="icon32" style="background: url('<?php echo plugins_url('images/mandrill-head-icon.png',__FILE__); ?>');"><br /></div>
<h2><?php _e('Mandrill How-Tos', 'wpmandrill'); ?> <small><a href="options-general.php?page=<?php echo 'wpmandrill'; ?>">back to settings</a></small></h2>
<?php
require plugin_dir_path( __FILE__ ) . '/how-tos.php';
echo wpMandrill_HowTos::show('intro');
echo wpMandrill_HowTos::show('auto');
echo wpMandrill_HowTos::show('regular');
echo wpMandrill_HowTos::show('filter');
echo wpMandrill_HowTos::show('nl2br');
echo wpMandrill_HowTos::show('direct');
?>
</div>
<?php
}
static function showReportPage() {
require plugin_dir_path( __FILE__ ) . '/stats.php';
}
/**
* Processes submitted settings from.
*/
static function formValidate($input) {
self::getConnected();
if ( empty($input['from_username']) ) {
add_settings_error(
'wpmandrill',
'from-email',
__('You must define a valid sender email.', 'wpmandrill'),
'error'
);
$input['from_username'] = '';
}
// Preserving the Reply-To address
$reply_to = $input['reply_to'];
$response = array_map('wp_strip_all_tags', $input);
$response['reply_to'] = $reply_to;
return $response;
}
/**
* Opens contextual help section.
*/
static function openContextualHelp() {
if ( !self::isPluginPage() || ( self::isConnected() && self::getFromEmail() ) )
return;
?>
<script type="text/javascript">
jQuery(document).bind( 'ready', function() {
jQuery('a#contextual-help-link').trigger('click');
});
</script>
<?php
}
/******************************************************************
** Helper functions
*******************************************************************
/**
* @return mixed
*/
static function getOption( $name, $default = false ) {
global $blog_id;
if( $blog_id == 1 )
{
$options = get_option('wpmandrill');
if( serialize(get_site_option('wpmandrill')) != serialize($options) ) {
update_site_option('wpmandrill', $options);
}
}
else {
$options = get_site_option('wpmandrill');
}
// var_dump($options);
if( isset( $options[$name] ) )
return $options[$name];
return $default;
}
/**
* @return boolean
*/
static function isConnected() {
return isset(self::$mandrill);
}
static function getConnected() {
if ( !isset(self::$mandrill) ) {
try {
require_once( plugin_dir_path( __FILE__ ) . '/lib/mandrill.class.php');
self::$mandrill = new Mandrill( self::getAPIKey() );
} catch ( Exception $e ) {}
}
}
/**
* @return boolean
*/
static function isConfigured() {
return self::getAPIKey() && self::getFromEmail();
}
/**
* @return boolean
*/
static function setOption( $name, $value )
{
global $blog_id;
if( $blog_id == 1 ) {
$options = get_option('wpmandrill');
}
else {
$options = get_site_option('wpmandrill');
}
$options[$name] = $value;
$result = update_site_option('wpmandrill', $options);
return $result;
}
/**
* @return string|boolean
*/
static function getAPIKey() {
return self::getOption('api_key');
}
/**
* @return string|boolean
*/
static function getFromUsername() {
return self::getOption('from_username');
}
/**
* @return string|boolean
*/
static function getFromEmail() {
$from_email = self::getOption('from_username');
if ( !empty($from_email) && !strpos($from_email, '@') ) {
$from_email = self::getOption('from_username') . '@' . self::getOption('from_domain');
self::setOption('from_username', $from_email);
self::setOption('from_domain', null);
}
return $from_email;
}
/**
* @return string|boolean
*/
static function getFromName() {
return self::getOption('from_name');
}
/**
* @return string|boolean
*/
static function getReplyTo() {
return self::getOption('reply_to');
}
/**
* @return string|boolean
*/
static function getTemplate() {
return self::getOption('template');
}
/**
* @return string|boolean
*/
static function getnl2br() {
return self::getOption('nl2br');
}
/**
* @return string|boolean
*/
static function getTrackOpens() {
return self::getOption('trackopens');
}
/**
* @return string|boolean
*/
static function getTrackClicks() {
return self::getOption('trackclicks');
}
/**
* @return string|boolean
*/
static function getTags() {
return self::getOption('tags');
}
/**
* @param string $subject
* @return array
*/
static function findTags($tags) {
// Getting general tags
$gtags = array();
$general_tags = self::getTags();
if ( !empty( $general_tags ) ) {
$gtags = explode("\n",$general_tags);
foreach ( $gtags as $index => $gtag ) {
if ( empty($gtag) ) unset($gtags[$index]);
}
$gtags = array_values($gtags);
}
// Finding tags based on WP Backtrace
$trace = debug_backtrace();
$level = 4;
$function = $trace[$level]['function'];
$wtags = array();
if( 'include' == $function || 'require' == $function ) {
$file = basename($trace[$level]['args'][0]);
$wtags[] = "wp_{$file}";
}
else {
if( isset( $trace[$level]['class'] ) )
$function = $trace[$level]['class'].$trace[$level]['type'].$function;
$wtags[] = "wp_{$function}";
}
return array('user' => $tags, 'general' => $gtags, 'automatic' => $wtags);
}
/**
* @return boolean
*/
static function isPluginPage($sufix = '') {
return ( isset( $_GET['page'] ) && $_GET['page'] == 'wpmandrill' . $sufix);
}
/**
* @return boolean
*/
static function isTemplateValid($template) {
self::getConnected();
if ( empty($template) || !self::isConnected() ) return false;
$templates = self::$mandrill->templates_list();
foreach ( $templates as $curtemplate ) {
if ( $curtemplate['name'] == $template ) {
return true;
}
}
return false;
}
/**
* Processes submitted email test form.
*/
static function sendTestEmail($input) {
if (isset($input['email_to']) && !empty($input['email_to'])) {
$to = $input['email_to'];
$subject = isset($input['email_subject']) ? $input['email_subject'] : '';
$message = isset($input['email_message']) ? $input['email_message'] : '';
$test = self::mail($to, $subject, $message);
if (is_wp_error($test)) {
add_settings_error('email-to', 'email-to', __('Test failed. Please verify the following:
<ol>
<li>That your web server has either cURL installed or is able to use fsock*() functions (if you don\'t know what this means, you may want to check with your hosting provider for more details);</li>
<li>That your API key is active (this can be viewed on the <a href="https://mandrillapp.com/settings/index" target="_blank">SMTP & API Credentials</a> page in your Mandrill account);</li>
</ol>', 'wpmandrill') . $test->get_error_message());
return array_map('wp_strip_all_tags', $input);
} else {
$result = array();
$result['sent'] = 0;
$result['queue'] = 0;
$result['rejected'] = 0;
foreach ( $test as $email ) {
if ( !isset($result[$email['status']]) ) $result[$email['status']] = 0;
$result[$email['status']]++;
}
add_settings_error('email-to', 'email-to', sprintf(__('Test executed: %d emails sent, %d emails queued and %d emails rejected', 'wpmandrill'), $result['sent'],$result['queue'],$result['rejected']), $result['sent'] ? 'updated' : 'error' );
}
}
return array();
}
// Following methods generate parts of settings and test forms.
static function askAPIKey() {
echo '<div class="inside">';
$api_key = self::getOption('api_key');
?><input id='api_key' name='wpmandrill[api_key]' size='45' type='text' value="<?php esc_attr_e( $api_key ); ?>" /><?php
if ( empty($api_key) ) {
?><br/><span class="setting-description"><small><em><?php _e('To get your API key, please visit your <a href="http://mandrillapp.com/settings/index" target="_blank">Mandrill Settings</a>', 'wpmandrill'); ?></em></small></span><?php
} else {
$api_is_valid = false;
self::getConnected();
if ( self::isConnected() ) $api_is_valid = ( self::$mandrill->users_ping() == 'PONG!' );
if ( !$api_is_valid ) {
?><br/><span class="setting-description"><small><em><?php _e('Sorry. Invalid API key.', 'wpmandrill'); ?></em></small></span><?php
}
}
echo '</div>';
}
static function askFromEmail() {
echo '<div class="inside">';
$from_username = self::getFromUsername();
$from_email = self::getFromEmail();
?><?php _e('This address will be used as the sender of the outgoing emails:', 'wpmandrill'); ?><br />
<input id="from_username" name="wpmandrill[from_username]" type="text" value="<?php esc_attr_e($from_username);?>">
<br/><?php
echo '</div>';
}
static function askFromName() {
echo '<div class="inside">';
$from_name = self::getFromName();
?><?php _e('Name the recipients will see in their email clients:', 'wpmandrill'); ?><br />
<input id="from_name" name="wpmandrill[from_name]" type="text" value="<?php esc_attr_e($from_name); ?>">
<?php
echo '</div>';
}
static function askReplyTo() {
echo '<div class="inside">';
$reply_to = self::getReplyTo();
?><?php _e('This address will be used as the recipient where replies from the users will be sent to:', 'wpmandrill'); ?><br />
<input id="reply_to" name="wpmandrill[reply_to]" type="text" value="<?php esc_attr_e($reply_to);?>"><br/>
<span class="setting-description"><small><em><?php _e('Leave blank to use the FROM Email. If you want to override this setting, you must use the <em><a href="#" onclick="jQuery(\'a#contextual-help-link\').trigger(\'click\');return false;">mandrill_payload</a></em> WordPress filter.', 'wpmandrill'); ?></em></small></span><?php
echo '</div>';
}
static function askTemplate() {
echo '<div class="inside">';
self::getConnected();
if ( !self::isConnected() ) {
_e('No templates found.', 'wpmandrill');
echo '</div>';
return;
}
$template = self::getTemplate();
$templates = self::$mandrill->templates_list();
if( is_wp_error($templates) || empty($templates)) {
_e('No templates found.', 'wpmandrill');
if( $templates )
self::setOption('templates', false);
echo '</div>';
return;
}
?><?php _e('Select the template to use:', 'wpmandrill'); ?><br />
<select id="template" name="wpmandrill[template]">
<option value="">-None-</option><?php
foreach( $templates as $curtemplate ) {
?><option value="<?php esc_attr_e($curtemplate['name']); ?>" <?php selected($curtemplate['name'], $template); ?>><?php esc_html_e($curtemplate['name']); ?></option><?php
}
?></select><br/><span class="setting-description"><em><?php _e('<small>The selected template must have a <strong><em>mc:edit="main"</em></strong> placeholder defined. The message will be shown there.</small>', 'wpmandrill'); ?></em></span><?php
echo '</div>';
}
static function askTrackOpens() {
$track = self::getTrackOpens();
if ( $track == '' ) $track = 0;
?>
<div class="inside">
<input id="trackopens" name="wpmandrill[trackopens]" type="checkbox" <?php echo checked($track,1); ?> value='1' /><br/>
</div><?php
}
static function askTrackClicks() {
$track = self::getTrackClicks();
if ( $track == '' ) $track = 0;
?>
<div class="inside">
<input id="trackclicks" name="wpmandrill[trackclicks]" type="checkbox" <?php echo checked($track,1); ?> value='1' /><br/>
</div><?php
}
static function asknl2br() {
$nl2br = self::getnl2br();
if ( $nl2br == '' ) $nl2br = 0;
?>
<div class="inside">
<?php _e('Replace all line feeds ("\n") by <br/> in the message body?', 'wpmandrill'); ?>
<input id="nl2br" name="wpmandrill[nl2br]" type="checkbox" <?php echo checked($nl2br,1); ?> value='1' /><br/>
<span class="setting-description">
<em>
<?php _e('<small>If you are sending HTML emails already keep this setting deactivated.<br/>But if you are sending text only emails (WordPress default) this option might help your emails look better.</small>', 'wpmandrill'); ?><br/>
<?php _e('<small>You can change the value of this setting on the fly by using the <strong><a href="#" onclick="jQuery(\'a#contextual-help-link\').trigger(\'click\');return false;">wpmandrill_nl2br</a></strong> filter.</small>', 'wpmandrill'); ?>
</em></span>
</div><?php
}
static function askTags() {
echo '<div class="inside">';
$tags = self::getTags();
?><?php _e('If there are tags that you want appended to every call, list them here, one per line:', 'wpmandrill'); ?><br />
<textarea id="tags" name="wpmandrill[tags]" cols="25" rows="3"><?php echo $tags; ?></textarea><br/>
<span class="setting-description"><small><em><?php _e('Also keep in mind that you can add or remove tags using the <em><a href="#" onclick="jQuery(\'a#contextual-help-link\').trigger(\'click\');return false;">mandrill_payload</a></em> WordPress filter.', 'wpmandrill'); ?></em></small></span>
<?php
echo '</div>';
}
static function askTestEmailTo() {
echo '<div class="inside">';
?><input id='email_to' name='wpmandrill-test[email_to]' size='45' type='text' value="<?php esc_attr_e( self::getTestEmailOption('email_to') ); ?>"/><?php
echo '</div>';
}
static function askTestEmailSubject() {
echo '<div class="inside">';
?><input id='email_subject' name='wpmandrill-test[email_subject]' size='45' type='text' value="<?php esc_attr_e( self::getTestEmailOption('email_subject') ); ?>" /><?php
echo '</div>';
}
static function askTestEmailMessage() {
echo '<div class="inside">';
?><textarea rows="5" cols="45" name="wpmandrill-test[email_message]" ><?php esc_html_e( self::getTestEmailOption('email_message') ); ?></textarea><?php
echo '</div>';
}
/**
* @param string $field
* @return string|bool
*/
static function getTestEmailOption($field) {
$email = get_option('wpmandrill-test');
if( isset( $email[$field] ) )
return $email[$field];
return false;
}
/******************************************************************
** Stats-related functions
*******************************************************************/
/**
* @return array
*/
static function getRawStatistics() {
self::getConnected();
if ( !self::isConnected() ) {
error_log( date('Y-m-d H:i:s') . " wpMandrill::getRawStatistics: Not Connected to Mandrill \n" );
return array();
}
$stats = array();
$final = array();
$stats['user'] = self::$mandrill->users_info();
$data = array();
$container = self::$mandrill->tags_list();
foreach ( $container as $tag ) {
try {
$data[$tag['tag']] = self::$mandrill->tags_info($tag['tag']);
if ( count($data) >= 40 ) break;
} catch ( Exception $e ) {}
}
$stats['tags'] = $data;
$data = array();
$container = self::$mandrill->senders_list();
foreach ( $container as $sender ) {
try {
$sender_info_data = self::$mandrill->senders_info($sender['address']);
$data[$sender['address']] = $sender_info_data;
if ( count($data) >= 20 ) break;
} catch ( Exception $e ) {}
}
$stats['senders'] = $data;
$stats['urls'] = self::$mandrill->urls_list();
$final['general'] = $stats['user'];
$final['urls'] = $stats['urls'];
$final['stats'] = array();
$final['stats']['hourly']['senders'] = array();;
$final['stats']['hourly']['tags'] = array();
$final['general']['stats'] = $final['general']['stats']['all_time'];
$final['stats']['hourly']['tags']['general_stats'] = self::$mandrill->tags_all_time_series();
foreach ( array('today', 'last_7_days','last_30_days','last_60_days','last_90_days') as $timeframe) {
if ( isset($stats['user']['stats'][$timeframe]) ) $final['stats']['periods']['account'][$timeframe] = $stats['user']['stats'][$timeframe];
foreach ($stats['tags'] as $index => $entity) {
if ( !in_array($entity['tag'], $final['stats']['hourly']['tags']) )
$final['stats']['hourly']['tags']['detailed_stats'][$entity['tag']] = self::$mandrill->tags_time_series($entity['tag']);
if ( isset($entity['stats'][$timeframe]) )
$final['stats']['periods']['tags'][$timeframe][$index] = $entity['stats'][$timeframe];
}
foreach ($stats['senders'] as $index => $entity) {
if ( !in_array($entity['address'], $final['stats']['hourly']['senders']) )
$final['stats']['hourly']['senders'][$entity['address']] = self::$mandrill->senders_time_series($entity['address']);
if ( isset($entity['stats'][$timeframe]) )
$final['stats']['periods']['senders'][$timeframe][$index] = $entity['stats'][$timeframe];
}
}
return $final;
}
static function getProcessedStats() {
$stats = self::getRawStatistics();
if ( empty($stats) ) {
error_log( date('Y-m-d H:i:s') . " wpMandrill::getProcessedStats (Empty Response from ::getRawStatistics)\n" );
return $stats;
}
$graph_data = array();
for ( $i = 0; $i < 24; $i++ ) {
$graph_data['hourly']['delivered'][ sprintf('"%02s"',$i) ] = 0;
$graph_data['hourly']['opens'][ sprintf('"%02s"',$i) ] = 0;
$graph_data['hourly']['clicks'][ sprintf('"%02s"',$i) ] = 0;
$graph_data['hourly']['open_rate'][ sprintf('"%02s"',$i) ] = 0;
$graph_data['hourly']['click_rate'][ sprintf('"%02s"',$i) ] = 0;
}
for ( $i = 29; $i >= 0; $i-- ) {
$day = date('m/d', strtotime ( "-$i day" , time() ) );
$graph_data['daily']['delivered'][ sprintf('"%02s"',$day) ] = 0;
$graph_data['daily']['opens'][ sprintf('"%02s"',$day) ] = 0;
$graph_data['daily']['clicks'][ sprintf('"%02s"',$day) ] = 0;
$graph_data['daily']['open_rate'][ sprintf('"%02s"',$day) ] = 0;
$graph_data['daily']['click_rate'][ sprintf('"%02s"',$day) ] = 0;
}
$timeOffset = get_option('gmt_offset');
$timeOffset = is_numeric($timeOffset) ? $timeOffset * 3600 : 0;
foreach ( $stats['stats']['hourly']['senders'] as $data_by_sender ) {
foreach ( $data_by_sender as $data ) {
if ( isset($data['time']) ) {
$hour = '"' . date('H',strtotime($data['time'])+$timeOffset) . '"';
$day = '"' . date('m/d', strtotime($data['time'])+$timeOffset) . '"';