You are here

public function FirewallUpdater::update in Anti Spam by CleanTalk 8.4

Same name and namespace in other branches
  1. 9.1.x src/lib/Cleantalk/Common/Firewall/FirewallUpdater.php \Cleantalk\Common\Firewall\FirewallUpdater::update()

File

src/lib/Cleantalk/Common/Firewall/FirewallUpdater.php, line 83

Class

FirewallUpdater

Namespace

Cleantalk\Common\Firewall

Code

public function update() {
  $helper = $this->helper;
  $fw_stats = $helper::getFwStats();

  // Prevent start another update at a time
  if (Get::get('spbc_remote_call_action') == 'sfw_update__write_base' && !Get::get('firewall_updating_id') && $fw_stats['firewall_updating_id'] && time() - $fw_stats['firewall_updating_last_start'] < 60) {
    return true;
  }

  // Check if the update performs right now. Blocks remote calls with different ID
  if (Get::get('spbc_remote_call_action') == 'sfw_update__write_base' && Get::get('firewall_updating_id') && Get::get('firewall_updating_id') !== $fw_stats['firewall_updating_id']) {
    return array(
      'error' => 'FIREWALL_IS_UPDATING',
    );
  }

  // No updating without api key
  if (empty($this->api_key)) {
    return true;
  }

  // Set new update ID
  if (Get::get('spbc_remote_call_action') == 'sfw_update__write_base' && (!$fw_stats['firewall_updating_id'] || time() - $fw_stats['firewall_updating_last_start'] > 300)) {
    $helper::setFwStats(array(
      'firewall_updating_id' => md5(rand(0, 100000)),
      'firewall_updating_last_start' => time(),
    ));
  }
  if (RemoteCalls::check()) {

    // Remote call is in process, do updating
    $file_urls = Get::get('file_urls');
    $file_ua_url = Get::get('file_ua_url');
    $url_count = Get::get('url_count');
    $current_url = Get::get('current_url');

    // Getting blacklists file here.
    if (!$file_urls) {

      // @todo We have to handle errors here
      $this
        ->createTempTables();
      $blacklists = $this
        ->getSfwBlacklists($this->api_key);
      if (empty($blacklists['error'])) {
        if (!empty($blacklists['file_url'])) {
          $data = $this
            ->unpackData($blacklists['file_url']);
          if (empty($data['error'])) {
            $request_params = array(
              'spbc_remote_call_token' => md5($this->api_key),
              'firewall_updating_id' => $fw_stats['firewall_updating_id'],
              'file_urls' => str_replace(array(
                'http://',
                'https://',
              ), '', $blacklists['file_url']),
              'url_count' => count($data),
              'current_url' => 0,
            );

            /**
             * Add UA files if AC on
             */
            $ac_settings_status = trim(\Drupal::config('cleantalk.settings')
              ->get('cleantalk_sfw_ac'));
            if ($ac_settings_status) {
              $request_params['file_ua_url'] = str_replace(array(
                'http://',
                'https://',
              ), '', $blacklists['file_ua_url']);
            }
            return Helper::http__request__rc_to_host('sfw_update__write_base', $request_params, array(
              'get',
              'async',
            ));
          }
          else {
            return $data;
          }
        }
        else {
          return array(
            'error' => 'NO_REMOTE_MULTIFILE_FOUND: ' . $blacklists['file_url'],
          );
        }
      }
      else {

        // Error getting blacklists.
        return $blacklists;
      }

      // Doing updating here.
    }
    elseif ($file_urls && $url_count > $current_url) {

      /**
       * Add data to UA BL table
       */
      if (!empty($file_ua_url)) {
        $lines = $this
          ->unpackData($file_ua_url);
        if (empty($lines['error'])) {
          $this
            ->addDataUaBlTable($lines);
        }
      }
      $file_url = 'https://' . str_replace('multifiles', $current_url, $file_urls);
      $lines = $this
        ->unpackData($file_url);
      if (empty($lines['error'])) {

        // Do writing to the DB
        reset($lines);
        for ($count_result = 0; current($lines) !== false;) {
          $query = "INSERT INTO " . $this->fw_data_table_name . "_temp (network, mask, status, source) VALUES ";
          for ($i = 0, $values = array(); self::WRITE_LIMIT !== $i && current($lines) !== false; $i++, $count_result++, next($lines)) {
            $entry = current($lines);
            if (empty($entry)) {
              continue;
            }
            if (self::WRITE_LIMIT !== $i) {

              // Cast result to int
              $ip = preg_replace('/[^\\d]*/', '', $entry[0]);
              $mask = preg_replace('/[^\\d]*/', '', $entry[1]);
              $private = isset($entry[2]) ? $entry[2] : 0;
              $source = isset($entry[3]) ? $entry[3] : 0;
            }
            $values[] = '(' . $ip . ',' . $mask . ',' . $private . ',' . $source . ')';
          }
          if (!empty($values)) {
            $query = $query . implode(',', $values) . ';';
            $this->db
              ->execute($query);
          }
        }
        $current_url++;
        $fw_stats['firewall_update_percent'] = round(((int) $current_url + 1) / (int) $url_count, 2) * 100;
        $helper::setFwStats($fw_stats);

        // Updating continue: Do next remote call.
        if ($url_count > $current_url) {
          return Helper::http__request__rc_to_host('sfw_update__write_base', array(
            'spbc_remote_call_token' => md5($this->api_key),
            'file_urls' => str_replace(array(
              'http://',
              'https://',
            ), '', $file_urls),
            'url_count' => $url_count,
            'current_url' => $current_url,
            // Additional params
            'firewall_updating_id' => $fw_stats['firewall_updating_id'],
          ), array(
            'get',
            'async',
          ));

          // Updating end: Do finish actions.
        }
        else {

          // Wtite local IP as whitelisted
          $result = $this
            ->writeDbExclusions();
          if (empty($result['error']) && is_int($result)) {

            // @todo We have to handle errors here
            $this
              ->deleteMainDataTables();

            // @todo We have to handle errors here
            $this
              ->renameDataTables();

            //Files array is empty update sfw stats
            $helper::SfwUpdate_DoFinisnAction();
            $fw_stats['firewall_update_percent'] = 0;
            $fw_stats['firewall_updating_id'] = null;
            $helper::setFwStats($fw_stats);
            return true;
          }
          else {
            return array(
              'error' => 'SFW_UPDATE: EXCLUSIONS: ' . $result['error'],
            );
          }
        }
      }
      else {
        return array(
          'error' => $lines['error'],
        );
      }
    }
    else {
      return array(
        'error' => 'SFW_UPDATE WRONG_FILE_URLS',
      );
    }
  }
  else {

    // Go to init remote call
    return $helper::http__request__rc_to_host('sfw_update', array(
      'spbc_remote_call_token' => md5($this->api_key),
      'firewall_updating_id' => $fw_stats['firewall_updating_id'],
    ), array(
      'get',
      'async',
    ));
  }
}