Jump to content

Get module settings in module function


Recommended Posts

Hi guys, i give up.

Since last night, i try to get the module setting inside a module function. I do it as the many ways i have found on the forum and wiki and documentation but nothing works! I think i have a big stone in my head....

class CommentFilterAntispamguard extends CommentFilter implements Module, ConfigurableModule {

	public static function getModuleInfo() {
		return array(
			'title' => __('Comment Filter: Antispam Guard', __FILE__),
			'version' => 102,
			'summary' => __('Uses a couple of filters to protect your comments from spam.', __FILE__),
			'permanent' => false,
			'singular' => false,
			'autoload' => false,
			'requires' => 'FieldtypeComments',
			);
	}

	static public function getDefaultConfig(){
		return array(
                'require_email_author' => '',
                'honeypot' => '',
                'already_commented' => 'checked',
		'gravatar_check' => '',
		'bbcode_check' => 'checked',
		'advanced_check' => 'checked',
		'regexp_check' => '',
		'spam_ip_local' => '',
		'dnspl_check' => '',
		'approve_comment' => ''
        );

	public function __construct() {
		parent::__construct();
		$this->comment->ip = $this->get_client_ip();
		foreach(self::getDefaultConfig() as $key => $value) {
			$this->$key = $value;
		}
	}

	private static function _verify_comment_request($comment){

	  /* Kommentarwerte */
	  $ip = $comment->ip;
	  $url = $comment->website;
	  $body = $comment->text;
	  $email = $comment->email;
	  $author = $comment->cite;

	  /* Optionen */

	  /* Bereits kommentiert? */
	  if ( $data['already_commented'] && ! empty($email) && self::_is_approved_email($email) ) {
	    return;
	  }

	  /* Check for a Gravatar */
	  if ( $data['gravatar_check']
				&& ! empty($email)
				&& self::_has_valid_gravatar($email) ) {
	      return;
	  }

	  /* Bot erkannt
	  if ( ! empty($_POST['ab_spam__hidden_field']) ) {
	    return array( 'reason' => 'css' );
	  } */

	  /* Action time
	  if ( isset $this->data['time_check']
				&& self::_is_shortest_time() ) {
	    return array( 'reason' => 'time' );
	  } */

	  /* BBCode Spam */
	  if ( $data['bbcode_check'] && self::_is_bbcode_spam($body) ) {
	    return array( 'reason' => 'bbcode' );
	  }

	  /* Erweiterter Schutz */
	  if ( $data['advanced_check'] && self::_is_fake_ip($ip) ) {
	    return array( 'reason' => 'server' );
	  }

	  /* Regexp für Spam */
	  if ( $data['regexp_check'] && self::_is_regexp_spam(
					    array(
					      'ip'	 => $ip,
					      //'host'	 => parse_url($url, PHP_URL_HOST),
					      'body'	 => $body,
					      'email'	 => $email,
					      'author' => $author
					    ) ) ) {
	    return array( 'reason' => 'regexp' );
	  }

	  /* IP im lokalen Spam */
	  if ( $data['spam_ip_local'] && self::_is_db_spam($ip, $url, $email) ) {
	    return array( 'reason' => 'localdb' );
	  }

	  /* DNSBL Spam */
	  if ( $data['dnsbl_check'] && self::_is_dnsbl_spam($ip) ) {
	    return array( 'reason' => 'dnsbl' );
	  }
	}

	static public function getModuleConfigInputfields(array $data) {

		$inputfields = new InputfieldWrapper();

		$name = "require_email_author";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Require E-Mail');
		$f->description = __('Require the E-Mail from commenters.');
		$inputfields->add($f);

		$name = "honeypot";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Activate Honeypot');
		$f->description = __('Add a hidden Field to your Commentform to protect from Spambot.');
		$inputfields->add($f);

		$name = "already_commented";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Trust approved commenters');
		$f->description = __('Always approve previously approved users.');
		$inputfields->add($f);

		$name = "gravatar_check";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Trust Gravatar');
		$f->description = __('Automatically approve Comments from Authors with Gravatar. (Pleas note the Privacy hint)');
		$inputfields->add($f);

		$name = "bbcode_check";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('BBcode as Spam.');
		$f->description = __('Review the comment contents for BBCode links.');
		$inputfields->add($f);

		$name = "advanced_check";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Validate commenters IP');
		$f->description = __('Validity check for used ip address.');
		$inputfields->add($f);

		$name = "regexp_check";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Use regular expressions');
		$f->description = __('Predefined and custom patterns by plugin hook (not now!).');
		$inputfields->add($f);

		$name = "spam_ip_local";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Look in the local spam database');
		$f->description = __('Already marked as spam? Yes? No?.');
		$inputfields->add($f);

		$name = "dnspl_check";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Use public Spam database');
		$f->description = __('Use the public Spam database from https://stopforumspam.com to check for knowen Spamer IP\'s.');
		$inputfields->add($f);

		$name = "approve_comment";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldCheckbox');
		$f->attr('name', $name);
		$f->attr('checked', $data[$name] ? 'checked' : '' );
		$f->label = __('Auto Approve');
		$f->description = __('Automatically approve all comments without spam.');
		$inputfields->add($f);

		return $inputfields;

	}
}

I found many ways to get the settings inside the module. I read all of this posts:

and many more...

i have try

if ( $this->data['already_commented'] );
if ( $data['already_commented'] );
if ( isset($this->data['already_commented']) );
if ( isset($this->already_commented) );
if ( isset($field->already_commented) );

nothing works! While i use $this i get this Error:

Error: Using $this when not in object context (line 86 of site/modules/FieldtypeComments/CommentFilterAntispamguard.module)

I don't know what i can do!!!

Pleas help me, i'm despairing.

Link to comment
Share on other sites

I am not sure what you are after, so a quick answer:

