<commit_before><?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Plugin to check submitted notices with Mollom
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Mollom is a bayesian spam checker, wrapped into a webservice
 * This plugin is based on the Drupal Mollom module
 *
 * @category  Plugin
 * @package   Laconica
 * @author    <NAME> <<EMAIL>>
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 *
 */

if (!defined('STATUSNET')) {
    exit(1);
}

define('MOLLOMPLUGIN_VERSION', '0.1');
define('MOLLOM_API_VERSION', '1.0');

define('MOLLOM_ANALYSIS_UNKNOWN' , 0);
define('MOLLOM_ANALYSIS_HAM'     , 1);
define('MOLLOM_ANALYSIS_SPAM'    , 2);
define('MOLLOM_ANALYSIS_UNSURE'  , 3);

define('MOLLOM_MODE_DISABLED', 0);
define('MOLLOM_MODE_CAPTCHA' , 1);
define('MOLLOM_MODE_ANALYSIS', 2);

define('MOLLOM_FALLBACK_BLOCK' , 0);
define('MOLLOM_FALLBACK_ACCEPT', 1);

define('MOLLOM_ERROR'   , 1000);
define('MOLLOM_REFRESH' , 1100);
define('MOLLOM_REDIRECT', 1200);

/**
 * Plugin to check submitted notices with Mollom
 *
 * Mollom is a bayesian spam filter provided by webservice.
 *
 * @category Plugin
 * @package  Laconica
 * @author   <NAME> <<EMAIL>>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 *
 * @see      Event
 */



class MollomPlugin extends Plugin
{
    function __construct($url=null) {
        parent::__construct();
    }

    function onStartNoticeSave($notice)
    {
    error_log(print_r($notice, 1));
      if (common_config('mollom', 'public_key')) {
        //Check spam
        $data = array(
            'post_body'      => $notice->content,
            'author_name'    => $profile->nickname,
            'author_url'     => $profile->homepage,
            'author_id'      => $profile->id,
            'author_ip'      => $this->getClientIp(),
        );
        $response = $this->mollom('mollom.checkContent', $data);
        if ($response['spam'] == MOLLOM_ANALYSIS_SPAM) {
          throw new ClientException(_("Spam Detected"), 400);
        }
        if ($response['spam'] == MOLLOM_ANALYSIS_UNSURE) {
          //if unsure, let through
        }
        if($response['spam'] == MOLLOM_ANALYSIS_HAM) {
          // all good! :-)
        }
      }
   
      return true;
    }

