Please enter a search term to begin your search.

Comment Guard Pro Developer Guide

Overview

Comment Guard Pro provides an extensive API to create pluglets (plugins for Comment Guard Pro) which extend and enhance the functionality of Comment Guard Pro.

Comment Guard Pro is modularly architected. The heart of Comment Guard Pro are the pluglets which provide most of the functionalities. Comment Guard supports two kind of pluglets - pre pluglets & post pluglets.

Comment Guard Pro ships with 14 pre pluglets and 1 post pluglet. Additionally 7 free pre pluglets are provided in the Comment Guard Pro Powerpack plugin. We encourage you to write your own pluglets, distribute them, give them away for free or even sell them if you want; your pluglet your decision. Use the forum to discuss your ideas, showcase your implementation and help others.

Notes:
  • Pluglet author can specify the default preferences of a pluglet
  • Pluglet author can enable or disable the pluglet by default
  • Pluglet author can get preferences and design UI for advanced preferences
  • User can change the order of execution of pre & post pluglets
  • User can override the default (both basic and advanced) preferences of a pluglet.
  • User can enable or disable individual pluglets.

Pre Pluglet

All pre pluglets are invoked sequentially for processing a comment. Each pre-pluglet can either take a direct decision (approve, delete, send for moderation, mark as spam) on the status of a comment or assign it a score depending on success or failure of the rule.

A comment is classified based on decision taken by one or more pre pluglets in the specified execution order.

Each pluglet can either take a direct decision (action) on the status of a comment or can assign a score based on its evaluation. Each pluglet comes pre-configured with a default action for success and failure condition. Please refer to the documentation of individual pluglets to determine the default action on success or failure. In most cases you are fine with the default. However you are encouraged to experiment.

Each pre pluglet can specify whether it will be enabled (available) while rechecking (manual or automated with Recheck Comment pluglet) a queue (like Approved or Moderation queue) for spam. You can view the option for each pluglet.

Post Pluglet

All post-pluglets are invoked sequentially after a comment has been processed and finally classified. Post pluglets do not have any say in decision making. Post pluglets can be used for running background tasks, delayed checks of comments, collecting / providing statistics, creating graphics for stats etc. Post pluglets which are designed to do time consuming tasks should latch on to processing of spam comments so the delay / cost is passed on to spammers.

Comment Guard Pro Pluglet API

Each pluglet has a basic configuration (action on success and failure) by default. You can change the default values of basic configuration options using the API. Comment Guard Pro also allows you to provide additional configuration options.

Pre Pluglet / Pre Rule Functions

tgAddPreRules($plugletMainFunctionName, $plugletName, $parameters = '')

This function allows you to add a pre pluglet.

Input:

$plugletMainFunctionName - This is the name of your pluglets main function which detects the spamminess of a comment based on your business rule / logic. This function gets comment data as an input parameter which has the following data structure:

Array
(
    [comment_post_ID] => 21
    [comment_author] => John Spammer Smith
    [comment_author_email] => [email protected]
    [comment_author_url] => http://www.examplespamsite.com
    [comment_content] => This is an attempted spam.
    [comment_type] => 
    [user_ID] => 
)

Note:
  • comment_post_ID is the post id at which the comment is targeted.
  • comment_type is empty for normal comment, "pingback" for pingback comment and "trackback" for trackback comment.
  • user_ID contains the user id for logged in commenter, otherwise it is empty.

This function returns an array based on its evaluation:

array('resultCode' => 'true', 'resultMsg' => 'message explaining the resultCode, if any')

