Repository navigation
Expand file tree
/
Copy pathshift8-treb.php
More file actions
1200 lines (1032 loc) · 41.1 KB
/
Copy pathshift8-treb.php
File metadata and controls
1200 lines (1032 loc) · 41.1 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
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: Shift8 Real Estate Listings for TREB
* Plugin URI: https://github.com/stardothosting/shift8-treb
* Description: Integrates Toronto Real Estate Board (TREB) listings via AMPRE API, automatically importing property listings into WordPress. Replaces the Python script with native WordPress functionality.
* Version: 1.8.2
* Author: Shift8 Web
* Author URI: https://shift8web.ca
* Text Domain: shift8-real-estate-listings-for-treb
* Domain Path: /languages
* Requires at least: 5.0
* Tested up to: 7.0
* Requires PHP: 7.4
* License: GPLv3 or later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Plugin constants
define('SHIFT8_TREB_VERSION', '1.8.2');
define('SHIFT8_TREB_PLUGIN_FILE', __FILE__);
define('SHIFT8_TREB_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SHIFT8_TREB_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SHIFT8_TREB_PLUGIN_BASENAME', plugin_basename(__FILE__));
/**
* Sanitize sensitive data for logging
*
* Recursively sanitizes array data to prevent sensitive information
* like API tokens and passwords from appearing in logs.
*
* @since 1.0.0
* @param mixed $data The data to sanitize
* @return mixed Sanitized data with sensitive fields redacted
*/
function shift8_treb_sanitize_log_data($data) {
if (is_array($data)) {
$sanitized = array();
foreach ($data as $key => $value) {
$key_lower = strtolower($key);
if (in_array($key_lower, array('token', 'api_token', 'password', 'pass', 'pwd', 'authorization'), true)) {
$sanitized[$key] = '***REDACTED***';
} elseif (in_array($key_lower, array('username', 'user', 'login'), true)) {
$sanitized[$key] = strlen($value) > 2 ? substr($value, 0, 2) . '***' : '***';
} elseif (is_array($value)) {
$sanitized[$key] = shift8_treb_sanitize_log_data($value);
} else {
$sanitized[$key] = $value;
}
}
return $sanitized;
}
return $data;
}
/**
* Global debug logging function
*
* Checks if debug logging is enabled before logging. Automatically
* sanitizes sensitive data to prevent credential exposure.
*
* @since 1.0.0
* @param string $message The log message
* @param mixed $data Optional data to include in the log
*/
// Removed duplicate function - using the new logging system below
/**
* Encrypt sensitive data for storage
*
* @since 1.0.0
* @param string $data The data to encrypt
* @return string The encrypted data
*/
function shift8_treb_encrypt_data($data) {
if (empty($data)) {
return '';
}
// Use WordPress salts for encryption key
$key = wp_salt('auth');
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
return base64_encode($iv . $encrypted);
}
/**
* Decrypt sensitive data from storage
*
* @since 1.0.0
* @param string $encrypted_data The encrypted data
* @return string The decrypted data
*/
function shift8_treb_decrypt_data($encrypted_data) {
if (empty($encrypted_data)) {
return '';
}
// Check if this looks like a JWT token (not encrypted)
if (strpos($encrypted_data, 'eyJ') === 0) {
// This is a plain JWT token, return as-is
return $encrypted_data;
}
// This should be encrypted data, try to decrypt it
$key = wp_salt('auth');
$data = base64_decode($encrypted_data);
// Check if base64 decode was successful and we have enough data
if ($data === false || strlen($data) < 16) {
return '';
}
$iv = substr($data, 0, 16);
$encrypted = substr($data, 16);
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
// Return decrypted data, or empty string if decryption failed
return $decrypted !== false ? $decrypted : '';
}
// Check for minimum PHP version
if (version_compare(PHP_VERSION, '7.4', '<')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>';
echo esc_html__('Shift8 TREB Real Estate Listings requires PHP 7.4 or higher. Please upgrade PHP.', 'shift8-real-estate-listings-for-treb');
echo '</p></div>';
});
return;
}
/**
* Main plugin class
*
* Handles plugin initialization, AMPRE API integration,
* and WordPress post management for TREB listings.
*
* @since 1.0.0
*/
class Shift8_TREB {
/**
* Plugin instance
*
* @since 1.0.0
* @var Shift8_TREB|null
*/
private static $instance = null;
/**
* Get plugin instance (Singleton pattern)
*
* @since 1.0.0
* @return Shift8_TREB
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*
* Sets up plugin hooks and initialization.
*
* @since 1.0.0
*/
private function __construct() {
add_action('plugins_loaded', array($this, 'init'));
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// Note: No custom post types - we create regular posts like the Python script
// Add custom cron schedules
add_filter('cron_schedules', array($this, 'add_custom_cron_schedules'));
// Cron hooks for TREB data synchronization
add_action('shift8_treb_sync_listings', array($this, 'sync_listings_cron'));
// Cron hook for cleanup of terminated listings
add_action('shift8_treb_cleanup_terminated', array($this, 'cleanup_terminated_listings_cron'));
// Admin hooks - register settings on admin_init regardless of is_admin() check
add_action('admin_init', array($this, 'register_settings'));
// Include WP-CLI commands if WP-CLI is available
if (defined('WP_CLI') && WP_CLI) {
require_once SHIFT8_TREB_PLUGIN_DIR . 'includes/class-shift8-treb-cli.php';
}
// Hook for Google Maps script enqueue
add_action('wp_enqueue_scripts', array($this, 'enqueue_google_maps_scripts'));
// Hook for WalkScore script enqueue
add_action('wp_enqueue_scripts', array($this, 'enqueue_walkscore_scripts'));
// Hook for frontend styles
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_styles'));
}
/**
* Initialize plugin
*
* Loads textdomain and sets up integrations.
*
* @since 1.0.0
*/
public function init() {
shift8_treb_log('Plugin init() called');
// WordPress automatically loads translations for plugins hosted on WordPress.org since WP 4.6
// load_plugin_textdomain() is no longer needed
// Initialize admin functionality
if (is_admin()) {
$this->init_admin();
}
// Manage cron scheduling based on plugin state
$this->manage_cron_scheduling();
}
/**
* Initialize admin functionality
*
* @since 1.0.0
*/
public function init_admin() {
require_once SHIFT8_TREB_PLUGIN_DIR . 'admin/class-shift8-treb-admin.php';
new Shift8_TREB_Admin();
}
/**
* Register plugin settings
*
* @since 1.0.0
*/
public function register_settings() {
register_setting(
'shift8_treb_settings',
'shift8_treb_settings',
array(
'sanitize_callback' => array($this, 'sanitize_settings'),
'default' => array(
'bearer_token' => '',
'sync_frequency' => 'daily',
'max_listings_per_query' => 100,
'debug_enabled' => '0',
'google_maps_api_key' => '',
'walkscore_id' => '',
'member_id' => '',
'excluded_member_ids' => '',
'listing_age_days' => '30',
'listing_template' => 'Property Details:\n\nAddress: %ADDRESS%\nPrice: %PRICE%\nMLS: %MLS%\nBedrooms: %BEDROOMS%\nBathrooms: %BATHROOMS%\nSquare Feet: %SQFT%\n\nDescription:\n%DESCRIPTION%',
'post_excerpt_template' => '%ADDRESS%\n%LISTPRICE%\nMLS : %MLSNUMBER%',
'geographic_filter_type' => '',
'postal_code_prefixes' => '',
'city_filter' => ''
)
)
);
}
/**
* Sanitize settings
*
* @since 1.0.0
* @param array $input Raw input data
* @return array Sanitized settings
*/
public function sanitize_settings($input) {
$sanitized = array();
// Sanitize Bearer Token
if (isset($input['bearer_token'])) {
$token = trim($input['bearer_token']);
if (!empty($token)) {
$sanitized['bearer_token'] = shift8_treb_encrypt_data($token);
} else {
// Keep existing token if new one is empty
$existing_settings = get_option('shift8_treb_settings', array());
$sanitized['bearer_token'] = isset($existing_settings['bearer_token']) ? $existing_settings['bearer_token'] : '';
}
}
// Sanitize sync frequency with extended options
$allowed_frequencies = array('hourly', 'shift8_treb_8hours', 'shift8_treb_12hours', 'daily', 'weekly', 'shift8_treb_biweekly', 'shift8_treb_monthly');
if (isset($input['sync_frequency']) && in_array($input['sync_frequency'], $allowed_frequencies, true)) {
$new_frequency = $input['sync_frequency'];
$old_frequency = get_option('shift8_treb_settings')['sync_frequency'] ?? 'daily';
// If frequency changed, reschedule cron
if ($new_frequency !== $old_frequency) {
wp_clear_scheduled_hook('shift8_treb_sync_listings');
// Schedule will be recreated in init() method
}
$sanitized['sync_frequency'] = $new_frequency;
} else {
$sanitized['sync_frequency'] = 'daily';
}
// Sanitize max listings per query
if (isset($input['max_listings_per_query'])) {
$max_listings = absint($input['max_listings_per_query']);
$sanitized['max_listings_per_query'] = max(1, min(1000, $max_listings)); // Between 1 and 1000
}
// Sanitize debug setting
$sanitized['debug_enabled'] = isset($input['debug_enabled']) ? '1' : '0';
// Sanitize Google Maps API key
if (isset($input['google_maps_api_key'])) {
$sanitized['google_maps_api_key'] = sanitize_text_field($input['google_maps_api_key']);
}
// Sanitize WalkScore ID (no API key needed)
if (isset($input['walkscore_id'])) {
$sanitized['walkscore_id'] = sanitize_text_field($input['walkscore_id']);
}
// Sanitize member ID (supports comma-separated values)
if (isset($input['member_id'])) {
$member_ids = sanitize_text_field($input['member_id']);
// Clean up comma-separated values: remove extra spaces, empty values
$member_list = array_filter(array_map('trim', explode(',', $member_ids)));
$sanitized['member_id'] = implode(',', $member_list);
}
// Sanitize excluded member IDs (supports comma-separated values)
if (isset($input['excluded_member_ids'])) {
$excluded_ids = sanitize_text_field($input['excluded_member_ids']);
// Clean up comma-separated values: remove extra spaces, empty values
$excluded_list = array_filter(array_map('trim', explode(',', $excluded_ids)));
$sanitized['excluded_member_ids'] = implode(',', $excluded_list);
}
// Sanitize listing age days
if (isset($input['listing_age_days'])) {
$listing_age = absint($input['listing_age_days']);
$sanitized['listing_age_days'] = max(1, min(365, $listing_age)); // Between 1 and 365 days
}
if (isset($input['listing_template'])) {
$sanitized['listing_template'] = wp_kses_post($input['listing_template']);
}
if (isset($input['post_excerpt_template'])) {
$sanitized['post_excerpt_template'] = wp_kses_post($input['post_excerpt_template']);
}
// Sanitize geographic filter settings
$allowed_geo_types = array('', 'postal_prefix', 'city');
if (isset($input['geographic_filter_type']) && in_array($input['geographic_filter_type'], $allowed_geo_types, true)) {
$sanitized['geographic_filter_type'] = $input['geographic_filter_type'];
} else {
$sanitized['geographic_filter_type'] = '';
}
if (isset($input['postal_code_prefixes'])) {
$raw_prefixes = sanitize_text_field(trim($input['postal_code_prefixes']));
if (!empty($raw_prefixes)) {
$prefixes = array_map('trim', explode(',', $raw_prefixes));
$valid_prefixes = array();
foreach ($prefixes as $prefix) {
$prefix = strtoupper($prefix);
if (preg_match('/^[A-Z][0-9][A-Z]$/', $prefix)) {
$valid_prefixes[] = $prefix;
}
}
$sanitized['postal_code_prefixes'] = implode(',', $valid_prefixes);
} else {
$sanitized['postal_code_prefixes'] = '';
}
}
if (isset($input['city_filter'])) {
$raw_cities = sanitize_text_field(trim($input['city_filter']));
if (!empty($raw_cities)) {
$cities = array_filter(array_map('trim', explode(',', $raw_cities)));
$cached_cities = get_transient('shift8_treb_city_lookups');
if (is_array($cached_cities) && !empty($cached_cities)) {
$lowered_cache = array_map('strtolower', $cached_cities);
$valid_cities = array();
$invalid_cities = array();
foreach ($cities as $city) {
$idx = array_search(strtolower($city), $lowered_cache, true);
if ($idx !== false) {
$valid_cities[] = $cached_cities[$idx];
} else {
$invalid_cities[] = $city;
}
}
if (!empty($invalid_cities)) {
add_settings_error(
'shift8_treb_settings',
'invalid_cities',
sprintf(
esc_html__('Unrecognised city name(s) removed: %s. Use the autocomplete suggestions.', 'shift8-real-estate-listings-for-treb'),
esc_html(implode(', ', $invalid_cities))
),
'warning'
);
}
$sanitized['city_filter'] = implode(', ', $valid_cities);
} else {
$sanitized['city_filter'] = implode(', ', $cities);
}
} else {
$sanitized['city_filter'] = '';
}
}
// Add success message
add_settings_error(
'shift8_treb_settings',
'settings_updated',
esc_html__('Settings saved successfully.', 'shift8-real-estate-listings-for-treb'),
'updated'
);
return $sanitized;
}
/**
* Add custom cron schedules
*
* @since 1.0.0
* @param array $schedules Existing cron schedules
* @return array Modified cron schedules
*/
public function add_custom_cron_schedules($schedules) {
// Only register the schedule that's currently being used
$settings = get_option('shift8_treb_settings', array());
$sync_frequency = isset($settings['sync_frequency']) ? $settings['sync_frequency'] : 'daily';
// Define all available custom schedules
$custom_schedules = array(
'shift8_treb_8hours' => array(
'interval' => 8 * HOUR_IN_SECONDS,
'display' => esc_html__('Every 8 Hours', 'shift8-real-estate-listings-for-treb')
),
'shift8_treb_12hours' => array(
'interval' => 12 * HOUR_IN_SECONDS,
'display' => esc_html__('Every 12 Hours', 'shift8-real-estate-listings-for-treb')
),
'shift8_treb_biweekly' => array(
'interval' => 2 * 7 * DAY_IN_SECONDS,
'display' => esc_html__('Bi-Weekly (Every 2 Weeks)', 'shift8-real-estate-listings-for-treb')
),
'shift8_treb_monthly' => array(
'interval' => 30 * DAY_IN_SECONDS,
'display' => esc_html__('Monthly', 'shift8-real-estate-listings-for-treb')
)
);
// Only register the schedule that's currently being used
if (isset($custom_schedules[$sync_frequency])) {
$schedules[$sync_frequency] = $custom_schedules[$sync_frequency];
shift8_treb_log('Registered cron schedule', array(
'schedule' => $sync_frequency,
'interval' => $custom_schedules[$sync_frequency]['interval']
));
}
return $schedules;
}
/**
* Schedule TREB data synchronization
*
* Replaces the Python cron job: 15 10 * * * (daily at 10:15 AM)
*
* @since 1.0.0
*/
public function schedule_sync() {
$settings = get_option('shift8_treb_settings', array());
$sync_frequency = isset($settings['sync_frequency']) ? $settings['sync_frequency'] : 'daily';
// Schedule the sync event
wp_schedule_event(time(), $sync_frequency, 'shift8_treb_sync_listings');
shift8_treb_log('TREB sync scheduled', array(
'frequency' => $sync_frequency,
'next_run' => wp_next_scheduled('shift8_treb_sync_listings')
));
return true;
}
/**
* Schedule terminated listings cleanup
*
* Separate job that runs weekly to query API for terminated listings
* and remove matching WordPress posts
*
* @since 1.6.7
*/
public function schedule_cleanup() {
// Schedule cleanup to run weekly
// Queries API for terminated/cancelled listings (up to 200)
// Then checks if those MLS numbers exist in WordPress and removes them
if (!wp_next_scheduled('shift8_treb_cleanup_terminated')) {
wp_schedule_event(time(), 'weekly', 'shift8_treb_cleanup_terminated');
shift8_treb_log('TREB cleanup scheduled', array(
'frequency' => 'weekly',
'next_run' => wp_next_scheduled('shift8_treb_cleanup_terminated')
));
}
return true;
}
/**
* Manage cron scheduling based on plugin state
*
* Following shift8-zoom pattern for proper cron management
*
* @since 1.0.0
*/
public function manage_cron_scheduling() {
$settings = get_option('shift8_treb_settings', array());
$bearer_token = isset($settings['bearer_token']) ? $settings['bearer_token'] : '';
$sync_frequency = isset($settings['sync_frequency']) ? $settings['sync_frequency'] : 'daily';
// Check if sync is enabled (has required settings)
$sync_enabled = !empty($bearer_token);
if ($sync_enabled) {
$next_scheduled = wp_next_scheduled('shift8_treb_sync_listings');
if (!$next_scheduled) {
// No cron scheduled, create one
$this->schedule_sync();
shift8_treb_log('TREB cron scheduled', array(
'frequency' => $sync_frequency,
'next_run' => wp_next_scheduled('shift8_treb_sync_listings')
));
} else {
// Check if frequency matches current setting
$current_cron = wp_get_scheduled_event('shift8_treb_sync_listings');
if ($current_cron && $current_cron->schedule !== $sync_frequency) {
// Frequency changed, reschedule
wp_clear_scheduled_hook('shift8_treb_sync_listings');
$this->schedule_sync();
shift8_treb_log('TREB cron rescheduled', array(
'old_frequency' => $current_cron->schedule,
'new_frequency' => $sync_frequency,
'next_run' => wp_next_scheduled('shift8_treb_sync_listings')
));
}
}
} else {
// Sync disabled, clear any existing cron
if (wp_next_scheduled('shift8_treb_sync_listings')) {
wp_clear_scheduled_hook('shift8_treb_sync_listings');
shift8_treb_log('TREB cron cleared - sync disabled (no bearer token)');
}
}
}
/**
* Cron job handler for syncing TREB listings
*
* This replaces the Python script functionality
*
* @since 1.0.0
*/
public function sync_listings_cron($skip_lock = false) {
// Check if sync is already running (prevent simultaneous syncs)
if (!$skip_lock) {
$sync_lock = get_transient('shift8_treb_sync_lock');
if ($sync_lock) {
shift8_treb_log('Sync already running, skipping cron execution', array(
'lock_time' => $sync_lock,
'current_time' => time()
));
return;
}
}
try {
// Set sync lock (expires in 10 minutes as safety)
set_transient('shift8_treb_sync_lock', time(), 600);
shift8_treb_log('=== TREB CRON SYNC STARTED ===');
// Include and initialize sync service
require_once SHIFT8_TREB_PLUGIN_DIR . 'includes/class-shift8-treb-sync-service.php';
$sync_service = new Shift8_TREB_Sync_Service();
// Execute sync (cron uses incremental sync by default)
$results = $sync_service->execute_sync(array(
'dry_run' => false,
'verbose' => false
));
if (!$results['success']) {
throw new Exception(esc_html($results['message']));
}
shift8_treb_log('=== TREB CRON SYNC COMPLETED ===', array(
'total_listings' => $results['total_listings'],
'processed' => $results['processed'],
'created' => $results['created'],
'updated' => $results['updated'],
'skipped' => $results['skipped'],
'errors' => $results['errors']
));
} catch (Exception $e) {
shift8_treb_log('TREB cron sync failed', array(
'error' => esc_html($e->getMessage())
), 'error');
} finally {
// Always clear the sync lock
delete_transient('shift8_treb_sync_lock');
}
}
/**
* Cron job handler for terminated listings cleanup
*
* Runs weekly to query API for terminated/cancelled listings
* and remove any matching WordPress posts
*
* @since 1.6.7
*/
public function cleanup_terminated_listings_cron() {
shift8_treb_log('=== WEEKLY CLEANUP JOB STARTED ===', array(), 'info');
try {
// Include and initialize sync service
require_once SHIFT8_TREB_PLUGIN_DIR . 'includes/class-shift8-treb-sync-service.php';
$sync_service = new Shift8_TREB_Sync_Service();
// Execute cleanup using the sync service method
$results = $sync_service->cleanup_terminated_listings();
shift8_treb_log('=== WEEKLY CLEANUP JOB COMPLETED ===', array(
'api_terminated_count' => $results['api_terminated_count'],
'checked' => $results['checked'],
'removed' => $results['removed'],
'errors' => $results['errors']
), 'info');
} catch (Exception $e) {
shift8_treb_log('Weekly cleanup job failed', array(
'error' => esc_html($e->getMessage())
), 'error');
}
}
/**
* Plugin activation
*
* Sets up default options and performs initial setup.
*
* @since 1.0.0
*/
public function activate() {
// Set default options if they don't exist
if (!get_option('shift8_treb_settings')) {
add_option('shift8_treb_settings', array(
'ampre_api_token' => '',
'sync_frequency' => 'daily',
'debug_enabled' => '0',
'google_maps_api_key' => '',
'listing_status_filter' => 'Active',
'city_filter' => '',
'max_listings_per_sync' => 100,
'geographic_filter_type' => '',
'postal_code_prefixes' => ''
));
}
// Create uploads directory for logs if it doesn't exist
$upload_dir = wp_upload_dir();
if (!is_dir($upload_dir['basedir'])) {
wp_mkdir_p($upload_dir['basedir']);
}
// No custom post types needed - we use regular WordPress posts like the Python script
// Flush rewrite rules
flush_rewrite_rules();
// Schedule the sync cron job
$this->schedule_sync();
// Schedule the cleanup cron job (separate from sync)
$this->schedule_cleanup();
shift8_treb_log('Plugin activated');
}
/**
* Plugin deactivation
*
* Cleans up scheduled events and temporary data.
*
* @since 1.0.0
*/
public function deactivate() {
// Clear scheduled events
wp_clear_scheduled_hook('shift8_treb_sync_listings');
wp_clear_scheduled_hook('shift8_treb_cleanup_terminated');
// Flush rewrite rules
flush_rewrite_rules();
shift8_treb_log('Plugin deactivated');
}
/**
* Enqueue Google Maps scripts for TREB listings
*
* @since 1.2.0
*/
public function enqueue_google_maps_scripts() {
// Only enqueue on single posts that are TREB listings
if (!is_single() || !shift8_treb_is_listing_post()) {
return;
}
// Only enqueue if we have Google Maps API key
if (!shift8_treb_has_google_maps_api_key()) {
return;
}
// Get current post data to check if it has coordinates
$post_id = get_the_ID();
$mls_number = get_post_meta($post_id, 'listing_mls_number', true);
if (empty($mls_number)) {
return;
}
// Get settings for API key
$settings = get_option('shift8_treb_settings', array());
$api_key = $settings['google_maps_api_key'];
// Get listing coordinates from post content or meta
$coordinates = $this->get_post_coordinates($post_id);
if (!$coordinates) {
return;
}
// Parse address for marker title
$post_title = get_the_title($post_id);
$address_parts = $this->parse_post_address($post_title);
// Enqueue Google Maps API
wp_enqueue_script(
'shift8-treb-google-maps-api',
'https://maps.googleapis.com/maps/api/js?key=' . esc_attr($api_key) . '&callback=shift8_treb_init_map',
array(),
SHIFT8_TREB_VERSION,
true
);
// Add inline script with map initialization
$map_script = sprintf("
function shift8_treb_init_map() {
var mapElement = document.getElementById('shift8-treb-map');
if (!mapElement) {
return; // Map element not found on this page
}
var theLatLng = {lat: %s, lng: %s};
var map = new google.maps.Map(mapElement, {
center: theLatLng,
zoom: 15
});
var marker = new google.maps.Marker({
position: theLatLng,
map: map,
title: '%s'
});
}",
floatval($coordinates['lat']),
floatval($coordinates['lng']),
esc_js($address_parts['street_number'] . ' ' . $address_parts['street_name'])
);
wp_add_inline_script('shift8-treb-google-maps-api', $map_script, 'before');
}
/**
* Enqueue WalkScore scripts for TREB listings
*
* @since 1.6.2
*/
public function enqueue_walkscore_scripts() {
// Only enqueue on single posts that are TREB listings
if (!is_single() || !shift8_treb_is_listing_post()) {
return;
}
// Get settings
$settings = get_option('shift8_treb_settings', array());
// Only enqueue if we have WalkScore ID
if (empty($settings['walkscore_id'])) {
return;
}
// Get current post data
$post_id = get_the_ID();
$mls_number = get_post_meta($post_id, 'listing_mls_number', true);
if (empty($mls_number)) {
return;
}
// Check if post content contains WalkScore div
$post_content = get_post_field('post_content', $post_id);
if (strpos($post_content, 'ws-walkscore-tile') === false) {
return; // No WalkScore div in content
}
// Get listing address from stored meta data
$unparsed_address = get_post_meta($post_id, 'shift8_treb_unparsed_address', true);
$city = get_post_meta($post_id, 'shift8_treb_city', true);
$province = get_post_meta($post_id, 'shift8_treb_state_province', true);
$country = get_post_meta($post_id, 'shift8_treb_country', true);
// Build full address for WalkScore (fallback to post title if meta not available)
if (!empty($unparsed_address)) {
$full_address = $unparsed_address;
if (!empty($city) && strpos($full_address, $city) === false) {
$full_address .= ', ' . $city;
}
if (!empty($province) && strpos($full_address, $province) === false) {
$full_address .= ', ' . $province;
}
if (!empty($country) && strpos($full_address, $country) === false) {
$full_address .= ', ' . $country;
}
} else {
// Fallback to post title
$full_address = get_the_title($post_id) . ', Canada';
}
// Enqueue WalkScore external script
wp_enqueue_script(
'shift8-treb-walkscore-api',
'https://www.walkscore.com/tile/show-walkscore-tile.php',
array(),
null, // No version for external script
true
);
// Add inline script with WalkScore initialization
$walkscore_script = sprintf("
// WalkScore configuration
var ws_wsid = '%s';
var ws_address = '%s';
var ws_format = 'square';
var ws_width = '300';
var ws_height = '300';
// WalkScore CSS
var walkscoreCSS = '#ws-walkscore-tile{position:relative;text-align:left}#ws-walkscore-tile *{float:none;}';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = walkscoreCSS;
} else {
style.appendChild(document.createTextNode(walkscoreCSS));
}
document.getElementsByTagName('head')[0].appendChild(style);",
esc_js($settings['walkscore_id']),
esc_js($full_address)
);
wp_add_inline_script('shift8-treb-walkscore-api', $walkscore_script, 'before');
}
/**
* Enqueue frontend styles for listing display
*
* @since 1.6.3
*/
public function enqueue_frontend_styles() {
// Only enqueue on single posts that are TREB listings
if (!is_single() || !shift8_treb_is_listing_post()) {
return;
}
wp_enqueue_style(
'shift8-treb-frontend',
SHIFT8_TREB_PLUGIN_URL . 'public/css/frontend.css',
array(),
SHIFT8_TREB_VERSION
);
}
/**
* Get coordinates for a post
*
* @since 1.2.0
* @param int $post_id Post ID
* @return array|false Coordinates array or false
*/
private function get_post_coordinates($post_id) {
// First, check stored meta fields (from geocoding or AMPRE API)
$stored_lat = get_post_meta($post_id, 'shift8_treb_latitude', true);
$stored_lng = get_post_meta($post_id, 'shift8_treb_longitude', true);
if (!empty($stored_lat) && !empty($stored_lng)) {
return array(
'lat' => floatval($stored_lat),
'lng' => floatval($stored_lng)
);
}
// Second, try to extract coordinates from post content (legacy support)
$post_content = get_post_field('post_content', $post_id);
// Look for coordinate values in various formats
if (preg_match('/lat:\s*([0-9.-]+)/', $post_content, $lat_matches) &&
preg_match('/lng:\s*([0-9.-]+)/', $post_content, $lng_matches)) {
return array(
'lat' => floatval($lat_matches[1]),
'lng' => floatval($lng_matches[1])
);
}
// Look for numeric coordinate values (from %MAPLAT% and %MAPLNG% placeholders)
if (preg_match('/([0-9.-]+),\s*([0-9.-]+)/', $post_content, $coord_matches)) {
$potential_lat = floatval($coord_matches[1]);
$potential_lng = floatval($coord_matches[2]);
// Basic validation for Toronto area coordinates
if ($potential_lat > 40 && $potential_lat < 50 && $potential_lng < -70 && $potential_lng > -90) {
return array(
'lat' => $potential_lat,
'lng' => $potential_lng
);
}
}
// No valid coordinates found - return false to indicate geocoding needed
return false;
}
/**
* Parse address from post title
*
* @since 1.2.0
* @param string $title Post title (address)
* @return array Address components
*/
private function parse_post_address($title) {
$parts = array(
'street_number' => '',
'street_name' => ''
);
if (empty($title)) {
return $parts;
}
// Extract street number (first number in the title)
if (preg_match('/^(\d+)/', trim($title), $matches)) {
$parts['street_number'] = $matches[1];
$title = preg_replace('/^\d+\s*/', '', $title);
}
// Remaining is street name (clean up extra info)
$parts['street_name'] = trim(preg_replace('/,.*$/', '', $title));
return $parts;
}
}
/**
* Main logging function
*
* @since 1.0.0
* @param string $message Log message
* @param array $context Additional context data
* @param string $level Log level (info, warning, error)
*/
function shift8_treb_log($message, $context = array(), $level = 'info') {