-
Notifications
You must be signed in to change notification settings - Fork 18
/
pay-per-view.php
3570 lines (3138 loc) · 129 KB
/
pay-per-view.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: Pay Per View
Description: Allows protecting posts/pages until visitor pays a nominal price or subscribes to the website.
Plugin URI: http://premium.wpmudev.org/project/pay-per-view
Version: 1.4.6
Author: WPMU Dev
Author URI: http://premium.wpmudev.org/
TextDomain: ppw
Domain Path: /languages/
WDP ID: 261
*/
/*
Copyright 2007-2018 Incsub (http://incsub.com)
Contributor: Hakan Evin (Incsub), Arnold Bailey (Incsub), Umesh Kumar ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License (Version 2 - GPLv2) as published by
the Free Software Foundation.
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
*/
if ( !class_exists( 'PayPerView' ) ) {
class PayPerView {
var $version = "1.4.7";
/**
* Constructor
*/
function __construct() {
// Plugin locations
$this->plugin_name = "pay-per-view";
$this->plugin_dir = plugin_dir_path( __FILE__ );
$this->plugin_url = plugin_dir_url( __FILE__ );
$this->page = 'settings_page_' . $this->plugin_name;
$this->time_format = get_option( 'time_format' );
$this->date_format = get_option( 'date_format' );
$this->datetime_format = $this->date_format . " " . $this->time_format;
// Read all options at once
$this->options = get_option( 'ppw_options' );
// We will need sessions
if ( ! session_id() ) {
@session_start();
}
register_activation_hook( __FILE__, array( $this, 'install' ) );
// Check if page can be cached
add_action( 'template_redirect', array( &$this, 'cachable' ), 1 );
// Localize the plugin
add_action( 'plugins_loaded', array( &$this, 'localization' ) );
// Initial stuff
add_action( 'init', array( &$this, 'init' ) );
// Initiate Paypal forms
add_action( 'init', array( &$this, 'initiate' ) );
// Calls post meta addition function on each save
add_action( 'save_post', array( &$this, 'add_postmeta' ) );
// Manipulate the content.
add_filter( 'the_content', array( &$this, 'content' ), 8 );
// Clear if a shortcode is left
add_filter( 'the_content', array( $this, 'clear' ), 130 );
// Send Paypal to IPN function
add_action( 'wp_ajax_ppw_paypal_ipn', array( &$this, 'process_paypal_ipn' ) );
// Send Paypal to IPN function
add_action( 'wp_ajax_nopriv_ppw_paypal_ipn', array( &$this, 'process_paypal_ipn' ) );
//Check Payment Status
add_action( 'wp_ajax_ppv_payment_status', array( &$this, 'ppv_payment_status' ) );
add_action( 'wp_head', array( &$this, 'wp_head' ) ); //Print admin ajax on head
// Admin side actions
add_action( 'admin_menu', array( &$this, 'admin_init' ) ); // Creates admin settings window
add_action( 'admin_notices', array( &$this, 'admin_notices' ) ); // Warns admin
add_action( 'add_meta_boxes', array( &$this, 'add_custom_box' ) ); // Add meta box to posts
add_filter( 'plugin_row_meta', array(
&$this,
'set_plugin_meta'
), 10, 2 );// Add settings link on plugin page
add_action( 'admin_print_scripts', array( &$this, 'admin_scripts' ) );
add_action( 'admin_print_styles', array( &$this, 'admin_css' ) );
add_action( 'wpmu_new_blog', array( $this, 'install_on_subsite' ) );
// tinyMCE stuff
add_action( 'wp_ajax_ppwTinymceOptions', array( &$this, 'tinymce_options' ) );
add_action( 'admin_init', array( &$this, 'load_tinymce' ) );
// Add/edit expiry date to user field
add_action( 'show_user_profile', array( &$this, 'edit_profile' ) );
add_action( 'edit_user_profile', array( &$this, 'edit_profile' ) );
add_action( 'personal_options_update', array( &$this, 'save_profile' ) );
add_action( 'edit_user_profile_update', array( &$this, 'save_profile' ) );
//Alway allow Wordpress login
add_action( 'wp_ajax_nopriv_ppw_ajax_login', array( &$this, 'ajax_login' ) );
// API login after the options have been initialized, Add scripts for enabled logins
if ( ! empty( $this->options['accept_api_logins'] ) && $this->options['accept_api_logins'] ) {
if ( $this->facebook_enabled() ) {
add_action( 'wp_ajax_nopriv_ppw_facebook_login', array( &$this, 'handle_facebook_login' ) );
}
if ( $this->twitter_enabled() ) {
add_action( 'wp_ajax_nopriv_ppw_get_twitter_auth_url', array(
&$this,
'handle_get_twitter_auth_url'
) );
add_action( 'wp_ajax_nopriv_ppw_twitter_login', array( &$this, 'handle_twitter_login' ) );
}
if ( $this->google_enabled() ) {
//Handle Google Login
add_action( 'wp_ajax_ppv_ggl_login', array( &$this, 'ppv_process_ggl_login' ) );
add_action( 'wp_ajax_nopriv_ppv_ggl_login', array( &$this, 'ppv_process_ggl_login' ) );
}
}
// Show DB results
global $wpdb;
$this->db = &$wpdb;
// Our DB table name
$this->table = $wpdb->prefix . "pay_per_view";
// Clear errors at start
$this->error = "";
// By default assume that pages are cachable (Cache plugins are allowed)
$this->is_cachable = true;
}
/**
* Add Settings link to the plugin page
* @ http://wpengineer.com/1295/meta-links-for-wordpress-plugins/
*/
function set_plugin_meta( $links, $file ) {
// create link
$plugin = plugin_basename( __FILE__ );
if ( $file == $plugin ) {
return array_merge(
$links,
array( sprintf( '<a href="admin.php?page=%s">%s</a>', $this->plugin_name, __( 'Settings' ) ) )
);
}
return $links;
}
/**
* Load css and javascript
* As of V1.3 this is called from "cachable" method, i.e. when it is required
*/
function load_scripts_styles() {
// Prevent caching for this page
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
define( 'DONOTCACHEPAGE', true );
}
if ( ! current_theme_supports( 'pay_per_view_style' ) ) {
$uploads = wp_upload_dir();
if ( ! $uploads['error'] && file_exists( $uploads['basedir'] . "/" . $this->plugin_name . ".css" ) ) {
wp_enqueue_style( $this->plugin_name, $uploads['baseurl'] . "/" . $this->plugin_name . ".css", array(), $this->version );
} else if ( file_exists( $this->plugin_dir . "/css/front.css" ) ) {
wp_enqueue_style( $this->plugin_name, $this->plugin_url . "/css/front.css", array(), $this->version );
}
}
wp_enqueue_script( 'jquery-cookie', $this->plugin_url . '/js/jquery.cookie-min.js', array( 'jquery' ), $this->version );
wp_register_script( 'ppw_api_js', $this->plugin_url . '/js/ppw-api.js', array( 'jquery' ), $this->version );
wp_enqueue_script( 'ppw_api_js' );
wp_localize_script( 'ppw_api_js', 'l10nPpwApi', array(
'facebook' => __( 'Login with Facebook', 'ppw' ),
'twitter' => __( 'Login with Twitter', 'ppw' ),
'google' => __( 'Login with Google', 'ppw' ),
'wordpress' => __( 'Login with WordPress', 'ppw' ),
'submit' => __( 'Submit', 'ppw' ),
'cancel' => __( 'Cancel', 'ppw' ),
'register' => __( 'Register', 'ppw' ),
'please_wait' => __( 'Please, wait...', 'ppw' ),
) );
//Facebook Script
if ( ! $this->options['facebook-no_init'] ) {
add_action( 'wp_footer', array( $this, 'wp_footer' ) );;
}
//Check and set which social logins are enabled
$logins_enabled = array(
'show_facebook' => $this->facebook_enabled(),
'show_twitter' => $this->twitter_enabled(),
'show_google' => $this->google_enabled()
);
wp_localize_script( 'ppw_api_js', 'ppw_social_logins', $logins_enabled );
if ( $this->options['allow_google_login'] && ! empty( $this->options['google-client_id'] ) ) {
wp_localize_script( 'ppw_api_js', "ppw_ggl_api", array(
'clientid' => $this->options['google-client_id'],
'cookiepolicy' => site_url()
) );
}
}
/**
* Print ajax url
* @since 1.4.0
*/
function wp_head() {
printf(
'<script type="text/javascript">var _ppw_data={"ajax_url": "%s", "root_url": "%s","register_url": "%s"};</script>',
admin_url( 'admin-ajax.php' ), plugins_url( 'pay-per-view/images/' ), wp_registration_url()
);
//Google Sign in script
if ( $this->options['allow_google_login'] && ! empty( $this->options['google-client_id'] ) ) { ?>
<meta name="google-signin-client_id" content="<?php echo $this->options['google-client_id']; ?>"/>
<meta name="google-signin-cookiepolicy" content="<?php echo site_url( '', 'http' ); ?>"/>
<meta name="google-signin-callback" content="ppv_ggl_signinCallback"/>
<meta name="google-signin-scope"
content="https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"/>
<script src="https://apis.google.com/js/platform.js" async defer>
{
"parsetags"
:
"explicit"
}
</script>
<?php
} ?>
<?php
}
function wp_footer() { ?>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({
appId: "<?php echo $this->options['facebook-app_id']; ?>",
status: true,
cookie: true,
xfbml: true
});
};
// Load the FB SDK Asynchronously
(function (d) {
var js, id = "facebook-jssdk";
if (d.getElementById(id)) {
return;
}
js = d.createElement("script");
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName("head")[0].appendChild(js);
}(document));
</script><?php
}
/**
* Login from front end
*/
function ajax_login() {
header( "Content-type: application/json" );
$user = wp_signon();
if ( ! is_wp_error( $user ) ) {
$reveal = 0;
if ( $this->is_subscription_valid( $user->ID ) OR $this->is_authorised() ) {
$reveal = 1;
}
die( json_encode( array(
"status" => 1,
"user_id" => $user->ID,
"reveal" => $reveal
) ) );
}
die( json_encode( array(
"status" => 0,
"error" => $user->get_error_message()
) ) );
}
/**
* Handles Facebook user login and creation
* Modified from Events and Bookings by S H Mohanjith
*/
function handle_facebook_login() {
header( "Content-type: application/json" );
$resp = array(
"status" => 0,
);
$fb_uid = @$_POST['user_id'];
$token = @$_POST['token'];
if ( ! $token ) {
die( json_encode( $resp ) );
}
$request = new WP_Http;
$result = $request->request(
'https://graph.facebook.com/me?fields=email,name,first_name,last_name&oauth_token=' . $token,
array( 'sslverify' => false ) // SSL certificate issue workaround
);
if ( is_wp_error( $result ) || 200 != $result['response']['code'] ) {
die( json_encode( $resp ) );
} // Couldn't fetch info
$data = json_decode( $result['body'] );
if ( ! $data->email ) {
die( json_encode( $resp ) );
} // No email, can't go further
$email = is_email( $data->email );
if ( ! $email ) {
die( json_encode( $resp ) );
} // Wrong email
if ( empty( $data->name ) ) {
$f_name = ! empty( $data->first_name ) ? preg_replace( '/[^_0-9a-z]/i', '_', strtolower( $data->first_name ) ) : '';
$l_name = ! empty( $data->last_name ) ? preg_replace( '/[^_0-9a-z]/i', '_', strtolower( $data->last_name ) ) : '';
}
$name = !empty( $data->name ) ? $data->name : ( $f_name . '_' . $l_name );
$wp_user = $this->user_from_email( $email, $name );
$user = get_userdata( $wp_user );
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID ); // Logged in with Facebook, yay
do_action( 'wp_login', $user->user_login );
// Check if user has already subscribed or authorized. Does not include Admin!!
$reveal = 0;
if ( $this->is_subscription_valid( $user->ID ) OR $this->is_authorised() ) {
$reveal = 1;
}
die( json_encode( array(
"status" => 1,
"user_id" => $user->ID,
"reveal" => $reveal
) ) );
}
/**
* Spawn a TwitterOAuth object.
*/
private function _get_twitter_object( $token = null, $secret = null ) {
// Make sure options are loaded and fresh
if ( ! $this->options['twitter-app_id'] ) {
$this->options = get_option( 'ppw_options' );
}
if ( ! class_exists( 'TwitterOAuth' ) ) {
include WP_PLUGIN_DIR . '/pay-per-view/includes/twitteroauth/twitteroauth.php';
}
$twitter = new TwitterOAuth(
$this->options['twitter-app_id'],
$this->options['twitter-app_secret'],
$token, $secret
);
return $twitter;
}
/**
* Get OAuth request URL and token.
*/
function handle_get_twitter_auth_url() {
header( "Content-type: application/json" );
$twitter = $this->_get_twitter_object();
$request_token = $twitter->getRequestToken( $_REQUEST['url'] );
//echo $request_token;
$response = array(
'url' => $twitter->getAuthorizeURL( $request_token['oauth_token'] ),
'secret' => $request_token['oauth_token_secret']
);
exit( json_encode( $response ) );
}
/**
* Login or create a new user using whatever data we get from Twitter.
*/
function handle_twitter_login() {
header( "Content-type: application/json" );
$resp = array(
"status" => 0,
);
$secret = @$_POST['secret'];
$data_str = @$_POST['data'];
$data_str = ( '?' == substr( $data_str, 0, 1 ) ) ? substr( $data_str, 1 ) : $data_str;
$data = array();
parse_str( $data_str, $data );
if ( ! $data ) {
die( json_encode( $resp ) );
}
$twitter = $this->_get_twitter_object( $data['oauth_token'], $secret );
$access = $twitter->getAccessToken( $data['oauth_verifier'] );
$twitter = $this->_get_twitter_object( $access['oauth_token'], $access['oauth_token_secret'] );
$tw_user = $twitter->get( 'account/verify_credentials' );
// Have user, now register him/her
$domain = preg_replace( '/www\./', '', parse_url( site_url(), PHP_URL_HOST ) );
$username = preg_replace( '/[^_0-9a-z]/i', '_', strtolower( $tw_user->name ) );
$email = $username . '@twitter.' . $domain; //STUB email
$wp_user = get_user_by( 'email', $email );
if ( ! $wp_user ) { // Not an existing user, let's create a new one
$password = wp_generate_password( 12, false );
$count = 0;
while ( username_exists( $username ) ) {
$username .= rand( 0, 9 );
if ( ++ $count > 10 ) {
break;
}
}
$wp_user = wp_create_user( $username, $password, $email );
if ( is_wp_error( $wp_user ) ) {
die( json_encode( $resp ) );
} // Failure creating user
} else {
$wp_user = $wp_user->ID;
}
$user = get_userdata( $wp_user );
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID ); // Logged in with Twitter, yay
do_action( 'wp_login', $user->user_login );
// Check if user has already subscribed
$reveal = 0;
if ( $this->is_subscription_valid( $user->ID ) OR $this->is_authorised() ) {
$reveal = 1;
}
die( json_encode( array(
"status" => 1,
"user_id" => $user->ID,
"reveal" => $reveal
) ) );
}
/**
* Get OAuth request URL and token.
*/
function handle_get_google_auth_url () {
header("Content-type: application/json");
$this->openid->returnUrl = $_POST['url'];
echo json_encode(array(
'url' => $this->openid->authUrl()
));
exit();
}
/**
* Login or create a new user using whatever data we get from Google.
*/
function handle_google_login () {
header("Content-type: application/json");
$resp = array(
"status" => 0,
);
$cache = $this->openid->getAttributes();
if (isset($cache['namePerson/first']) || isset($cache['namePerson/last']) || isset($cache['namePerson/friendly']) || isset($cache['contact/email'])) {
$this->_google_user_cache = $cache;
}
// Have user, now register him/her
if ( isset( $this->_google_user_cache['namePerson/friendly'] ) )
$username = $this->_google_user_cache['namePerson/friendly'];
else
$username = $this->_google_user_cache['namePerson/first'];
$email = $this->_google_user_cache['contact/email'];
$wordp_user = get_user_by('email', $email);
if (!$wordp_user) { // Not an existing user, let's create a new one
$password = wp_generate_password(12, false);
$count = 0;
while (username_exists($username)) {
$username .= rand(0,9);
if (++$count > 10) break;
}
$wordp_user = wp_create_user($username, $password, $email);
if (is_wp_error($wordp_user))
die(json_encode($resp)); // Failure creating user
else {
update_user_meta($wordp_user, 'first_name', $this->_google_user_cache['namePerson/first']);
update_user_meta($wordp_user, 'last_name', $this->_google_user_cache['namePerson/last']);
}
}
else {
$wordp_user = $wordp_user->ID;
}
$user = get_userdata($wordp_user);
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID); // Logged in with Google, yay
do_action('wp_login', $user->user_login);
// Check if user has already subscribed
$reveal = 0;
if ( get_user_meta( $user->ID, "ppw_subscribe", true) != '' OR $this->is_authorised() )
$reveal = 1;
die(json_encode(array(
"status" => 1,
"user_id"=>$user->ID,
"reveal"=>$reveal
)));
}
/**
* Saves expiry date field on user profile
*/
function save_profile( $user_id ) {
if ( ! current_user_can( 'administrator' ) ) {
return;
}
if ( isset( $_POST["ppw_expiry"] ) ) {
update_user_meta( $user_id, 'ppw_subscribe', trim( $_POST['ppw_expiry'] ) );
}
if ( isset( $_POST["ppw_days"] ) ) {
update_user_meta( $user_id, 'ppw_days', trim( $_POST['ppw_days'] ) );
}
if ( isset( $_POST["ppw_period"] ) ) {
update_user_meta( $user_id, 'ppw_period', trim( $_POST['ppw_period'] ) );
}
}
/**
* Displays expiry date on the user profile
*/
function edit_profile( $current_user ) {
?>
<h3><?php _e( "Pay Per View Subscription", "ppw" ); ?></h3>
<table class="form-table">
<tr>
<th><label for="address"><?php _e( "Expires at" ); ?></label></th>
<td>
<?php
$expiry = get_user_meta( $current_user->ID, 'ppw_subscribe', true );
$days = get_user_meta( $current_user->ID, 'ppw_days', true );
$period = get_user_meta( $current_user->ID, 'ppw_period', true );
$readonly = ( ! current_user_can( 'administrator' ) ) ? "readonly" : "";
?>
<input type="text" name="ppw_expiry" value="<?php echo $expiry ?>" <?php echo $readonly; ?> />
</td>
</tr>
<tr>
<th><label for="address"><?php _e( "Recurring days" ); ?></label></th>
<td>
<input type="text" name="ppw_days" value="<?php echo $days ?>" <?php echo $readonly; ?> />
<input type="radio" name="ppw_period"
value="D" <?php echo checked( $period == "D" || empty( $period ) ); ?> <?php echo $readonly; ?> />Days
<input type="radio" name="ppw_period"
value="W" <?php echo checked( $period == "W" ); ?> <?php echo $readonly; ?> />Weeks
<input type="radio" name="ppw_period"
value="M" <?php echo checked( $period == "M" ); ?> <?php echo $readonly; ?> />Months
<input type="radio" name="ppw_period"
value="Y" <?php echo checked( $period == "Y" ); ?> <?php echo $readonly; ?> />Years
</td>
</tr>
</table>
<?php
}
/**
* Installs database table
*/
function install( $network_wide ) {
if ( ( function_exists( 'is_multisite' ) && is_multisite() ) && $network_wide ) {
$blogs = get_sites();
foreach ( $blogs as $blog ) {
switch_to_blog( $blog->blog_id );
$this->create_table();
restore_current_blog();
}
} else {
$this->create_table();
}
}
/**
* Installs database table on new blog/site creation on multisite
*/
function install_on_subsite( $blog_id ){
//No need to check for is_plugin_active_for_network
//since it will not be active at all on wpmu_new_blog
switch_to_blog( $blog_id );
$this->create_table();
restore_current_blog();
}
/**
* Create Table
*
*/
function create_table() {
global $wpdb;
$sql = "CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "pay_per_view" . "` (
`transaction_ID` bigint(20) unsigned NOT NULL auto_increment,
`transaction_post_ID` bigint(20) NOT NULL default '0',
`transaction_user_ID` bigint(20) NOT NULL default '0',
`transaction_content_ID` bigint(20) default '0',
`transaction_paypal_ID` varchar(30) default NULL,
`transaction_payment_type` varchar(20) default NULL,
`transaction_stamp` bigint(35) NOT NULL default '0',
`transaction_total_amount` bigint(20) default NULL,
`transaction_currency` varchar(35) default NULL,
`transaction_status` varchar(35) default NULL,
`transaction_duedate` date default NULL,
`transaction_gateway` varchar(50) default NULL,
`transaction_note` text,
`transaction_expires` datetime default NULL,
PRIMARY KEY (`transaction_ID`),
KEY `transaction_gateway` (`transaction_gateway`),
KEY `transaction_post_ID` (`transaction_post_ID`),
KEY `transaction_user_ID` (`transaction_user_ID`)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
/**
* Localize the plugin
*/
function localization() {
// Load up the localization file if we're using WordPress in a different language
// Place it in this plugin's "languages" folder and name it "ppw-[value in wp-config].mo"
load_plugin_textdomain( 'ppw', false, '/pay-per-view/languages/' );
}
/**
* Provide options if asked outside the class
*/
function get_options() {
return $this->options;
}
/**
* Save a message to the log file
*/
function log( $message = '' ) {
// Don't give warning if folder is not writable
@file_put_contents( WP_PLUGIN_DIR . "/pay-per-view/log.txt", $message . chr( 10 ) . chr( 13 ), FILE_APPEND );
}
/**
* Checks if user is authorised by the admin
*/
function is_authorised() {
$result = false;
if ( $this->options['authorized'] == 'true' && is_user_logged_in() && !current_user_can('administrator') ) {
if ( $this->options['level'] == 'subscriber' && current_user_can( 'read' ) ){
$result = true;
}else if ( $this->options['level'] == 'contributor' && current_user_can( 'edit_posts' ) ){
$result = true;
}else if ( $this->options['level'] == 'author' && current_user_can( 'edit_published_posts' ) ){
$result = true;
}else if ( $this->options['level'] == 'editor' && current_user_can( 'edit_others_posts' ) ){
$result = true;}
}
$result = apply_filters( 'ppv_authorized_role', $result, $this->options );
return $result;
}
/**
* Check if page can be cached or not
*
*/
function cachable() {
global $post;
// If plugin is enabled for this post/page, it is not cachable
if ( is_object( $post ) && is_singular() ) {
$post_meta = get_post_meta( $post->ID, 'ppw_enable', true );
if ( $post->post_type == 'page' ) {
$default = $this->options["page_default"];
} else if ( $post->post_type == 'post' ) {
$default = $this->options["post_default"];
} else if ( $post->post_type != 'attachment' ) {
$default = $this->options["custom_default"];
} // New in V1.2
else {
$default = '';
}
if ( $post_meta == 'enable' || ( $default == 'enable' && $post_meta != 'disable' ) ) {
$this->is_cachable = false;
}
} else if ( $this->options["multi"] && ! is_home() ) {
$this->is_cachable = false;
}
if ( is_home() && $this->options["home"] ) {
$this->is_cachable = false;
}
// Load css files and scripts when they are neccesary
if ( ! $this->is_cachable ) {
$this->load_scripts_styles();
}
}
/**
* Checks if user can see the content, if chosen method is not tool
*
* @param $post
* @param $content
* @param $method
*
* @return mixed
*/
function subscription_status( $post, $method ) {
$settings = get_option( 'ppw_options' );
$duration = !empty( $settings['cookie']) ? $settings['cookie'] * 3600 : 7200;
// If user paid, show content. 'Tool' option has its own logic
if ( isset( $_COOKIE["pay_per_view"] ) && $method != 'tool' ) {
// On some installations slashes are added while serializing. So get rid of them.
$orders = unserialize( stripslashes( $_COOKIE["pay_per_view"] ) );
if ( is_array( $orders ) ) {
$found = false;
// Let's first check if post ID matches. If not, we save to make DB calls which are expensive
foreach ( $orders as $order ) {
if ( is_object( $post ) && $post->ID == $order["post_id"] ) {
$found = true;
break;
}
}
// If $found:true, user has a cookie which matches to the post.
// But we have to be sure that visitor did not play with it.
if ( $found ) {
global $wpdb;
$query = '';
foreach ( $orders as $order ) {
//Escape everything
$query .= $wpdb->prepare( " SELECT * FROM " . $this->table .
" WHERE transaction_post_ID=%d
AND transaction_paypal_ID=%s
AND ( transaction_status='Paid' OR transaction_status='Pending' )
AND %d < transaction_stamp UNION",
$order['post_id'],
$order['order_id'],
( time() - $duration ) );
}
// Get rid of the last UNION
$query = rtrim( $query, "UNION" );
$result = $wpdb->get_results( $query );
return $result;
}
}
}
}
/**
* Changes the content according to selected settings
*
*/
function content( $content, $force = false, $method = '' ) {
global $post;
// Unsupported post type. Maybe a temporary page, like checkout of MarketPress
if ( ! is_object( $post ) && ! $content ) {
return;
}
// If caching is allowed no need to continue
if ( $this->is_cachable && ! $force ) {
return $this->clear( $content );
}
// Display the admin full content, if selected so
if ( $this->options["admin"] == 'true' && current_user_can( 'administrator' ) ) {
return $this->clear( $content );
}
// Display the bot full content, if selected so
if ( $this->options["bot"] == 'true' && $this->is_bot() ) {
return $this->clear( $content );
}
// Check if current user has been authorized to see full content
if ( $this->is_authorised() ) {
return $this->clear( $content );
}
$is_subscription_valid = $this->is_subscription_valid( get_current_user_id() );
// If user has already subscribed content
if ( is_user_logged_in() && $is_subscription_valid ) {
return $this->clear( $content );
}
//PDT Integration
if ( is_user_logged_in() && ! empty( $_GET['ppw_paypal_subscribe'] ) && ! empty( $_GET['tx'] ) && ! empty( $_GET['st'] ) ) {
$ppl = $this->call_gateway();
//Get Transaction Details
$transaction_details = $ppl->pdt_get_transaction_details( $_GET['tx'], $this->options['gateways']['paypal-express']['identity_token'] );
$transaction_details = $this->process_pdt_response( $transaction_details );
//Check Status
if ( ! empty( $transaction_details['status'] ) && $transaction_details['status'] == 'success' ) {
//Update Subscription and show the content
$this->update_subscription( $transaction_details );
//Show the content
return $this->clear( $content );
} else {
//Store Payment pending message in $_SESSION, we can use this to display a message
$_SESSION['ppv_payment_status'] = 'pending';
$_SESSION['ppv_message'] = ! empty( $transaction_details['message'] ) ? $transaction_details['message'] : '';
}
}
// Find method if it is not forced
if ( ! $method && is_object( $post ) ) {
$method = get_post_meta( $post->ID, 'ppw_method', true );
}
// Apply default method, if there is none
if ( ! $method ) {
$method = $this->options["method"];
}
//Get content as per the method and permissions
$result = $this->subscription_status( $post, $method );
if ( $result ) {
// Visitor did paid for this content!
return $this->clear( $content );
}
// If we are here, it means content will be restricted.
// Now prepare the restricted output
if ( $method == "automatic" ) {
$content = preg_replace( '%\[ppw(.*?)\](.*?)\[( *)\/ppw( *)\]%is', '$2', $content ); // Clean shortcode
$temp_arr = explode( " ", $content );
// If the article is shorter than excerpt, show full content
if ( ! $excerpt_len = get_post_meta( $post->ID, 'ppw_excerpt', true ) ) {
$excerpt_len = $this->options["excerpt"];
}
if ( count( $temp_arr ) <= $excerpt_len ) {
return $this->clear( $content );
}
// Otherwise prepare excerpt
$e = "";
for ( $n = 0; $n < $excerpt_len; $n ++ ) {
$e .= $temp_arr[ $n ] . " ";
}
// If a tag is broken, try to complete it within reasonable limits, i.e. in next 50 words
if ( substr_count( $e, '<' ) != substr_count( $e, '>' ) ) {
// Save existing excerpt
$e_saved = $e;
$found = false;
for ( $n = $excerpt_len; $n < $excerpt_len + 50; $n ++ ) {
if ( isset( $temp_arr[ $n ] ) ) {
$e .= $temp_arr[ $n ] . " ";
if ( substr_count( $e, '<' ) == substr_count( $e, '>' ) ) {
$found = true;
break;
}
}
}
// Revert back to original excerpt if a fix is not found
if ( ! $found ) {
$e = $e_saved;
}
}
// Find the price
if ( ! $price = get_post_meta( $post->ID, "ppw_price", true ) ) {
$price = $this->options["price"];
} // Apply default price if it is not set for the post/page
return $e . $this->mask( $price );
} else if ( $method == "manual" ) {
// Find the price
if ( ! $price = get_post_meta( $post->ID, "ppw_price", true ) ) {
$price = $this->options["price"];
}
return $post->post_excerpt . $this->mask( $price );
} else if ( $method == "tool" ) {
$contents = array();
if ( preg_match_all( '%\[ppw( +)id="(.*?)"( +)description="(.*?)"( +)price="(.*?)"(.*?)\](.*?)\[( *)\/ppw( *)\]%is', $content, $matches, PREG_SET_ORDER ) ) {
if ( isset( $_COOKIE["pay_per_view"] ) ) {
$orders = unserialize( stripslashes( $_COOKIE["pay_per_view"] ) );
if ( is_array( $orders ) ) {
foreach ( $orders as $order ) {
if ( is_object( $post ) && $order["post_id"] == $post->ID ) {
$contents[] = $order["content_id"];
} // Take only values related to this post
}
}
}
// Prepare the content
foreach ( $matches as $m ) {
if ( in_array( $m[2], $contents ) ) {
// This is paid
$content = str_replace( $m[0], $m[8], $content );
} else {
$content = str_replace( $m[0], $this->mask( $m[6], $m[2], $m[4] ), $content );
}
}
}
return $this->clear( $content );
}
// Script cannot come to this point, but just in case.
return $this->clear( $content );
}
/**
* Try to clear remaining shortcodes
*
*/
function clear( $content ) {
// Don't even try to touch an object, just in case
if ( is_object( $content ) ) {
return $content;
} else {
$content = preg_replace( '%\[ppw(.*?)\]%is', '', $content );
$content = preg_replace( '%\[\/ppw\]%is', '', $content );
return $content;
}
}
/**
* Initiates an instance of the Paypal gateway
*/
function call_gateway() {
include_once( WP_PLUGIN_DIR . "/pay-per-view/includes/paypal-express.php" );
$post_id = ! empty( $_SESSION["ppw_post_id"] ) ? $_SESSION["ppw_post_id"] : '';
$P = new PPW_Gateway_Paypal_Express( $post_id );
return $P; // return Gateway object
}
/**
* This just makes error call compatible to gateway class
*/
function error( $text ) {
$this->error = $text;
}
/**
* Prepare the mask/template which includes payment form(s)
*