  • In PHP, you cannot refer to a static method using $this. you need self::staticMethodName()
  • Example of accessing module values (including getModuleConfigInputfields()) that are in a static method (ProcessBlog)

Edit: Also, I don't see where $data is coming from in your code, line #73

Edited by kongondo
  • Like 1
Link to comment
Share on other sites

I have testet a lot of things and i don't know what is wrong... I look into many other modules and each module have a other solution for this problem.

I found this:

public function __construct() {
		parent::__construct();
		$this->set('appUserAgent', "ProcessWire/2 | AkismetCommentFilter/1"); 
		$this->set('apiKey', ''); 
	}

protected function verifyKey() {
		if(!$this->comment) throw new WireException("No Comment provided to CommentFilter"); 
		if(!$this->apiKey) throw new WireException("apiKey must be set to use this filter"); 
		$request = "key={$this->apiKey}&blog=" . urlencode($this->homeURL);
		$response = $this->httpPost($request, 'rest.akismet.com', '/1.1/verify-key');
		if($response[1] == 'valid') return true; 
		if($response[1] == 'invalid') throw new WireException("Invalid Akismet Key $request, " . print_r($response, true)); 
		// some other error
		return false; 
	}

static public function getModuleConfigInputfields(array $data) {

		$inputfields = new InputfieldWrapper();

		$name = "apiKey";
		if(!isset($data[$name])) $data[$name] = '';
		$f = Wire::getFuel('modules')->get('InputfieldText'); 
		$f->attr('name', $name); 
		$f->attr('value', $data[$name]); 
		$f->label = __('Akismet Key');
		$f->description = __('If you want to have comments automatically identified as spam, the Comments fieldtype can utilize the Akismet service to do this. In order to use it, you must enter an Akismet API key obtained from akismet.com. Use of this service is optional but recommended.'); // Akismet description

		$inputfields->append($f);

		return $inputfields;

	}

in the CommentFilterAkismet.module from Ryan and this:

// ------------------------------------------------------------------------
    // Init global configuration variables.
    // ------------------------------------------------------------------------
    private static $cacheMaxLifetime;
    private static $cssCachePrefix;
    private static $jsCachePrefix;
    private static $enableHTMLMinify;
    private static $developmentMode;
    private static $directoryTraversal;
    private static $domainSharding;
    private static $domainShardingSSL;
    private static $templateUseSSL;

public function init(){
 // ------------------------------------------------------------------------
        // Set module configuration
        // ------------------------------------------------------------------------
        self::$cssCachePrefix       = wire('sanitizer')->name($this->stylesheet_prefix);
        self::$jsCachePrefix        = wire('sanitizer')->name($this->javascript_prefix);
        self::$cacheMaxLifetime     = self::_sanitizeNumericCacheTime($this->max_cache_lifetime);
        self::$enableHTMLMinify     = ($this->html_minify == 1) ? true : false;
        self::$developmentMode      = ($this->development_mode == 1) ? true : false;
        self::$directoryTraversal   = ($this->directory_traversal == 1) ? true : false;
        self::$domainSharding       = self::_validateURL($this->domain_sharding);
        self::$domainShardingSSL    = self::_validateURL($this->domain_sharding_ssl);
}

