Repository navigation
Expand file tree
/
Copy pathpixelflow.php
More file actions
869 lines (763 loc) · 31.8 KB
/
Copy pathpixelflow.php
File metadata and controls
869 lines (763 loc) · 31.8 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
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
<?php
/**
* Plugin Name: PixelFlow – Meta & TikTok Pixel + Conversions API for WooCommerce
* Description: Facebook Pixel & TikTok Pixel with server-side Conversions API (CAPI) for WooCommerce & WordPress. Auto-tracks sales & forms. No code, no GTM.
* Version: 1.2.3
* Requires at least: 6.5
* Requires PHP: 7.4
* Author: PixelFlow Team
* Author URI: https://pixelflow.so/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: pixelflow
* Domain Path: /languages
*/
// Prevent direct access
if ( ! defined('ABSPATH')) {
exit;
}
// Define plugin constants
define('PIXELFLOW_VERSION', '1.2.3');
define('PIXELFLOW_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PIXELFLOW_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('PIXELFLOW_PLUGIN_BASENAME', plugin_basename(__FILE__));
/**
* Main PixelFlow class
*/
class PixelFlow
{
/**
* Script handle for the tracking script
*
* @var string
*/
private $tracking_script_handle = 'pixelflow-tracking';
/**
* Single instance of the class
*/
private static $instance = null;
/**
* Get single instance
*/
public static function get_instance()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct()
{
$this->load_dependencies();
pixelflow_forms_bootstrap();
add_action('plugins_loaded', 'pixelflow_register_wp_consent_api_consumer');
add_action('init', 'pixelflow_register_consent_cookie_info');
add_action('init', array($this, 'init'));
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_init', array($this, 'migrate_product_id_format'));
add_action('admin_init', array($this, 'handle_disable_debug_action'));
add_action('admin_notices', array($this, 'display_debug_notice'));
add_action('admin_notices', array($this, 'display_unconfigured_notice'));
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
add_action('wp_print_scripts', array($this, 'inject_script'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_held_events_script'));
add_filter('plugin_action_links_' . PIXELFLOW_PLUGIN_BASENAME, array($this, 'add_plugin_action_links'));
// AJAX handlers
add_action('wp_ajax_pixelflow_save_settings', array($this, 'ajax_save_settings'));
add_action('wp_ajax_pixelflow_get_settings', array($this, 'ajax_get_settings'));
add_action('wp_ajax_pixelflow_save_script_params', array($this, 'ajax_save_script_params'));
add_action('wp_ajax_pixelflow_remove_script_params', array($this, 'ajax_remove_script_params'));
add_action('wp_ajax_pixelflow_clear_debug_log', array($this, 'ajax_clear_debug_log'));
add_action('wp_ajax_pixelflow_get_debug_log', array($this, 'ajax_get_debug_log'));
add_action('wp_ajax_pixelflow_resolve_held_events', array($this, 'ajax_resolve_held_events'));
add_action('wp_ajax_nopriv_pixelflow_resolve_held_events', array($this, 'ajax_resolve_held_events'));
}
/**
* Load dependencies
*/
private function load_dependencies()
{
// Load WooCommerce integration
require_once PIXELFLOW_PLUGIN_PATH . 'includes/helpers.php';
require_once PIXELFLOW_PLUGIN_PATH . 'includes/consent.php';
require_once PIXELFLOW_PLUGIN_PATH . 'includes/blocked-events.php';
require_once PIXELFLOW_PLUGIN_PATH . 'includes/held-events.php';
require_once PIXELFLOW_PLUGIN_PATH . 'includes/forms/forms.php';
require_once PIXELFLOW_PLUGIN_PATH . 'includes/woo/class-woocommerce-integration.php';
}
/**
* Initialize plugin
*/
public function init()
{
// Initialize WooCommerce integration if enabled
if (PixelFlow_WooCommerce_Integration::is_woocommerce_active()) {
PixelFlow_WooCommerce_Integration::get_instance();
}
}
/**
* Enqueue admin scripts and styles
*/
public function admin_enqueue_scripts($hook)
{
if ($hook === 'settings_page_pixelflow-settings') {
// Prepare settings for the admin app
$pixelflow_general_options = get_option('pixelflow_general_options', array());
$debug_options = get_option('pixelflow_debug_options', array());
$script_params = get_option('pixelflow_script_params', '');
$config = pixelflow_config();
$settings = array(
'general_options' => $pixelflow_general_options,
'debug_options' => $debug_options,
'script_params' => $script_params,
'nonce' => wp_create_nonce('pixelflow_settings_nonce'),
'ajax_url' => admin_url('admin-ajax.php'),
'is_woocommerce_active' => PixelFlow_WooCommerce_Integration::is_woocommerce_active(),
'woo_debug_log_url' => $this->get_debug_log_url(),
// PixelFlow service addresses of this build; the admin bundle carries none.
'config' => array(
'apiBaseUrl' => $config['api_url'] ?? '',
'uiBaseUrl' => $config['ui_url'] ?? '',
'cdnUrl' => $config['cdn_url'] ?? '',
),
);
// Paths and versions
$js_path = plugin_dir_path(__FILE__) . 'app/dist/index.js';
$css_path = plugin_dir_path(__FILE__) . 'app/dist/style.css';
$js_url = PIXELFLOW_PLUGIN_URL . 'app/dist/index.js';
$css_url = PIXELFLOW_PLUGIN_URL . 'app/dist/style.css';
$js_version = file_exists($js_path) ? filemtime($js_path) : PIXELFLOW_VERSION;
$css_version = file_exists($css_path) ? filemtime($css_path) : PIXELFLOW_VERSION;
$script_key = 'pixelflow-admin';
// Register and enqueue style
wp_register_style($script_key, $css_url, array(), $css_version);
wp_enqueue_style($script_key);
// Register and enqueue script as ES module
wp_enqueue_script_module($script_key, $js_url, array(), $js_version);
// Mark as module (WP >= 6.3 supports 'type' data)
wp_script_add_data($script_key, 'type', 'module');
// Provide settings before the script executes
wp_register_script($script_key, '', array(), PIXELFLOW_VERSION, array('in_footer' => false));
$inline = 'window.pixelflowSettings = ' . wp_json_encode($settings) . ';';
wp_add_inline_script($script_key, $inline, 'before');
wp_enqueue_script($script_key);
}
}
/**
* Add admin menu
*/
public function add_admin_menu()
{
add_options_page(
__('PixelFlow Settings', 'pixelflow'),
__('PixelFlow Settings', 'pixelflow'),
'manage_options',
'pixelflow-settings',
array($this, 'settings_page')
);
}
/**
* Register settings
*/
public function register_settings()
{
register_setting('pixelflow_settings', 'pixelflow_general_options', array($this, 'sanitize_general_options'));
register_setting('pixelflow_settings', 'pixelflow_debug_options', array($this, 'sanitize_debug_options'));
}
public function migrate_product_id_format()
{
if (get_option('pixelflow_migration_product_id_format_done')) {
return;
}
$opts = get_option('pixelflow_general_options', array());
// Only migrate already-configured installs. On a fresh install the option does not
// exist yet, and creating it here would make the settings page treat the plugin as
// "configured" (showing the options panel before the user has even logged in).
if (is_array($opts) && ! empty($opts) && ! isset($opts['woo_product_id_format'])) {
$opts['woo_product_id_format'] = ! empty($opts['woo_enabled']) ? 'legacy' : 'product_id';
update_option('pixelflow_general_options', $opts);
}
update_option('pixelflow_migration_product_id_format_done', 1, true);
}
/**
* Sanitize options
*/
/**
* Sanitize general options (enabled/disabled toggles)
*/
public function sanitize_general_options($input)
{
$sanitized = array();
// Define general checkbox options
$checkbox_options = array(
'enabled',
'woo_enabled',
'woo_purchase_tracking',
'debug_enabled',
'remove_on_uninstall',
'woo_disable_add_to_cart',
'woo_disable_initiate_checkout',
'woo_disable_purchase',
'woo_disable_add_to_cart_freebies',
'woo_disable_initiate_checkout_freebies',
'woo_disable_purchase_freebies',
'woo_purchase_first_only',
'woo_debug_enabled',
'forms_enabled',
'forms_debug_enabled',
);
// Set all checkboxes: 1 if checked, 0 if not
foreach ($checkbox_options as $option) {
$sanitized[$option] = isset($input[$option]) && $input[$option] ? 1 : 0;
}
// Sanitize excluded_user_roles (array of role keys)
if (isset($input['excluded_user_roles'])) {
if ( ! is_array($input['excluded_user_roles'])) {
$input['excluded_user_roles'] = explode(',', $input['excluded_user_roles']);
}
$sanitized['excluded_user_roles'] = array_map('sanitize_text_field', $input['excluded_user_roles']);
}
// Sanitize woo_excluded_skus (comma-separated string → filtered array of non-empty SKUs)
if (isset($input['woo_excluded_skus'])) {
if ( ! is_array($input['woo_excluded_skus'])) {
$input['woo_excluded_skus'] = explode(',', $input['woo_excluded_skus']);
}
$sanitized['woo_excluded_skus'] = array_values(
array_filter(array_map('sanitize_text_field', $input['woo_excluded_skus']))
);
}
// Sanitize woo_product_id_format
$allowed_formats = ['product_id', 'prefixed', 'sku', 'legacy', 'off'];
$sanitized['woo_product_id_format'] = in_array($input['woo_product_id_format'] ?? '', $allowed_formats, true)
? $input['woo_product_id_format']
: 'product_id';
$stored = get_option('pixelflow_general_options', array());
$sanitized += pixelflow_sanitize_first_purchase_options(
is_array($input) ? $input : array(),
is_array($stored) ? $stored : array()
);
return $sanitized;
}
/**
* Inject script into wp_head
*/
public function inject_script()
{
if (is_admin()) {
return;
}
$pixelflow_general_options = get_option('pixelflow_general_options', array());
// Only inject if enabled and user role is not excluded
if (isset($pixelflow_general_options['enabled']) && $pixelflow_general_options['enabled']) {
// Check if current user's role should be excluded
if ( ! $this->should_exclude_current_user($pixelflow_general_options)) {
// Get saved parameters
$params = get_option('pixelflow_script_params', array());
// Only enqueue if params exist
if ( ! empty($params)) {
// Extract parameters
$site_external_id = isset($params['siteExternalId']) ? $params['siteExternalId'] : '';
$api_key = isset($params['apiKey']) ? $params['apiKey'] : '';
$script = pixelflow_tracking_snippet((string) $site_external_id, (string) $api_key, pixelflow_config());
// Empty without both credentials or without a configuration
if ($script !== '') {
$script = apply_filters('pixelflow_analytics_code', $script);
wp_register_script(
$this->tracking_script_handle,
'',
array(),
PIXELFLOW_VERSION,
array('in_footer' => false)
);
wp_add_inline_script($this->tracking_script_handle, $script, 'before');
wp_enqueue_script($this->tracking_script_handle);
}
}
}
}
}
/**
* Storefront script that flushes the Woo hold queue after a same-page grant or deny.
*
* @return void
*/
public function enqueue_held_events_script()
{
if (is_admin()) {
return;
}
$general = get_option('pixelflow_general_options', array());
if (empty($general['enabled']) || empty($general['woo_enabled'])) {
return;
}
if ($this->should_exclude_current_user($general)) {
return;
}
$params = get_option('pixelflow_script_params', array());
if (empty($params['siteExternalId']) || empty($params['apiKey'])) {
return;
}
$handle = 'pixelflow-held-events';
wp_register_script(
$handle,
PIXELFLOW_PLUGIN_URL . 'assets/js/held-events.js',
array(),
PIXELFLOW_VERSION,
true
);
// No nonce is baked into the page: this HTML may be served from a full-page
// cache long after the nonce it carried expired. The script asks the state
// route for a fresh one at the moment it is about to flush.
wp_localize_script(
$handle,
'pixelflowHeldEvents',
array(
'stateUrl' => $this->wc_ajax_endpoint('pixelflow_held_state'),
'flushUrl' => $this->wc_ajax_endpoint('pixelflow_resolve_held_events'),
'holdCookie' => PIXELFLOW_NO_CONSENT_DECISION_COOKIE_NAME,
'holdValue' => PIXELFLOW_NO_CONSENT_DECISION_COOKIE_VALUE,
'heldCookie' => PIXELFLOW_HELD_WOO_EVENTS_COOKIE_NAME,
)
);
wp_enqueue_script($handle);
}
/**
* WooCommerce AJAX endpoint URL, which skips the admin bootstrap and is the
* route cache plugins already know to leave alone.
*
* @param string $action wc-ajax action name
*
* @return string
*/
private function wc_ajax_endpoint($action)
{
if (class_exists('WC_AJAX')) {
return WC_AJAX::get_endpoint($action);
}
return add_query_arg('wc-ajax', $action, home_url('/'));
}
/**
* Same-page grant or deny: flush or beacon the Woo session queue.
*
* Deprecated alias of the `wc-ajax` route, kept for one release so storefront
* pages cached before this version keep flushing. Remove in the next release.
*
* @return void
*/
public function ajax_resolve_held_events()
{
check_ajax_referer('pixelflow_held_events', 'nonce');
if (class_exists('PixelFlow_WooCommerce_Cart_Hooks')) {
$hooks = PixelFlow_WooCommerce_Cart_Hooks::instance();
if ($hooks !== null) {
$session = pixelflow_woo_session();
if ($session !== null && method_exists($session, 'init_session_cookie')) {
$session->init_session_cookie();
}
$hooks->resolve_held_events();
}
}
wp_send_json_success();
}
/**
* Check if the current user's role is in the excluded list
*
* @param array $pixelflow_general_options General plugin options
*
* @return bool True if user should be excluded, false otherwise
*/
private function should_exclude_current_user($pixelflow_general_options)
{
return pixelflow_current_user_has_excluded_role(
is_array($pixelflow_general_options) ? $pixelflow_general_options : array()
);
}
/**
* Get the URL to the WooCommerce debug log file.
* Generates a random key once and persists it as an option.
*/
private function get_debug_log_url(): string
{
$key = get_option('pixelflow_debug_log_key', '');
if (empty($key)) {
$key = wp_generate_password(12, false);
update_option('pixelflow_debug_log_key', $key);
}
$path = pixelflow_get_debug_log_path();
if (empty($path)) {
return '';
}
return content_url('/pixelflow_debug_' . preg_replace('/[^a-zA-Z0-9]/', '', $key) . '.log');
}
/**
* AJAX handler to clear (delete) the WooCommerce debug log file.
* Accepts no user-supplied parameters — the file path is derived server-side only.
*/
public function ajax_clear_debug_log(): void
{
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
$path = pixelflow_get_debug_log_path();
if (empty($path)) {
wp_send_json_error(array('message' => __('Log file path could not be resolved.', 'pixelflow')), 400);
return;
}
if ( ! file_exists($path)) {
wp_send_json_success(array('message' => __('Log file does not exist.', 'pixelflow')));
return;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
if (unlink($path)) {
wp_send_json_success(array('message' => __('Log file cleared.', 'pixelflow')));
} else {
wp_send_json_error(array('message' => __('Could not delete log file.', 'pixelflow')), 500);
}
}
/**
* AJAX handler to read and return the WooCommerce debug log file contents.
*/
public function ajax_get_debug_log(): void
{
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
$path = pixelflow_get_debug_log_path();
if (empty($path)) {
wp_send_json_error(array('message' => __('Log file path could not be resolved.', 'pixelflow')), 400);
return;
}
if ( ! file_exists($path)) {
wp_send_json_success(array('content' => '', 'message' => __('Log file does not exist yet.', 'pixelflow')));
return;
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$content = file_get_contents($path, false, null, 0, PIXELFLOW_DEBUG_LOG_MAX_SIZE);
if ($content === false) {
wp_send_json_error(array('message' => __('Could not read log file.', 'pixelflow')), 500);
return;
}
wp_send_json_success(array('content' => $content));
}
/**
* Disable Woo debug logging via a one-click admin URL action.
*/
public function handle_disable_debug_action(): void
{
if ( ! isset($_GET['pixelflow_disable_debug'])) {
return;
}
check_admin_referer('pixelflow_disable_debug');
if ( ! current_user_can('manage_options')) {
return;
}
$options = get_option('pixelflow_general_options', array());
$options['woo_debug_enabled'] = 0;
$options['forms_debug_enabled'] = 0;
update_option('pixelflow_general_options', $options);
wp_safe_redirect(remove_query_arg(array('pixelflow_disable_debug', '_wpnonce')));
exit;
}
/**
* Show an admin notice when Woo debug logging is enabled.
*/
public function display_debug_notice(): void
{
if ( ! current_user_can('manage_options')) {
return;
}
$options = get_option('pixelflow_general_options', array());
$woo_debug = ! empty($options['woo_debug_enabled']) && PixelFlow_WooCommerce_Integration::is_woocommerce_active();
$form_debug = ! empty($options['forms_debug_enabled']);
if ( ! $woo_debug && ! $form_debug) {
return;
}
$what = $woo_debug && $form_debug ? 'Woo and form events' : ($woo_debug ? 'Woo events' : 'Form events');
$log_path = pixelflow_get_debug_log_path();
$file_size = ( ! empty($log_path) && file_exists($log_path))
? size_format(filesize($log_path))
: '0 B';
$disable_url = wp_nonce_url(
add_query_arg('pixelflow_disable_debug', '1'),
'pixelflow_disable_debug'
);
$settings_url = admin_url('options-general.php?page=pixelflow-settings');
printf(
'<div class="notice notice-warning"><p>'
. '<strong>PixelFlow:</strong> '
. '%s debug logging is <strong>enabled</strong>. '
. 'Events are being saved to a log file (current size: <strong>%s</strong>). '
. 'This may slow down your site — disable it when not in use. '
. '<a href="%s">Disable debug logging</a> | '
. '<a href="%s">Go to settings</a>'
. '</p></div>',
esc_html($what),
esc_html($file_size),
esc_url($disable_url),
esc_url($settings_url)
);
}
/**
* Tells an unconfigured site that no events are being sent.
*
* The credential gate would otherwise turn a half-configured site into a total, unexplained
* loss of events: silence the owner cannot see is indistinguishable from a broken plugin.
*
* Conditioned on the credentials alone — not on the enable toggles and not on WooCommerce
* being active. An empty credential is a misconfiguration rather than a choice, and the same
* two values gate the browser script, so the notice covers both.
*
* @return void
*/
public function display_unconfigured_notice(): void
{
// Off by default until the notice's wording and placement are reworked; a site can opt in
// with add_filter('pixelflow_show_unconfigured_notice', '__return_true').
if ( ! apply_filters('pixelflow_show_unconfigured_notice', false)) {
return;
}
if ( ! current_user_can('manage_options')) {
return;
}
$params = get_option('pixelflow_script_params', array());
$site_external_id = isset($params['siteExternalId']) ? $params['siteExternalId'] : '';
$api_key = isset($params['apiKey']) ? $params['apiKey'] : '';
if ( ! empty($site_external_id) && ! empty($api_key)) {
return;
}
printf(
'<div class="notice notice-error"><p>'
. '<strong>PixelFlow:</strong> '
. 'the plugin is not fully configured, so <strong>no events are being sent</strong>. '
. 'Add the site identifier and the API key to start tracking. '
. '<a href="%s">Go to settings</a>'
. '</p></div>',
esc_url(admin_url('options-general.php?page=pixelflow-settings'))
);
}
/**
* Add plugin action links
*/
public function add_plugin_action_links($links)
{
$settings_link = '<a href="' . admin_url('options-general.php?page=pixelflow-settings') . '">' . __(
'Settings',
'pixelflow'
) . '</a>';
array_unshift($links, $settings_link);
return $links;
}
/**
* Settings page callback
*/
public function settings_page()
{
?>
<div class="wrap pixelflow-admin-wrap">
<h1><?php
echo esc_html(get_admin_page_title()); ?></h1>
<p>Configure your PixelFlow integration and WooCommerce tracking settings</p>
<div style="display: none" id="pixelflow-settings">
<?php
$pixelflowSiteId = apply_filters('pixelflow_site_id', "wp_" . md5(home_url()));
global $wp_roles;
if ( ! isset($wp_roles)) {
$wp_roles = wp_roles();
}
$roles = [];
foreach ($wp_roles->roles as $role_key => $role) {
$roles[] = $role_key . "|" . $role["name"];
}
$pixelflowUserRoles = apply_filters('pixelflow_user_roles', implode(",", $roles));
?>
<input id="pixelflow-site-id" value="<?php
echo esc_html($pixelflowSiteId); ?>" type="hidden"/>
<input id="pixelflow-user-roles" value="<?php
echo esc_html($pixelflowUserRoles); ?>" type="hidden"/>
<input id="pixelflow-configured" value="<?php
$pixelflow_general_options = get_option('pixelflow_general_options', array());
if(!empty($pixelflow_general_options)) {
echo "1";
} else {
echo "0";
}
?>" type="hidden"/>
</div>
<div id="pixelflowroot" class="pixelflow-app"></div>
</div>
<?php
}
/**
* AJAX handler to get settings
*/
public function ajax_get_settings()
{
// Verify nonce
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
// Check user capability
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
$pixelflow_general_options = get_option('pixelflow_general_options', array());
$debug_options = get_option('pixelflow_debug_options', array());
$script_params = get_option('pixelflow_script_params', '');
wp_send_json_success(array(
'general_options' => $pixelflow_general_options,
'debug_options' => $debug_options,
'script_params' => $script_params,
'is_woocommerce_active' => PixelFlow_WooCommerce_Integration::is_woocommerce_active(),
));
}
/**
* AJAX handler to save settings
*/
public function ajax_save_settings()
{
// Verify nonce
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
// Check user capability
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
// Get the posted data
if (isset($_POST['general_options']) && is_array($_POST['general_options'])) {
$pixelflow_general_options = array_map('sanitize_text_field', wp_unslash($_POST['general_options']));
} else {
$pixelflow_general_options = array();
}
if (isset($_POST['debug_options']) && is_array($_POST['debug_options'])) {
$debug_options = array_map('sanitize_text_field', wp_unslash($_POST['debug_options']));
} else {
$debug_options = array();
}
// Sanitize and save options
$sanitized_general_options = $this->sanitize_general_options($pixelflow_general_options);
$sanitized_debug_options = $this->sanitize_debug_options($debug_options);
update_option('pixelflow_general_options', $sanitized_general_options);
update_option('pixelflow_debug_options', $sanitized_debug_options);
wp_send_json_success(array(
'message' => __('Settings saved successfully', 'pixelflow'),
'general_options' => $sanitized_general_options,
'debug_options' => $sanitized_debug_options,
));
}
/**
* AJAX handler to save script code and parameters
*/
public function ajax_save_script_params()
{
// Verify nonce
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
// Check user capability
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
// Get the params (base64 encoded JSON)
$params_encoded = '';
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$raw_params = isset($_POST['params']) ? wp_unslash($_POST['params']) : '';
if ($raw_params && preg_match('/^[A-Za-z0-9\/+=]+$/', $raw_params) === 1) {
$params_encoded = $raw_params;
}
// Decode base64 params
$params_json = base64_decode($params_encoded, true);
if ($params_json === false) {
wp_send_json_error(array('message' => __('Invalid base64 params payload', 'pixelflow')), 400);
return;
}
// Decode JSON
$params = json_decode($params_json, true);
if ($params === null || json_last_error() !== JSON_ERROR_NONE) {
wp_send_json_error(array('message' => __('Invalid JSON payload', 'pixelflow')), 400);
return;
}
// Validate required parameters
$required_keys = array('siteExternalId', 'apiKey', 'apiEndpoint', 'cdnUrl');
foreach ($required_keys as $key) {
if ( ! isset($params[$key])) {
// translators: %s is the name of the missing required parameter.
wp_send_json_error(array('message' => sprintf(__('Missing required parameter: %s', 'pixelflow'), $key)),
400);
}
}
// Sanitize and validate parameters
$sanitized_params = array(
'siteExternalId' => sanitize_text_field($params['siteExternalId']),
'apiKey' => sanitize_text_field($params['apiKey']),
'apiEndpoint' => esc_url_raw($params['apiEndpoint']),
'cdnUrl' => esc_url_raw($params['cdnUrl']),
);
// Save parameters to database option
update_option('pixelflow_script_params', $sanitized_params);
wp_send_json_success(array(
'message' => __('Script parameters saved successfully', 'pixelflow'),
));
}
/**
* AJAX handler to remove script code and parameters
*/
public function ajax_remove_script_params()
{
// Verify nonce
check_ajax_referer('pixelflow_settings_nonce', 'nonce');
// Check user capability
if ( ! current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Unauthorized access', 'pixelflow')), 403);
return;
}
// Clear script parameters from options
update_option('pixelflow_script_params', array());
wp_send_json_success(array(
'message' => __('Script code and parameters removed successfully', 'pixelflow'),
));
}
/**
* Sanitize tracking URLs array
*
* @param array $tracking_urls Raw tracking URLs data
*
* @return array Sanitized tracking URLs
*/
private function sanitize_tracking_urls(array $tracking_urls): array
{
$sanitized = array();
foreach ($tracking_urls as $url_data) {
if ( ! is_array($url_data)) {
continue;
}
$sanitized[] = array(
'url' => esc_url_raw($url_data['url'] ?? ''),
'event' => sanitize_text_field($url_data['event'] ?? ''),
);
}
return $sanitized;
}
/**
* Sanitize debug options
*
* @param array $input Raw input array
* @return array Sanitized debug options
*/
private function sanitize_debug_options(array $input): array
{
$sanitized = array();
$boolean_keys = array('woo_debug_enabled');
foreach ($boolean_keys as $key) {
$sanitized[$key] = isset($input[$key]) ? 1 : 0;
}
return $sanitized;
}
}
// Initialize the plugin
PixelFlow::get_instance();