resultCode is a required parameter and contains one of the following:

  • resultCode should be 'true' when the pluglet identifies the comment as ham (not spam).
  • resultCode must be 'false' for spam.
  • When the pluglet is not applicable to a comment (doesn't process the specific type of comment for any reason), resultCode must be 'N/A'.

resultMsg contains an optional reason explaining the decision. Any reason specified here will be shown in Comment Guard Pro Management console against the comment.

$plugletName - This is the name of your pluglet which is displayed in Pluglet console. Pluglet name must be unique across all pluglets. It is also used to refer to this pluglet data in subsequent API calls.

$parameters - This is an optional parameter string containing one or more parameters in key=>value format, separated by comma ( , ). The order of key=>value pairs within the string is not important. None of the values should contain comma. Pluglet description should be base64 encoded and hence can contain anything (originally; before encoding). All the parameters are optional.

plugletDocURL=>Pluglet documentation url
author=>Pluglet author name
plugletDescription=>Pluglet description (base64 encoded)
plugletConfiguration=>Name of additional / advanced configuration function 
plugletCallbackConfiguration=>Name of additional / advanced configuration callback function
order=>Pluglet order
insertOnCollision=>Insert on collision
recheck=>Enable for recheck

Let's examine the individual parameters in more details:

  • Pluglet documentation url - Specify the url to obtain more information about your pluglet. This is used to hyperlink your pluglet name in Pluglet console.
  • Pluglet author name - This is displayed in the header of each pluglet after pluglet name in Pluglet console.
  • Pluglet description - Description of your pluglet which is displayed in Pluglet console. It must be base64 encoded.
  • Name of advanced configuration function - This function should return advanced configuration form data, when advanced configuration needs to be provided, as a string excluding starting and ending form tags. To specify advanced / additional configuration you need to provide the html form which will be displayed to get user input.
    Note: When advanced configuration is not required this parameter and the next one should not be provided.
  • Name of advanced configuration callback function - This function saves pluglet additional / advanced configuration options. It gets an array as an input parameter which contains submitted form data for pluglet advanced configuration.
  • Pluglet order - This is the order of execution of the pluglet while evaluating a comment. The same order is used to display a pluglet in Pluglet console. You can assign any positive integer value greater than zero but less than 100 as your pluglet order. The default value 10. Comment Guard Pro user can also change the order of each pluglet from Pluglet console which overrides this setting.
  • Insert on collision - This is a string which can either be 'true' or 'false'. When two pluglets have the same order then this parameter is used to determine whether the newly added pluglet will be inserted at the specified order (when set to 'true'), by pushing up by one position all the pluglets currently on or above that order, or the new pluglet will be added at the next available position. By default it is 'true'.
  • Enable for recheck - This is a string, which can either be 'true' or 'false', which specifies whether the pluglet is available for rechecking (both manual and automatic).By default it is 'false'.

Here is a simple example of $parameters:

$parameters = 'order=>2,
                    plugletDocURL=>'http://www.taragana.com/products/commentguard', 
                    author=>'Angsuman Chakraborty', 
                    plugletDescription=>' . base64_encode("My Super Pluglet Example Description."), ' 
                    plugletConfiguration=>getMyPlugletConfig, 
                    plugletCallbackConfiguration=>saveMyPlugletAdvancedConfig, 
                    insertOnCollision=>false,
                    recheck=>true';

Output: None

Note: You can also, perhaps more easily, construct $parameters by calling tgCreateParameterString(), described below.

tgCreateParameterString($plugletOrder = NULL, $plugletDocumentURL = '', $PlugletAuthor = '', $plugletDescription = '', $plugletConfigurationFunctionName = '', $plugletCallbackConfigurationFunctionName = '', $insertOnCollision = NULL, $enableForRecheck = NULL)

Comment Guard Pro provides an alternative, perhaps simpler, way to construct $parameters (third input parameter of tgAddPreRules and tgAddPostRules function) by using this function.

Input (See tgAddPreRules() documentation for details on the parameters):

  • $plugletOrder
  • $plugletDocumentURL
  • $plugletAuthor
  • $plugletDescription - This is a plain (not base64 encoded) string. We do the base64 encoding for you.
  • $plugletConfigurationFunctionName
  • $plugletConfigurationCallbackFunctionName
  • $insertOnCollosion
  • $enableForRecheck

Note: For post pluglets the last parameter $enableForRecheck is not required.

Output: It returns a string which can be used as $parameters argument in tgAddPreRules() and tgAddPostRules().

tgSetBasicConfiguration($plugletName, $plugletConfig)

Pluglet basic configuration has two sections - decision / action to be taken on success of $plugletMainFunctionName and decision / action to be taken on failure. By using this function you can set the default decisions.

On success the available decisions are:

  • Approve comment and stop processing
  • Assign a score and continue

On failure the available decisions are:

  • Send to moderation queue and stop processing
  • Mark as spam and stop processing
  • Delete comment and stop processing
  • Assign a score and continue

Input:

$plugletName - This is the name of your pluglet which you specified in tgAddPreRules().

$plugletConfig - This is a string containing one or more parameters in key=>value format, separated by comma ( , ). The order of key=>value pairs within the string is not important.

For success the key is success and the value is either approve (approve comment and stop processing) or score (assign a score and continue).

For failure the key is failure and the value is either moderate (send to moderation queue and stop processing) or spam (mark as spam and stop processing) or nuke (delete comment and stop processing) or score (assign a score and continue).

For both success and failure if the decision is score then the corresponding score should also be specified. Comment Guard Pro provides two additional keys to assign score value. For success the key is sScore and for failure the key is fScore. You can assign any numeric value or the string N/A (not applicable) to sScore and fScore.

For example if you want to set the basic configuration of your pluglet as shown below

On success - Approve comment and stop processing

On failure - Assign a score and continue

then $plugletConfig will be -

success => approve, failure => score, fScore => -1

Note: All keys are case sensitive.

Example

Lets see an example of a pre pluglet named Comment Link Limit:

Normal comment rarely contains more than two links. Comment Link Limit pluglet rejects comment which contains more than 4 links (configurable).

// Default number of links in comment content beyond which the comment will be rejected.
$linkLimitToReject = 4;
/*
Adds the Comment Link Limit pluglet if Comment Guard Pro plugin is available and active.
*/
function addLinkLimitPluglet() {
    if(function_exists('tgAddPreRules')) {
    
        // Create parameter string for tgAddPreRules function.
        $parameterString = tgCreateParameterString(
            10, 
            'http://www.taragana.com/products/commentguard', 
            'Angsuman Chakraborty', 
            'Comment spammers often embed several links in a single comment. Normal comments rarely 
            contains more than two links. Any comment with greater than four links is almost 
            certainly a spam. You can use this pluglet to specify the maximum allowable number of 
            links in a comment beyond which it is considered as a   spam and simply deleted.',
            'getLinkLimitRejectAdvancedConfig',
            'saveLinkLimitRejectAdvancedConfig',
            'true',
            'true'
        );
        
        // Add Comment Link Limit pluglet to Comment Guard Pro pluglet list.
        tgAddPreRules('rejectOnLinkLimit', 'Comment Link Limit', $parameterString);
        
        // Set default actions / decisions of Comment Link Limit pluglets basic configuration.
        tgSetBasicConfiguration('Comment Link Limit',
                                'success => score, failure => nuke, sScore => 0');
    }
}

/*
This is Comment Link Limit pluglets main function. It determines number of links
in a comment text and rejects the comment if the number of links in comment text exceeds 
(configurable) link limit.
*/
function rejectOnLinkLimit($comment) {
    global $linkLimitToReject;
    $ltLinks = get_option('linkLimitLinks');
    if($ltLinks === false) {
        $ltLinks = $linkLimitToReject;
    }
    $ltLinks = intval(trim($ltLinks));
    $links = preg_match_all('/http[s]?:\/\/www\.|http[s]?:\/\/|www\./is', 
                             $comment['comment_content'], 
                             $matches);
    if($links > $ltLinks) return (array('resultCode' => 'false'));
    return (array('resultCode' => 'true'));
}

/*
This is Comment Link Limit pluglet's advanced configuration function.
It returns advanced configuration form data for this pluglet. It allows 
user to specify the maximum number of links in a comment text beyond which
the comment will be rejected.
*/
function getLinkLimitRejectAdvancedConfig() {
    global $linkLimitToReject;
    $links = get_option('linkLimitLinks');
    if($links === false) {
        $links = $linkLimitToReject;
        update_option('linkLimitLinks', $links);
    }
    $formData = '
        <b>Link limit ( Reject )</b><br/>
        You can either keep the default value of 4 or set it to any positive integer
        value greater than zero. Setting it to zero or any negative value or leaving
        it blank will automatically reset the link limit to the default value (4).<br/>
        How many links : <input type="text" value="' . $links . '" name="linkLimitLinks">
                         </input><br/>';
    return $formData;
}

/*
This is Comment Link Limit pluglet's advanced configuration callback function. 
It gets the user updated value of maximum number of links in comment text and saves that value 
in database for later use. 
*/
function saveLinkLimitRejectAdvancedConfig($postData = array()) {
    global $linkLimitToReject;
    if(isset($postData['linkLimitLinks'])) {
        $links = trim($postData['linkLimitLinks']);
        if(intval($links) > 0) {
            update_option('linkLimitLinks', $links);
        } else {
            update_option('linkLimitLinks', $linkLimitToReject);
        }
    } else {
        update_option('linkLimitLinks', $linkLimitToReject);
    }
}

// This call addLinkLimitPluglet() on 'init' hook.
add_action('init', 'addLinkLimitPluglet');

Post Pluglet or Post Rule Functions

Post pluglets do not have any basic configuration unlike pre pluglets. However Comment Guard Pro allows you to display advanced configuration options for each post pluglet, if needed, similar to pre pluglets.

tgAddPostRules($plugletMainFunctionName, $plugletName, $parameters = '')

This function allows you to add a post pluglet to the Comment Guard Pro.

Input:

$plugletMainFunctionName - This is the name of your pluglets main function. It gets comment data as an input parameter which has one of two data structure, described below, depending on whether the comment is nuked or not. Comment data has the following data structure for approved, moderated or spam comments:

Array
(
    [comment_post_ID] => 21
    [comment_author] => tips
    [comment_author_email] => [email protected]
    [comment_author_url] =>
    [comment_author_IP] => 172.16.0.60
    [comment_date] => 2007-12-21 15:42:52
    [comment_date_gmt] => 2007-12-21 10:12:52
    [comment_content] => This is a tips test
    [comment_karma] => 0
    [comment_approved] => 1
    [comment_agent] => Incutio XML-RPC -- WordPress/2.3
    [comment_type] => 
    [comment_parent] => 0
    [user_id] => 0
    [cg_reason] => Array
        (
            [approve] => Array
                (
                    [pluglet] => Array
                        (
                            [Approve Pingback / Trackback From Blogroll] => 
                        )

                )

        )
)

Comment data has the following data structure for comments which are deleted / nuked by Comment Guard Pro:

Array
(
    [comment_post_ID] => 21
    [comment_author] => tips
    [comment_author_email] => [email protected]
    [comment_author_url] => 
    [comment_content] => This is a tips test
    [comment_type] => 
    [user_ID] => 
    [comment_approved] => nuke
)

$plugletName - It is same as $plugletName parameter of tgAddPreRules function described above.

$parameters - It is same as $parameters parameter of tgAddPreRules function described above, except it doesn't process $enableForRecheck parameter.

Here is a simple example of $parameters:

$parameters = 'order=>2,
                    plugletDocURL=>'http://www.taragana.com/products/commentguard', 
                    author=>'Angsuman Chakraborty', 
                    plugletDescription=>' . base64_encode("My Super Pluglet Example Description."), ' 
                    plugletConfiguration=>getMyPlugletConfig, 
                    plugletCallbackConfiguration=>saveMyPlugletAdvancedConfig, 
                    insertOnCollision=>false';

Note: You can also, perhaps more easily, construct $parameters by calling tgCreateParameterString(), described previously.

Output: None

Example

Lets see an example of a post pluglet named as Spam Keywords Statistics:

Spam Keywords Statistics pluglet generates statistics based on configurable list of spam key words which is displayed in Advanced configuration section. It shows how many spams caught by Comment Guard Pro contains a particular spam keyword.

// Default spam key words.
$spamKeyWords = '
soma,
casino,
phentermine
';

/*
Adds the Spam Keywords Statistics pluglet if Comment Guard Pro plugin is available and active.
*/
function addSpamKeywordsStatisticsPluglet() {
    if(function_exists('tgAddPostRules')) {
    
        // Create parameter string for tgAddPostRules function.
        $parameterString = 'order=>2,
                            plugletDocURL=>http://www.taragana.com/products/commentguard, 
                            author=>Angsuman Chakraborty, 
                            plugletDescription=>' . base64_encode("Spam Keywords Statistics
                            pluglet generates statistics based on configurable list of spam key words 
                            which is displayed in Advanced configuration section. It shows how many 
                            spams caught by Comment Guard Pro contains a particular spam keyword.") . ',  
                            plugletConfiguration=>getSpamKeywordsStatisticsAdvancedConfig, 
                            plugletCallbackConfiguration=>saveSpamKeywordsStatisticsAdvancedConfig, 
                            insertOnCollision=>false';
        
        // Add Spam Keywords Statistics pluglet to Comment Guard Pro pluglet list.
        tgAddPostRules('logSpamsBasedOnSpamKeywords', 'Spam Keywords Statistics', $parameterString);
    }
}

/*
This is Spam Keywords Statistics pluglets main function. It counts frequency of (configurable)
spam keywords and saves that information to display statistics. By default the statistics 
will be shown in advanced configuration of this pluglet. However by using
<?php echo getSpamKeyWordsStatistics(); ?> tag you can display this statistics 
anywhere in your template.
*/
function logSpamsBasedOnSpamKeywords($comment) {
    global $spamKeyWords;
    if($comment['comment_approved'] == 'spam') {
        $update = false;
        $statistics = get_option('spamKeyWordsStat');
        $spamKeys = get_option('spamKeys');
        if($spamKeys === false) $spamKeys = $spamKeyWords;
        if('' == $spamKeys) return; // If spam keys are empty
        $words = explode("\n", $spamKeys);
        foreach((array)$words as $word) {
            $word = trim($word);
    
            // Skip empty lines
            if(empty($word)) continue;
    
            // Do some escaping magic so that '#' chars in the
            // spam words don't break things:
            $pqWord = preg_quote($word, '#');
            if(preg_match("#$pqWord#i", $comment['comment_content'])) {
                $update = true;
                if(array_key_exists($word, $statistics)) {
                    $statistics[$word] += 1;
                } else {
                    $statistics[$word] = 1;
                }
            }
        }
        if($update) update_option('spamKeyWordsStat', $statistics);
    }
}

/*
It returns statistics string to display spam keywords statistics. You can add the following
tag anywhere in your template to display statistics:
<?php echo getSpamKeyWordsStatistics(); ?>
*/
function getSpamKeyWordsStatistics() {
    $str = '';
    $statistics = get_option('spamKeyWordsStat');
    if($statistics === false) return $str;
    $str = '<table><tr><td>Spam key word</td><td>Count</td></tr>';
    foreach($statistics as $key=>$value) {
        $str .= '<tr><td>' . $key . '</td><td>' . $value . '</td></tr>';
    }    
    $str .= '</table>';
    return $str;
}

/*
This is Spam Keywords Statistics pluglets advanced configuration function.
It returns advanced configuration form data for this pluglet. It shows spam
keywords in a text area. Each keyword should be in a separate line. It also
displays the statistics at the top.
*/
function getSpamKeywordsStatisticsAdvancedConfig() {
    global $spamKeyWords;
    $keys = get_option('spamKeys');
    if($keys === false) $keys = $spamKeyWords;
    $formData = '';
    $str = getSpamKeyWordsStatistics();
    if(strlen($str) > 0) $formData .= $str . '</br>';
    $formData .= '
        <b>Spam keywords</b><br/><textarea name="spamKeys" cols="46" rows="9" 
        class="code">' . $keys . '</textarea><br/>';
    return $formData;    
}

/*
This is Spam Keywords Statistics pluglets advanced configuration callback function. 
It saves the user updated list of spam keywords in database. 
*/
function saveSpamKeywordsStatisticsAdvancedConfig($postData = array()) {
    if(isset($postData['spamKeys'])) {
        update_option('spamKeys', trim($postData['spamKeys']));
    } else {
        update_option('spamKeys', '');
    }
}

// Add Spam Keywords Statistics pluglet in 'init' action hook
add_action('init', 'addSpamKeywordsStatisticsPluglet');

Common Functions

tgIsActive($plugletName)

Input:

$plugletName - This is the name of your pluglet which you specified in tgAddPreRules() or tgAddPostRules().

Output:

It returns true (boolean) if the pluglet (pre or post) is enabled. Otherwise it returns false (boolean).

For example:

if(tgIsActive('Comment Link Limit')) {
    // execute your statements 
}

tgDisablePluglet($plugletName)

Input:

$plugletName - This is the name of your pluglet which you specified in tgAddPreRules() or tgAddPostRules().

Output: None.

For example:

tgDisablePluglet('Comment Link Limit');

This will disable Comment Link Limit pluglet by default.