 private static function _clearCache($force_all = false) {
       if(self::$developmentMode) return true;
}

(some code shortened) in the All in one Minify Module....

or

static protected $defaults = array(
    'fullname' => '',
    'color' => 'blue',
    'age' => 40
  );
  public function __construct() {
    // populate defaults, which will get replaced with actual
    // configured values before the init/ready methods are called
    $this->setArray(self::$defaults);
  }
  public function ready() {
    if($this->fullname && !count($this->input->post)) {
      $msg = "Hi $this->fullname! ";
      $msg .= "Your age: $this->age. ";
      $msg .= "Favorite color: $this->color.";
      $this->message($msg);
    }
  }

at https://processwire.com/blog/posts/new-module-configuration-options/

But nothing will work for me....

What is the best solution for getting setup variables inside the module and how to call this variables? In one of my modules i use the method set AIOM use. But there are some modules without global variables but with settings inside and call this settings in the module. I think its better to do

Link to comment
Share on other sites

Thanks, this article i've already read. (see the first post)

I think i can not use the "config.module" because my module is not placed in a separate folder. At the moment i place my module inside the FieldtypeComment folder where the Akismet module is placed.

Did you even read our responses? :-) What do you mean by 'But nothing will work for me....' ??

yes i read it all and i try a lot of changes and tests in the background.

Non of the exemples worked on my code....

I delete everything and start from scratch.

Link to comment
Share on other sites

In this block of code...

	private static function _verify_comment_request($comment){
 
	  /* Kommentarwerte */
	  $ip = $comment->ip;
	  $url = $comment->website;
	  $body = $comment->text;
	  $email = $comment->email;
	  $author = $comment->cite;
 
	  /* Optionen */
 
	  /* Bereits kommentiert?  @kongondo: Where is this $data coming from?*/
	  if ( $data['already_commented'] && ! empty($email) && self::_is_approved_email($email) ) {
	    return;
	  }

...where is $data coming from? It needs to come from somewhere...e.g.

private static function _verify_comment_request($comment, $data){

}
 

  • Like 1
Link to comment
Share on other sites

You are right. This is a broken version of code...

Damn!!! Thanks kongondo, now i have seen what you meant in your first post...

  • In PHP, you cannot refer to a static method using $this. you need self::staticMethodName()

the _verify_comment_request() should not be static!!! I don't know why i have type this at night. I have only see the "public static function getModuleInfo()" and not the other!

Sorry guys i have a lot to learn and sleep more time.

Link to comment
Share on other sites

You could always use the separate module config as long as your module is in any subdirectory. It's named after your modules, so there cannot be any conflicts and it makes things a heck of a lot more streamlined and less static-y.

Link to comment
Share on other sites

You could always use the separate module config as long as your module is in any subdirectory. It's named after your modules, so there cannot be any conflicts and it makes things a heck of a lot more streamlined and less static-y.

thank you LostKobrakai, i will test this tonight.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...