-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtls-web-push.php
More file actions
368 lines (301 loc) · 12.7 KB
/
tls-web-push.php
File metadata and controls
368 lines (301 loc) · 12.7 KB
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
<?php
/**
* Plugin Name: TLS Web Push
* Plugin URI: https://example.com
* Description: Web push notifications for promoting weekly articles, special offers, and product packs with comprehensive analytics tracking.
* Version: 1.0.0
* Author: Varun Kumar
* Author URI: https://example.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: tls-web-push
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Load Composer autoloader for web-push library
if (file_exists(plugin_dir_path(__FILE__) . 'vendor/autoload.php')) {
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
}
// Define plugin constants
define('TLS_WEB_PUSH_VERSION', '1.0.0');
define('TLS_WEB_PUSH_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('TLS_WEB_PUSH_PLUGIN_URL', plugin_dir_url(__FILE__));
class TLS_Web_Push {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// Activation and deactivation hooks
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// Initialize plugin
add_action('plugins_loaded', array($this, 'init'));
}
public function init() {
// Load dependencies with error handling
if (!$this->load_dependencies()) {
add_action('admin_notices', array($this, 'show_dependency_error'));
return;
}
// Admin hooks
if (is_admin()) {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
// Frontend hooks
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
// AJAX hooks
add_action('wp_ajax_tls_subscribe_push', array($this, 'handle_subscription'));
add_action('wp_ajax_nopriv_tls_subscribe_push', array($this, 'handle_subscription'));
add_action('wp_ajax_tls_unsubscribe_push', array($this, 'handle_unsubscription'));
add_action('wp_ajax_nopriv_tls_unsubscribe_push', array($this, 'handle_unsubscription'));
add_action('wp_ajax_tls_send_push_notification', array($this, 'send_notification'));
add_action('wp_ajax_tls_track_notification_click', array($this, 'track_notification_click'));
add_action('wp_ajax_nopriv_tls_track_notification_click', array($this, 'track_notification_click'));
add_action('wp_ajax_tls_track_push_event', array($this, 'track_push_event'));
add_action('wp_ajax_nopriv_tls_track_push_event', array($this, 'track_push_event'));
}
private function load_dependencies() {
$files = array(
'includes/class-database.php',
'includes/class-analytics.php',
'includes/class-notification-sender.php'
);
foreach ($files as $file) {
$file_path = TLS_WEB_PUSH_PLUGIN_DIR . $file;
if (!file_exists($file_path)) {
error_log('TLS Web Push: Missing file - ' . $file);
return false;
}
require_once $file_path;
}
return true;
}
public function show_dependency_error() {
echo '<div class="notice notice-error"><p><strong>TLS Web Push:</strong> Plugin files are missing. Please reinstall the plugin.</p></div>';
}
public function activate() {
// Load database class for activation
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'includes/class-database.php';
// Create tables
TLS_Web_Push_Database::create_tables();
// Set default options
if (!get_option('tls_web_push_vapid_public_key')) {
add_option('tls_web_push_vapid_public_key', '');
}
if (!get_option('tls_web_push_vapid_private_key')) {
add_option('tls_web_push_vapid_private_key', '');
}
}
public function deactivate() {
// Cleanup tasks if needed
}
public function add_admin_menu() {
add_menu_page(
'Web Push Notifications',
'Web Push',
'manage_options',
'tls-web-push',
array($this, 'render_admin_page'),
'dashicons-megaphone',
30
);
add_submenu_page(
'tls-web-push',
'Send Notification',
'Send Notification',
'manage_options',
'tls-web-push-send',
array($this, 'render_send_page')
);
add_submenu_page(
'tls-web-push',
'Analytics',
'Analytics',
'manage_options',
'tls-web-push-analytics',
array($this, 'render_analytics_page')
);
add_submenu_page(
'tls-web-push',
'Settings',
'Settings',
'manage_options',
'tls-web-push-settings',
array($this, 'render_settings_page')
);
add_submenu_page(
'tls-web-push',
'Preview Notification',
'Preview',
'manage_options',
'tls-web-push-preview',
array($this, 'render_preview_page')
);
}
public function enqueue_admin_scripts($hook) {
if (strpos($hook, 'tls-web-push') === false) {
return;
}
wp_enqueue_style('tls-web-push-admin', TLS_WEB_PUSH_PLUGIN_URL . 'assets/css/admin.css', array(), TLS_WEB_PUSH_VERSION);
wp_enqueue_script('tls-web-push-admin', TLS_WEB_PUSH_PLUGIN_URL . 'assets/js/admin.js', array('jquery'), TLS_WEB_PUSH_VERSION, true);
wp_localize_script('tls-web-push-admin', 'tlsWebPush', array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('tls_web_push_nonce')
));
}
public function enqueue_frontend_scripts() {
// Register service worker
wp_enqueue_script('tls-web-push-frontend', TLS_WEB_PUSH_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), TLS_WEB_PUSH_VERSION, true);
$vapid_public_key = get_option('tls_web_push_vapid_public_key', '');
wp_localize_script('tls-web-push-frontend', 'tlsWebPushConfig', array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('tls_web_push_nonce'),
'vapidPublicKey' => $vapid_public_key,
'serviceWorkerUrl' => TLS_WEB_PUSH_PLUGIN_URL . 'service-worker.js'
));
wp_enqueue_style('tls-web-push-frontend', TLS_WEB_PUSH_PLUGIN_URL . 'assets/css/frontend.css', array(), TLS_WEB_PUSH_VERSION);
}
public function handle_subscription() {
check_ajax_referer('tls_web_push_nonce', 'nonce');
// Try to get subscription from POST data first
$subscription_json = isset($_POST['subscription']) ? stripslashes($_POST['subscription']) : file_get_contents('php://input');
$subscription = json_decode($subscription_json, true);
if (!$subscription || !isset($subscription['endpoint'])) {
wp_send_json_error('Invalid subscription data');
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'tls_push_subscriptions';
// Check if subscription already exists
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_name WHERE endpoint = %s",
$subscription['endpoint']
));
if ($existing) {
wp_send_json_success('Already subscribed');
return;
}
// Insert new subscription
$result = $wpdb->insert(
$table_name,
array(
'endpoint' => $subscription['endpoint'],
'auth_key' => isset($subscription['keys']['auth']) ? $subscription['keys']['auth'] : '',
'p256dh_key' => isset($subscription['keys']['p256dh']) ? $subscription['keys']['p256dh'] : '',
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
'ip_address' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
'created_at' => current_time('mysql')
),
array('%s', '%s', '%s', '%s', '%s', '%s')
);
if ($result) {
// Track opt-in
if (class_exists('TLS_Web_Push_Analytics')) {
TLS_Web_Push_Analytics::track_opt_in_presented();
TLS_Web_Push_Analytics::track_opt_in_accepted();
}
wp_send_json_success('Subscription saved');
} else {
wp_send_json_error('Failed to save subscription: ' . $wpdb->last_error);
}
}
public function handle_unsubscription() {
check_ajax_referer('tls_web_push_nonce', 'nonce');
// Try to get endpoint from POST data first
$endpoint = isset($_POST['endpoint']) ? $_POST['endpoint'] : '';
if (empty($endpoint)) {
$data = json_decode(file_get_contents('php://input'), true);
$endpoint = isset($data['endpoint']) ? $data['endpoint'] : '';
}
if (empty($endpoint)) {
wp_send_json_error('Invalid data');
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'tls_push_subscriptions';
$result = $wpdb->delete(
$table_name,
array('endpoint' => $endpoint),
array('%s')
);
if ($result) {
wp_send_json_success('Unsubscribed');
} else {
wp_send_json_error('Failed to unsubscribe');
}
}
public function send_notification() {
check_ajax_referer('tls_web_push_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error('Unauthorized');
return;
}
$title = sanitize_text_field($_POST['title'] ?? '');
$message = sanitize_textarea_field($_POST['message'] ?? '');
$url = esc_url_raw($_POST['url'] ?? home_url());
$icon = esc_url_raw($_POST['icon'] ?? '');
if (empty($title) || empty($message)) {
wp_send_json_error('Title and message are required');
return;
}
$sender = new TLS_Web_Push_Notification_Sender();
$result = $sender->send_to_all($title, $message, $url, $icon);
wp_send_json_success(array(
'sent' => $result['sent'],
'failed' => $result['failed'],
'total' => $result['total']
));
}
public function track_notification_click() {
$notification_id = intval($_POST['notification_id'] ?? 0);
if ($notification_id > 0) {
TLS_Web_Push_Analytics::track_notification_click($notification_id);
}
wp_send_json_success();
}
public function track_push_event() {
$event_type = sanitize_text_field($_POST['event_type'] ?? '');
if (empty($event_type)) {
wp_send_json_error('Event type required');
return;
}
if (class_exists('TLS_Web_Push_Analytics')) {
switch ($event_type) {
case 'opt_in_presented':
TLS_Web_Push_Analytics::track_opt_in_presented();
break;
case 'opt_in_accepted':
TLS_Web_Push_Analytics::track_opt_in_accepted();
break;
case 'opt_in_declined':
TLS_Web_Push_Analytics::track_opt_in_declined();
break;
}
}
wp_send_json_success();
}
public function render_admin_page() {
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'templates/admin-dashboard.php';
}
public function render_send_page() {
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'templates/admin-send.php';
}
public function render_analytics_page() {
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'templates/admin-analytics.php';
}
public function render_settings_page() {
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'templates/admin-settings.php';
}
public function render_preview_page() {
require_once TLS_WEB_PUSH_PLUGIN_DIR . 'templates/notification-preview.php';
}
}
// Initialize plugin
TLS_Web_Push::get_instance();