    function getClientIP() {
        if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
            // Note: order matters here; use proxy-forwarded stuff first
            foreach (array('HTTP_X_FORWARDED_FOR', 'CLIENT-IP', 'REMOTE_ADDR') as $k) {
                if (isset($_SERVER[$k])) {
                    return $_SERVER[$k];
                }
            }
        }
        return '127.0.0.1';
    }
    /**
      * Call a remote procedure at the Mollom server.  This function will
      * automatically add the information required to authenticate against
      * Mollom.
      */
    function mollom($method, $data = array()) {
        if (!extension_loaded('xmlrpc')) {
            if (!dl('xmlrpc.so')) {
                common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
            }
        }
    
      // Construct the server URL:
      $public_key = common_config('mollom', 'public_key');
      // Retrieve the list of Mollom servers from the database:
      $servers = common_config('mollom', 'servers');
    
      if ($servers == NULL) {
        // Retrieve a list of valid Mollom servers from mollom.com:
        $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
        
        // Store the list of servers in the database:
    // TODO!    variable_set('mollom_servers', $servers);
      }
      
      if (is_array($servers)) {
        // Send the request to the first server, if that fails, try the other servers in the list:
        foreach ($servers as $server) { 
          $auth = $this->authentication();
          $data = array_merge($data, $auth);
          $result = $this->xmlrpc($server .'/'. MOLLOM_API_VERSION, $method, $data);
    
          // Debug output:
          if (isset($data['session_id'])) {
            error_log("called $method at server $server with session ID '". $data['session_id'] ."'");
          }
          else {
            error_log("called $method at server $server with no session ID");
          }
          
          if ($errno = $this->xmlrpc_errno()) {
            error_log(sprintf('Error @errno: %s - %s - %s - <pre>%s</pre>', $this->xmlrpc_errno(), $server, $this->xmlrpc_error_msg(), $method, print_r($data, TRUE)));
    
            if ($errno == MOLLOM_REFRESH) {
              // Retrieve a list of valid Mollom servers from mollom.com:
              $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
    
              // Store the updated list of servers in the database:
              //tODO variable_set('mollom_servers', $servers);
            }
            else if ($errno == MOLLOM_ERROR) {
              return $result;
            }
            else if ($errno == MOLLOM_REDIRECT) {
              // Do nothing, we select the next client automatically.
            }
    
            // Reset the XMLRPC error:
            $this->xmlrpc_error(0);  // FIXME: this is crazy.
          }
          else {
            error_log("Result = " . print_r($result, TRUE));
            return $result;
          }
        }
      }
    
      // If none of the servers worked, activate the fallback mechanism:
      error_log("none of the servers worked");
    //   _mollom_fallback();
      
      // If everything failed, we reset the server list to force Mollom to request a new list:
      //TODO variable_set('mollom_servers', array());
    }

    /**
    * This function generate an array with all the information required to
    * authenticate against Mollom. To prevent that requests are forged and
    * that you are impersonated, each request is signed with a hash computed
    * based on a private key and a timestamp.
    *
    * Both the client and the server share the secret key that is used to
    * create the authentication hash based on a timestamp.  They both hash
    * the timestamp with the secret key, and if the hashes match, the
    * authenticity of the message has been validated.
    *
    * To avoid that someone can intercept a (hash, timestamp)-pair and
    * use that to impersonate a client, Mollom will reject the request
    * when the timestamp is more than 15 minutes off.
    *
    * Make sure your server's time is synchronized with the world clocks,
    * and that you don't share your private key with anyone else.
    */
    private function authentication() {
    
      $public_key = common_config('mollom', 'public_key');
      $private_key = common_config('mollom', 'private_key');
    
      // Generate a timestamp according to the dateTime format (http://www.w3.org/TR/xmlschema-2/#dateTime):
      $time = gmdate("Y-m-d\TH:i:s.\\0\\0\\0O", time());<commit_msg>Use common_{log,debug} instead of error_log for logging<commit_after><?php
/**
 * Laconica, the distributed open-source microblogging tool
 *
 * Plugin to check submitted notices with Mollom
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Mollom is a bayesian spam checker, wrapped into a webservice
 * This plugin is based on the Drupal Mollom module
 *
 * @category  Plugin
 * @package   Laconica
 * @author    <NAME> <<EMAIL>>
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 *
 */

if (!defined('STATUSNET')) {
    exit(1);
}

define('MOLLOMPLUGIN_VERSION', '0.1');
define('MOLLOM_API_VERSION', '1.0');

define('MOLLOM_ANALYSIS_UNKNOWN' , 0);
define('MOLLOM_ANALYSIS_HAM'     , 1);
define('MOLLOM_ANALYSIS_SPAM'    , 2);
define('MOLLOM_ANALYSIS_UNSURE'  , 3);

define('MOLLOM_MODE_DISABLED', 0);
define('MOLLOM_MODE_CAPTCHA' , 1);
define('MOLLOM_MODE_ANALYSIS', 2);

define('MOLLOM_FALLBACK_BLOCK' , 0);
define('MOLLOM_FALLBACK_ACCEPT', 1);

define('MOLLOM_ERROR'   , 1000);
define('MOLLOM_REFRESH' , 1100);
define('MOLLOM_REDIRECT', 1200);

/**
 * Plugin to check submitted notices with Mollom
 *
 * Mollom is a bayesian spam filter provided by webservice.
 *
 * @category Plugin
 * @package  Laconica
 * @author   <NAME> <<EMAIL>>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 *
 * @see      Event
 */



class MollomPlugin extends Plugin
{
    function __construct($url=null) {
        parent::__construct();
    }

    function onStartNoticeSave($notice)
    {
      if (common_config('mollom', 'public_key')) {
        //Check spam
        $data = array(
            'post_body'      => $notice->content,
            'author_name'    => $profile->nickname,
            'author_url'     => $profile->homepage,
            'author_id'      => $profile->id,
            'author_ip'      => $this->getClientIp(),
        );
        $response = $this->mollom('mollom.checkContent', $data);
        if ($response['spam'] == MOLLOM_ANALYSIS_SPAM) {
          throw new ClientException(_("Spam Detected"), 400);
        }
        if ($response['spam'] == MOLLOM_ANALYSIS_UNSURE) {
          //if unsure, let through
        }
        if($response['spam'] == MOLLOM_ANALYSIS_HAM) {
          // all good! :-)
        }
      }
   
      return true;
    }

    function getClientIP() {
        if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
            // Note: order matters here; use proxy-forwarded stuff first
            foreach (array('HTTP_X_FORWARDED_FOR', 'CLIENT-IP', 'REMOTE_ADDR') as $k) {
                if (isset($_SERVER[$k])) {
                    return $_SERVER[$k];
                }
            }
        }
        return '127.0.0.1';
    }
    /**
      * Call a remote procedure at the Mollom server.  This function will
      * automatically add the information required to authenticate against
      * Mollom.
      */
    function mollom($method, $data = array()) {
        if (!extension_loaded('xmlrpc')) {
            if (!dl('xmlrpc.so')) {
                common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
            }
        }
    
      // Construct the server URL:
      $public_key = common_config('mollom', 'public_key');
      // Retrieve the list of Mollom servers from the database:
      $servers = common_config('mollom', 'servers');
    
      if ($servers == NULL) {
        // Retrieve a list of valid Mollom servers from mollom.com:
        $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
        
        // Store the list of servers in the database:
    // TODO!    variable_set('mollom_servers', $servers);
      }
      
      if (is_array($servers)) {
        // Send the request to the first server, if that fails, try the other servers in the list:
        foreach ($servers as $server) { 
          $auth = $this->authentication();
          $data = array_merge($data, $auth);
          $result = $this->xmlrpc($server .'/'. MOLLOM_API_VERSION, $method, $data);
    
          // Debug output:
          if (isset($data['session_id'])) {
            common_debug("called $method at server $server with session ID '". $data['session_id'] ."'");
          }
          else {
            common_debug("called $method at server $server with no session ID");
          }
          
          if ($errno = $this->xmlrpc_errno()) {
            common_log(LOG_ERR, sprintf('Error @errno: %s - %s - %s - <pre>%s</pre>', $this->xmlrpc_errno(), $server, $this->xmlrpc_error_msg(), $method, print_r($data, TRUE)));
    
            if ($errno == MOLLOM_REFRESH) {
              // Retrieve a list of valid Mollom servers from mollom.com:
              $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
    
              // Store the updated list of servers in the database:
              //tODO variable_set('mollom_servers', $servers);
            }
            else if ($errno == MOLLOM_ERROR) {
              return $result;
            }
            else if ($errno == MOLLOM_REDIRECT) {
              // Do nothing, we select the next client automatically.
            }
    
            // Reset the XMLRPC error:
            $this->xmlrpc_error(0);  // FIXME: this is crazy.
          }
          else {
            common_debug("Result = " . print_r($result, TRUE));
            return $result;
          }
        }
      }
    
      // If none of the servers worked, activate the fallback mechanism:
      common_debug("none of the servers worked");
    //   _mollom_fallback();
      
      // If everything failed, we reset the server list to force Mollom to request a new list:
      //TODO variable_set('mollom_servers', array());
    }

    /**
    * This function generate an array with all the information required to
    * authenticate against Mollom. To prevent that requests are forged and
    * that you are impersonated, each request is signed with a hash computed
    * based on a private key and a timestamp.
    *
    * Both the client and the server share the secret key that is used to
    * create the authentication hash based on a timestamp.  They both hash
    * the timestamp with the secret key, and if the hashes match, the
    * authenticity of the message has been validated.
    *
    * To avoid that someone can intercept a (hash, timestamp)-pair and
    * use that to impersonate a client, Mollom will reject the request
    * when the timestamp is more than 15 minutes off.
    *
    * Make sure your server's time is synchronized with the world clocks,
    * and that you don't share your private key with anyone else.
    */
    private function authentication() {
    
      $public_key = common_config('mollom', 'public_key');
      $private_key = common_config('mollom', 'private_key');
    
      // Generate a timestamp according to the dateTime format (http://www.w3.org/TR/xmlschema-2/#dateTime):
      $time = gmdate("Y-m-d\TH:i:s.\\0\\0\\0O", time());
{'fraction_non_alphanumeric': 0.11892272262026612, 'fraction_numerical': 0.006844933469805527, 'mean_word_length': 2.438847338319402, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 8, 'xml': 26}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3722363', 'n_tokens_mistral': 4805, 'n_tokens_neox': 4641, 'n_words': 1416}