| 1 |
<?php |
| 2 |
|
| 3 |
if ( ! defined( 'ABSPATH' ) ) { |
| 4 |
exit; // Exit if accessed directly |
| 5 |
} |
| 6 |
|
| 7 |
class PH_Search_Analytics |
| 8 |
{ |
| 9 |
private $recorded = false; |
| 10 |
|
| 11 |
public function __construct() |
| 12 |
{ |
| 13 |
add_action( |
| 14 |
'template_redirect', |
| 15 |
array( $this, 'look_for_submitted_search' ) |
| 16 |
); |
| 17 |
|
| 18 |
add_action( |
| 19 |
'propertyhive_property_search_performed', |
| 20 |
array( $this, 'record_property_search' ) |
| 21 |
); |
| 22 |
|
| 23 |
add_action( |
| 24 |
'propertyhive_cleanup_search_analytics', |
| 25 |
array( $this, 'clear_old_searches' ) |
| 26 |
); |
| 27 |
} |
| 28 |
|
| 29 |
public function look_for_submitted_search() |
| 30 |
{ |
| 31 |
if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) |
| 32 |
{ |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
if ( |
| 37 |
!is_post_type_archive( 'property' ) && |
| 38 |
!is_page( ph_get_page_id( 'search_results' ) ) |
| 39 |
) |
| 40 |
{ |
| 41 |
return; |
| 42 |
} |
| 43 |
|
| 44 |
// Ignore page 2 onwards |
| 45 |
if ( is_paged() ) |
| 46 |
{ |
| 47 |
return; |
| 48 |
} |
| 49 |
|
| 50 |
do_action( 'propertyhive_property_search_performed' ); |
| 51 |
} |
| 52 |
|
| 53 |
public function record_property_search() |
| 54 |
{ |
| 55 |
global $wpdb; |
| 56 |
|
| 57 |
if ( $this->recorded ) |
| 58 |
{ |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
$this->recorded = true; |
| 63 |
|
| 64 |
$result = $wpdb->insert( |
| 65 |
$wpdb->prefix . 'ph_search_log', |
| 66 |
array( |
| 67 |
'searched_at' => current_time( 'mysql', true ), |
| 68 |
), |
| 69 |
array( |
| 70 |
'%s', |
| 71 |
) |
| 72 |
); |
| 73 |
|
| 74 |
if ( false === $result ) |
| 75 |
{ |
| 76 |
$this->recorded = false; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
public function clear_old_searches() |
| 81 |
{ |
| 82 |
global $wpdb; |
| 83 |
|
| 84 |
$table_name = $wpdb->prefix . 'ph_search_log'; |
| 85 |
$cutoff = gmdate( 'Y-m-d H:i:s', strtotime( '-90 days' ) ); |
| 86 |
|
| 87 |
do |
| 88 |
{ |
| 89 |
$deleted = $wpdb->query( |
| 90 |
$wpdb->prepare( |
| 91 |
"DELETE FROM {$table_name} |
| 92 |
WHERE searched_at < %s |
| 93 |
ORDER BY searched_at ASC |
| 94 |
LIMIT 500", |
| 95 |
$cutoff |
| 96 |
) |
| 97 |
); |
| 98 |
} |
| 99 |
while ( 500 === $deleted ); |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
new PH_Search_Analytics(); |