You are here

public static function CleantalkFuncs::_cleantalk_check_spam in Anti Spam by CleanTalk 8.3

Same name and namespace in other branches
  1. 8.4 src/CleantalkFuncs.php \Drupal\cleantalk\CleantalkFuncs::_cleantalk_check_spam()
  2. 9.1.x src/CleantalkFuncs.php \Drupal\cleantalk\CleantalkFuncs::_cleantalk_check_spam()

Cleantalk inner function - performs antispam checking.

7 calls to CleantalkFuncs::_cleantalk_check_spam()
BootSubscriber::handle in src/EventSubscriber/BootSubscriber.php
Handles a Request to convert it to a Response.
cleantalk_uc_order in ./cleantalk.module
cleantalk_validate_comment in ./cleantalk.module
Cleantalk inner function - comment validation function.
cleantalk_validate_contact_message in ./cleantalk.module
Cleantalk inner function - contact message validation function.
cleantalk_validate_forum_topic in ./cleantalk.module
Cleantalk inner function - forum topic validation function.

... See full list

File

src/CleantalkFuncs.php, line 190

Class

CleantalkFuncs
Cleantalk class create request

Namespace

Drupal\cleantalk

Code

public static function _cleantalk_check_spam($spam_check, $form_errors = null) {
  global $cleantalk_executed;
  $curr_user = \Drupal::currentUser();

  // Exclusion. Administrator.
  if ($curr_user
    ->hasPermission('access administration menu') || $cleantalk_executed) {
    return NULL;
  }

  // Exclusion. By roles.
  $roles = \Drupal::config('cleantalk.settings')
    ->get('cleantalk_roles_exclusions');
  if (!empty($roles)) {
    foreach ($roles as $role_id) {
      if (self::_cleantalk_user_has_role_id($role_id, $curr_user)) {
        return NULL;
      }
    }
  }

  // Exclusion. By number of posted comments
  if ($curr_user
    ->id()) {
    $user = \Drupal\user\Entity\User::load($curr_user
      ->id());
    $uid = $user
      ->get('uid')->value;

    // Don't check reged user with >= 'cleantalk_check_comments_min_approved' approved msgs.
    if (is_object($user) && $user
      ->get('uid')->value > 0 && \Drupal::service('module_handler')
      ->moduleExists('comment')) {
      $result = \Drupal::database()
        ->query('SELECT count(*) AS count FROM {comment_field_data} WHERE uid=:uid AND status=1', [
        ':uid' => $uid,
      ])
        ->fetchObject()->count;
      $count = intval($result);
      $ct_comments = \Drupal::config('cleantalk.settings')
        ->get('cleantalk_check_comments_min_approved');
      if ($count >= $ct_comments) {
        return NULL;
      }
    }
  }

  // Exclusion. By URLs
  $url_exclusion = explode(",", \Drupal::config('cleantalk.settings')
    ->get('cleantalk_url_exclusions'));
  if (is_array($url_exclusion) && count($url_exclusion)) {
    $check_type = \Drupal::config('cleantalk.settings')
      ->get('cleantalk_url_regexp');
    foreach ($url_exclusion as $key => $value) {
      if (!empty($value)) {
        if ($check_type == 1) {

          // If RegExp
          if (@preg_match('/' . trim($value) . '/', $_SERVER['REQUEST_URI'])) {
            return NULL;
          }
        }
        else {
          if (strpos($_SERVER['REQUEST_URI'], $value) !== false) {

            // Simple string checking
            return NULL;
          }
        }
        if (strpos(trim($value), 'node') !== FALSE && strpos($_SERVER['REQUEST_URI'], 'q=comment/reply/') !== FALSE) {
          $get_node = array_values(array_slice(explode('/', trim($value)), -1))[0];
          $current_reply_id = array_values(array_slice(explode('/', $_SERVER['REQUEST_URI']), -1))[0];
          if ($get_node == $current_reply_id) {
            return NULL;
          }
        }
      }
    }
  }
  $ct_authkey = \Drupal::config('cleantalk.settings')
    ->get('cleantalk_authkey');
  $ct_ws = self::_cleantalk_get_ws();
  if (!self::apbct_getcookie('ct_check_js')) {
    $checkjs = NULL;
  }
  elseif (self::apbct_getcookie('ct_check_js') == self::_cleantalk_get_checkjs_value()) {
    $checkjs = 1;
  }
  else {
    $checkjs = 0;
  }
  $ct = new Cleantalk();
  $ct->work_url = $ct_ws['work_url'];
  $ct->server_url = $ct_ws['server_url'];
  $ct->server_ttl = $ct_ws['server_ttl'];
  $ct->server_changed = $ct_ws['server_changed'];
  $role_exclusions = \Drupal::config('cleantalk.settings')
    ->get('cleantalk_roles_exclusions');
  $ct_options = array(
    'access_key' => $ct_authkey,
    'cleantalk_check_comments' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_comments'),
    'cleantalk_check_comments_automod' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_comments_automod'),
    'cleantalk_check_comments_min_approved' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_comments_min_approved'),
    'cleantalk_check_register' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_register'),
    'cleantalk_check_webforms' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_webforms'),
    'cleantalk_check_contact_forms' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_contact_forms'),
    'cleantalk_check_forum_topics' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_forum_topics'),
    'cleantalk_check_search_form' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_search_form'),
    'cleantalk_url_exclusions' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_url_exclusions'),
    'cleantalk_url_regexp' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_url_regexp'),
    'cleantalk_fields_exclusions' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_fields_exclusions'),
    'cleantalk_roles_exclusions' => !empty($role_exclusions) ? implode(',', $role_exclusions) : '',
    'cleantalk_add_search_noindex' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_add_search_noindex'),
    'cleantalk_search_noindex' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_search_noindex'),
    'cleantalk_set_cookies' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_set_cookies'),
    'cleantalk_alternative_cookies_session' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_alternative_cookies_session'),
    'cleantalk_check_ccf' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_check_ccf'),
    'cleantalk_link' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_link'),
    'cleantalk_sfw' => \Drupal::config('cleantalk.settings')
      ->get('cleantalk_sfw'),
  );
  $sender_info = \Drupal\Component\Serialization\Json::encode(array(
    'cms_lang' => \Drupal::languageManager()
      ->getCurrentLanguage()
      ->getId(),
    'REFFERRER' => isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : null,
    'page_url' => isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? htmlspecialchars($_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']) : null,
    'USER_AGENT' => isset($_SERVER['HTTP_USER_AGENT']) ? htmlspecialchars($_SERVER['HTTP_USER_AGENT']) : null,
    'ct_options' => \Drupal\Component\Serialization\Json::encode($ct_options),
    'REFFERRER_PREVIOUS' => self::apbct_getcookie('apbct_prev_referer'),
    'cookies_enabled' => self::_cleantalk_apbct_cookies_test(),
    'fields_number' => sizeof($spam_check),
    'js_timezone' => self::apbct_getcookie('ct_timezone'),
    'mouse_cursor_positions' => !empty($_COOKIE['ct_pointer_data']) ? json_decode(stripslashes($_COOKIE['ct_pointer_data']), true) : null,
    'key_press_timestamp' => !empty($_COOKIE['ct_fkp_timestamp']) ? $_COOKIE['ct_fkp_timestamp'] : null,
    'page_set_timestamp' => !empty($_COOKIE['ct_ps_timestamp']) ? $_COOKIE['ct_ps_timestamp'] : null,
    'form_validation' => $form_errors && is_array($form_errors) ? json_encode(array(
      'validation_notice' => strip_tags(json_encode($form_errors)),
      'page_url' => $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
    )) : null,
  ));
  $post_info = \Drupal\Component\Serialization\Json::encode(array(
    'comment_type' => $spam_check['type'],
    'post_url' => isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : null,
  ));
  $ct_request = new CleantalkRequest();
  $ct_request->auth_key = $ct_authkey;
  $ct_request->agent = CLEANTALK_USER_AGENT;
  $ct_request->response_lang = 'en';
  $ct_request->js_on = $checkjs;
  $ct_request->sender_info = $sender_info;
  $ct_request->post_info = $post_info;
  $ct_request->sender_email = $spam_check['sender_email'];
  $ct_request->sender_nickname = $spam_check['sender_nickname'];
  $ct_request->sender_ip = CleantalkHelper::ip_get(array(
    'real',
  ), false);
  $ct_request->x_forwarded_for = CleantalkHelper::ip_get(array(
    'x_forwarded_for',
  ), false);
  $ct_request->x_real_ip = CleantalkHelper::ip_get(array(
    'x_real_ip',
  ), false);
  $ct_request->submit_time = isset($spam_check['multistep_submit_time']) ? self::_cleantalk_get_submit_time($spam_check['multistep_submit_time']) : self::_cleantalk_get_submit_time(self::apbct_getcookie('apbct_timestamp'));
  switch ($spam_check['type']) {
    case 'comment':
    case 'contact':
    case 'forum_topic':
    case 'webform':
    case 'site_search_drupal8':
    case 'custom_contact_form':
      $timelabels_key = 'mail_error_comment';
      if (is_array($spam_check['message_body'])) {
        $spam_check['message_body'] = isset($spam_check['message_body']['message']) ? $spam_check['message_body']['message'] : implode("\n\n", $spam_check['message_body']);
      }
      $ct_request->message = $spam_check['message_title'] . " \n\n" . strip_tags($spam_check['message_body']);
      $ct_result = $ct
        ->isAllowMessage($ct_request);
      break;
    case 'register':
      $timelabels_key = 'mail_error_reg';
      $ct_request->tz = $spam_check['timezone'];
      $ct_result = $ct
        ->isAllowUser($ct_request);
      break;
  }
  $cleantalk_executed = true;
  $ret_val = array();
  $ret_val['ct_request_id'] = $ct_result->id;
  if ($ct->server_change) {
    self::_cleantalk_set_ws($ct->work_url, $ct->server_ttl, time());
  }

  // First check errstr flag.
  if (!empty($ct_result->errstr) || !empty($ct_result->inactive) && $ct_result->inactive == 1) {

    // Cleantalk error so we go default way (no action at all).
    $ret_val['errno'] = 1;
    if ($checkjs == 0) {
      $ret_val['allow'] = 0;
    }

    // Just inform admin.
    $err_title = $_SERVER['SERVER_NAME'] . ' - CleanTalk hook error';
    if (!empty($ct_result->errstr)) {
      $ret_val['errstr'] = self::_cleantalk_filter_response($ct_result->errstr);
    }
    else {
      $ret_val['errstr'] = self::_cleantalk_filter_response($ct_result->comment);
    }
    $send_flag = FALSE;
    $result = \Drupal::database()
      ->select('cleantalk_timelabels', 'c')
      ->fields('c', array(
      'ct_value',
    ))
      ->condition('ct_key', $timelabels_key, '=')
      ->execute();
    $results = $result
      ->fetchCol(0);
    if (count($results) == 0) {
      $send_flag = TRUE;
    }
    elseif (\Drupal::time()
      ->getRequestTime() - 900 > $result
      ->fetchObject()->ct_value) {

      // 15 minutes.
      $send_flag = TRUE;
    }
    if ($send_flag) {
      \Drupal::database()
        ->merge('cleantalk_timelabels')
        ->key(array(
        'ct_key' => $timelabels_key,
      ))
        ->fields(array(
        'ct_value' => \Drupal::time()
          ->getRequestTime(),
      ))
        ->execute();

      // @FIXME
      // // @FIXME
      // // This looks like another module's variable. You'll need to rewrite this call
      // // to ensure that it uses the correct configuration object.
      // $to = variable_get('site_mail', ini_get('sendmail_from'));
      if (!empty($to)) {
        drupal_mail("cleantalk", $timelabels_key, $to, language_default(), array(
          'subject' => $err_title,
          'body' => $ret_val['errstr'],
          'headers' => array(),
        ), $to, TRUE);
      }
    }
    return $ret_val;
  }
  $ret_val['errno'] = 0;
  if ($ct_result->allow == 1) {

    // Not spammer.
    $ret_val['allow'] = 1;

    // Store request_id in globals to store it in DB later.
    self::_cleantalk_ct_result('set', $ret_val['allow'], $ct_result->id);

    // Don't store 'ct_result_comment', means good comment.
  }
  else {

    // Spammer.
    $ret_val['allow'] = 0;
    $ret_val['ct_result_comment'] = self::_cleantalk_filter_response($ct_result->comment);

    // Check stop_queue flag.
    if ($spam_check['type'] == 'comment') {

      // Spammer and stop_queue == 0 - to manual approvement.
      $ret_val['stop_queue'] = $ct_result->stop_queue;

      // Store request_id and comment in static to store them in DB later.
      self::_cleantalk_ct_result('set', $ct_result->id, $ret_val['allow'], $ret_val['ct_result_comment']);
    }
  }
  return $ret_val;
}