is_active() ) { return $check; } try { $this->record_event( $post_id, 'view' ); } catch ( \Throwable $e ) { TMDO_Logger::error( $this->module, 'update_post_metadata', $e->getMessage() ); } return $check; } /** * Records a view event when a HivePress listing is viewed. * * @param mixed $listing Listing object or ID. * @return void */ public function action_listing_viewed( $listing ): void { if ( ! $this->is_active() ) { return; } $listing_id = is_object( $listing ) && method_exists( $listing, 'get_id' ) ? $listing->get_id() : ( is_numeric( $listing ) ? (int) $listing : 0 ); if ( ! $listing_id ) { return; } try { $this->record_event( $listing_id, 'hp_action_view' ); } catch ( \Throwable $e ) { TMDO_Logger::error( $this->module, 'listing_viewed', $e->getMessage() ); } } /** * Deletes statistics records when a listing post is deleted. * * @param int $post_id Post ID. * @param \WP_Post $post Post object. * @return void */ public function action_delete_post( int $post_id, \WP_Post $post ): void { if ( 'hp_listing' !== $post->post_type || ! $this->is_active() ) { return; } try { global $wpdb; $wpdb->delete( TMDO_DB::table( 'hpct_statistics' ), array( 'listing_id' => $post_id ), array( '%d' ) ); } catch ( \Throwable $e ) { TMDO_Logger::error( $this->module, 'before_delete_post', $e->getMessage() ); } } /** * Records a statistics event to the hpct_statistics table. * * @param int $listing_id Listing post ID. * @param string $event_type Event type identifier. * @return void */ private function record_event( int $listing_id, string $event_type ): void { global $wpdb; $user_id = get_current_user_id(); $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) ); $ip_hash = $ip ? hash( 'sha256', $ip ) : ''; $wpdb->insert( TMDO_DB::table( 'hpct_statistics' ), array( 'listing_id' => $listing_id, 'event_type' => $event_type, 'user_id' => $user_id, 'ip_hash' => $ip_hash, 'referrer' => substr( esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ?? '' ) ), 0, 500 ), 'created_at' => TMDO_DB::now(), ), array( '%d', '%s', '%d', '%s', '%s', '%s' ) ); } }