TA Repeat Clicks

mail@pastecode.io avatar
unknown
php
2 years ago
1.6 kB
15
Indexable
add_action('ta_before_link_redirect', function($thirsty_link, $redirect_url) {
  global $wpdb;
	
  if(is_admin()) {
    return;
  }	

  $ip = '';
  $current_datetime = current_time('mysql', true);
  $link_click_db = $wpdb->prefix . 'wplb_ta_link_clicks';
  $link_click_meta_db = $wpdb->prefix . 'wplb_ta_link_clicks_meta';

  // Get the user's IP address.
  if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
  } elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = explode(',', sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR'])));
    $ip = trim( $ip[0] );
  } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
    $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
  }

  // Check to see when the link was last clicked by them.
  $query = "SELECT `date_clicked` FROM {$link_click_db} AS link_clicks
    JOIN {$link_click_meta_db} AS link_clicks_meta
    ON link_clicks_meta.click_id = link_clicks.id
    WHERE link_clicks_meta.meta_key = 'user_ip_address' AND link_clicks_meta.meta_value = %s
    ORDER BY `date_clicked` DESC LIMIT 1";

  $query = $wpdb->prepare($query, $ip);
  
  $link_last_clicked = $wpdb->get_var($query);

  if($link_last_clicked) {
    $last_clicked_dt = new DateTime($link_last_clicked);
    $current_dt = new DateTime($current_datetime);

    $diff = $current_dt->diff($last_clicked_dt);
    $seconds = $diff->s + ($diff->i * 60);

    // 1 minute hasn't passed yet, throw a 403 error.
    if($seconds < 60) {
      header('HTTP/1.0 403 Forbidden');
      exit;
    }
  }

}, 1, 2);