source: wp-hashcash/trunk/wp-hashcash.php @ 342466

Revision 342466, 23.6 KB checked in by donncha, 16 months ago (diff)

Bump version to 4.6 and update changelog

Line 
1<?php
2/*
3 Plugin Name: WordPress Hashcash
4 Plugin URI: http://wordpress-plugins.feifei.us/hashcash/
5 Description: Client-side javascript blocks all spam bots.  XHTML 1.1 compliant.
6 Author: Elliott Back
7 Author URI: http://elliottback.com
8 Version: 4.6
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 */
21
22function wphc_option($save = false){
23        if($save) {
24                if( function_exists( 'update_site_option' ) ) {
25                        update_site_option('plugin_wp-hashcash', $save);
26                } else {
27                        update_option('plugin_wp-hashcash', $save);
28                }
29
30                return $save;
31        } else {
32                if( function_exists( 'get_site_option' ) ) {
33                        $options = get_site_option('plugin_wp-hashcash');
34                } else {
35                        $options = get_option('plugin_wp-hashcash');
36                }
37
38                if(!is_array($options))
39                        $options = array();
40
41                return $options;
42        }
43}
44
45/**
46 * Install WP Hashcash
47 */
48
49function wphc_install () {
50        // set our default options
51        $options = wphc_option();
52        $options['comments-spam'] = $options['comments-spam'] || 0;
53        $options['comments-ham'] = $options['comments-ham'] || 0;
54        $options['signups-spam'] = $options['signups-spam'] || 0;
55        $options['signups-ham'] = $options['signups-ham'] || 0;
56        $options['key'] = array();
57        $options['key-date'] = 0;
58        $options['refresh'] = 60 * 60 * 24 * 7;
59        $options['signup_active'] = 1;
60        $options['comments_active'] = 1;
61        $options['attribution'] = 1;
62       
63        // akismet compat check
64        if(function_exists('akismet_init')){
65                $options['moderation'] = 'akismet';
66        } else {
67                $options['moderation'] = 'moderate';
68        }
69       
70        // validate ip / url
71        $options['validate-ip'] = true;
72        $options['validate-url'] = true;
73
74        // logging
75        $options['logging'] = true;
76
77        // update the key
78        wphc_option($options);
79        wphc_refresh();
80}
81
82add_action('activate_wp-hashcash/wp-hashcash.php', 'wphc_install');
83add_action('activate_wp-hashcash.php', 'wphc_install');
84
85/**
86 * Update the key, if needed
87 */
88
89function wphc_refresh(){
90        $options = wphc_option();
91
92        if( !isset( $options[ 'signup_active' ] ) ) {
93                wphc_install();
94                return;
95        }
96
97        if(time() - $options['key-date'] > $options['refresh']) {
98                if(count($options['key']) >= 5)
99                        array_shift($options['key']);
100
101                array_push($options['key'], rand(21474836, 2126008810));
102
103                $options['key-date'] = time();
104                wphc_option($options);
105        }
106}
107
108add_action('shutdown', 'wphc_refresh');
109
110/**
111 * Our plugin can also have a widget
112 */
113
114function get_spam_ratio( $ham, $spam ) {
115        if($spam + $ham == 0)
116                $ratio = 0;
117        else
118                $ratio = round(100 * ($spam/($ham+$spam)),2);
119
120        return $ratio;
121}
122
123function widget_ratio($options){
124        $signups_ham = (int)$options['signups-ham'];
125        $signups_spam = (int)$options['signups-spam'];
126        $ham = (int)$options['comments-ham'];
127        $spam = (int)$options['comments-spam'];
128        $ratio = get_spam_ratio( $ham, $spam );
129        $signups_ratio = get_spam_ratio( $signups_ham, $signups_spam );
130
131        $msg = "<li><span>$spam spam comments blocked out of $ham human comments.  " . $ratio ."% of your comments are spam!</span></li>";
132
133        if( $signups_ham && $signups_spam )
134                $msg = "<li><span>$signups_spam spam signups blocked out of $signups_ham human signups.  " . $signups_ratio ."% of your signups are spam!</span></li>";
135
136        return $msg;
137}
138
139/**
140 * Admin Options
141 */
142
143add_action('admin_menu', 'wphc_add_options_to_admin');
144
145function wphc_add_options_to_admin() {
146        if( function_exists( 'is_site_admin' ) && !is_site_admin() )
147                return;
148
149        if (function_exists('add_options_page')) {
150                if( function_exists( 'is_site_admin' ) ) {
151                        add_submenu_page('wpmu-admin.php', __('WordPress Hashcash'), __('WordPress Hashcash'), 'manage_options', 'wphc_admin', 'wphc_admin_options');
152                } else {
153                        add_options_page('Wordpress Hashcash', 'Wordpress Hashcash', 8, basename(__FILE__), 'wphc_admin_options');
154                }
155        }
156}
157
158function wphc_admin_options() {
159        if( function_exists( 'is_site_admin' ) && !is_site_admin() )
160                return;
161
162        $options = wphc_option();
163
164        if( !isset( $options[ 'signup_active' ] ) ) {
165                wphc_install(); // MU has no activation hook
166                $options = wphc_option();
167        }
168
169        // POST HANDLER
170        if($_POST['wphc-submit']){
171                check_admin_referer( 'wphc-options' );
172                if ( function_exists('current_user_can') && !current_user_can('manage_options') )
173                        die('Current user not authorized to managed options');
174
175                $options['refresh'] = strip_tags(stripslashes($_POST['wphc-refresh']));
176                $options['moderation'] = strip_tags(stripslashes($_POST['wphc-moderation']));
177                $options['validate-ip'] = strip_tags(stripslashes($_POST['wphc-validate-ip']));
178                $options['validate-url'] = strip_tags(stripslashes($_POST['wphc-validate-url']));
179                $options['logging'] = strip_tags(stripslashes($_POST['wphc-logging']));
180                $options['signup_active'] = (int) $_POST['signup_active'];
181                $options['comments_active'] = (int) $_POST['comments_active'];
182                wphc_option($options);
183        }
184       
185        // MAIN FORM
186        echo '<style type="text/css">
187                .wrap h3 { color: black; background-color: #e5f3ff; padding: 4px 8px; }
188
189                .sidebar {
190                        border-right: 2px solid #e5f3ff;
191                        width: 200px;
192                        float: left;
193                        padding: 0px 20px 0px 10px;
194                        margin: 0px 20px 0px 0px;
195                }
196
197                .sidebar input {
198                        background-color: #FFF;
199                        border: none;
200                }
201
202                .main {
203                        float: left;
204                        width: 600px;
205                }
206
207                .clear { clear: both; }
208        </style>';
209
210        echo '<div class="wrap">';
211
212        echo '<div class="sidebar">';
213        echo '<h3>Plugin</h3>';
214        echo '<ul>
215        <li><a href="http://wordpress-plugins.feifei.us/hashcash/">Plugin\'s Homepage</a></li>';
216        if( function_exists( 'is_site_admin' ) && is_site_admin() ) {
217                echo '<li><a href="http://mu.wordpress.org/forums/">WordPress MU Forums</a></li>';
218        }
219        echo '<li><a href="http://wordpress.org/tags/wp-hashcash">Plugin Support Forum</a></li>';
220        echo '</ul>';           
221        echo '<h3>Donation</h3>';
222        echo '<center><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
223<input type="hidden" name="cmd" value="_s-xclick">
224<input style="border:none;" type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
225<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
226<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHTwYJKoZIhvcNAQcEoIIHQDCCBzwCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJKoZIhvcNAQEBBQAEgYB92DQNuZFkPnoaXIGUgUCBMNWj7VUVJdLa3lfGJ7JbMOoBJA0T5e4p/iydz35l+95Chl9z17WRD00ne+fkm6f2/9IKLzvp8jOhuHzD/OyQPj9hGXH6uXGrAeLrPEfh4GpWnsv8g5c3ARM1wdETboRudQwjy7Fxjsz3SzGseILnXTELMAkGBSsOAwIaBQAwgcwGCSqGSIb3DQEHATAUBggqhkiG9w0DBwQIKY5dtf5OOeqAgahu2NkH46BLYa4W734anwXSxL8AbN0QPmgYZ4TAxEG2Tzd7EmFlC1WeG1hi/fGS7aoJ4jzr08N25QZyvcAKwF4Ud2ycMRvmoPqHwFtlxF+vQ4yDGwjUuMcwK8+yhOwuCD4ElHoGp1A7SzPGsjrFBaComuzzdBSuuIXoS8v/l7BKOepUJkpAj2lhshh562GvUqY8UtanV5QY5pN9wEIkx1zZrvcfh8YUQFGgggOHMIIDgzCCAuygAwIBAgIBADANBgkqhkiG9w0BAQUFADCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20wHhcNMDQwMjEzMTAxMzE1WhcNMzUwMjEzMTAxMzE1WjCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMFHTt38RMxLXJyO2SmS+Ndl72T7oKJ4u4uw+6awntALWh03PewmIJuzbALScsTS4sZoS1fKciBGoh11gIfHzylvkdNe/hJl66/RGqrj5rFb08sAABNTzDTiqqNpJeBsYs/c2aiGozptX2RlnBktH+SUNpAajW724Nv2Wvhif6sFAgMBAAGjge4wgeswHQYDVR0OBBYEFJaffLvGbxe9WT9S1wob7BDWZJRrMIG7BgNVHSMEgbMwgbCAFJaffLvGbxe9WT9S1wob7BDWZJRroYGUpIGRMIGOMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxFDASBgNVBAoTC1BheVBhbCBJbmMuMRMwEQYDVQQLFApsaXZlX2NlcnRzMREwDwYDVQQDFAhsaXZlX2FwaTEcMBoGCSqGSIb3DQEJARYNcmVAcGF5cGFsLmNvbYIBADAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAIFfOlaagFrl71+jq6OKidbWFSE+Q4FqROvdgIONth+8kSK//Y/4ihuE4Ymvzn5ceE3S/iBSQQMjyvb+s2TWbQYDwcp129OPIbD9epdr4tJOUNiSojw7BHwYRiPh58S1xGlFgHFXwrEBb3dgNbMUa+u4qectsMAXpVHnD9wIyfmHMYIBmjCCAZYCAQEwgZQwgY4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLUGF5UGFsIEluYy4xEzARBgNVBAsUCmxpdmVfY2VydHMxETAPBgNVBAMUCGxpdmVfYXBpMRwwGgYJKoZIhvcNAQkBFg1yZUBwYXlwYWwuY29tAgEAMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wODAzMjQwMDE3NTBaMCMGCSqGSIb3DQEJBDEWBBS0fFUHov0nsYX2eSAA/ufHpUOIIDANBgkqhkiG9w0BAQEFAASBgHJc/pMXctQsQFliIlc/izXs4whQ5vDPC+UUy+FQ8jKp+lA6as3P5+EXCUOtbx9xTj8HEYwM0DodZv0w+Y6DTo6y/uNzbhOAKSGkml1l6co1WTtKY4axurF/b1lJqZuC1a57qALC72F62OvVeeYILmu6Z/ZIvMaWERL85cwp0mCl-----END PKCS7-----"></form></center>';
227        echo '<p>Any small donation would be highly appreciated.</p>';
228        echo '<h3>Miscellaneous</h3>';
229        echo '<ul>
230        <li><a href="http://wordpress-plugins.feifei.us/">Elliott\'s WP Plugins</a></li>
231        <li><a href="http://ocaoimh.ie/wordpress-plugins/">Donncha\'s WP Plugins</a></li>
232        </ul>';
233        echo '<h3>Statistics</h3>';
234        echo '<p>'.widget_ratio($options).'</p>';
235        echo '</div>';
236
237        echo '<div class="main">';
238        echo '<h2>WordPress Hashcash</h2>';
239        echo '<p>This is an antispam plugin that eradicates spam signups on WordPress sites. It works because your visitors must use obfuscated
240        javascript to submit a proof-of-work that indicates they opened your website in a web browser, not a robot.  You can read more about it on the
241        <a href="http://wordpress-plugins.feifei.us/hashcash/">WordPress Hashcash plugin page</a> of my site.</p>';
242
243        echo '<h3>Standard Options</h3>';
244        echo '<form method="POST" action="?page=' . $_GET[ 'page' ] . '&updated=true">';
245        wp_nonce_field('wphc-options');
246        if( function_exists( 'is_site_admin' ) ) { // MU only
247                $signup_active = (int)$options[ 'signup_active' ];
248                $comments_active = (int)$options[ 'comments_active' ];
249                echo "<p><label>Signup protection enabled: <input type='checkbox' name='signup_active' value='1' " . ( $signup_active == '1' ? ' checked' : '' ) . " /></label></p>";
250                echo "<p><label>Comments protection enabled: <input type='checkbox' name='comments_active' value='1' " . ( $comments_active == '1' ? ' checked' : '' ) . " /></label></p>";
251        }
252        // moderation options
253        $moderate = htmlspecialchars($options['moderation'], ENT_QUOTES);
254        echo '<p><label for="wphc-moderation">' . __('Moderation:', 'wp-hashcash') . '</label>';
255        echo '<select id="wphc-moderation" name="wphc-moderation">';
256        echo '<option value="moderate"'.($moderate=='moderate'?' selected':'').'>Moderate</option>';
257        echo '<option value="akismet"'.($moderate=='akismet'?' selected':'').'>Akismet</option>';
258        echo '<option value="delete"'.($moderate=='delete'?' selected':'').'>Delete</option>';
259        echo '</select>';
260        echo '<br/><span style="color: grey; font-size: 90%;">The default is to place spam comments into the
261        akismet/moderation queue. Otherwise, the delete option will immediately discard spam comments.</span>';
262        echo '</p>';
263
264        // refresh interval
265        $refresh = htmlspecialchars($options['refresh'], ENT_QUOTES);
266        echo '<p><label for="wphc-refresh">' . __('Key Expiry:', 'wp-hashcash').'</label>
267                <input style="width: 200px;" id="wphc-refresh" name="wphc-refresh" type="text" value="'.$refresh.'" />
268                <br/><span style="color: grey; font-size: 90%;">Default is one week, or <strong>604800</strong> seconds.</p>';
269
270        // current key
271        echo '<p>Your current key is <strong>' . $options['key'][count($options['key']) - 1] . '</strong>.';
272        if(count($options['key']) > 1)
273                echo ' Previously you had keys '. join(', ', array_reverse(array_slice($options['key'], 0, count($options['key']) - 1))).'.';
274        echo '</p>';
275
276        // additional options
277        echo '<h3>Additional options:</h3>';
278
279        $validate_ip = htmlspecialchars($options['validate-ip'], ENT_QUOTES);
280        echo '<p><label for="wphc-validate-ip">Validate IP Address</label>
281                <input name="wphc-validate-ip" type="checkbox" id="wphc-validate-ip"'.($validate_ip?' checked':'').'/>
282                <br /><span style="color: grey; font-size: 90%;">
283                Checks if the IP address of the trackback sender is equal to the IP address of the webserver the trackback URL is referring to.</span></p>';
284
285        $validate_url = htmlspecialchars($options['validate-url'], ENT_QUOTES);
286        echo '<p><label for="wphc-validate-url">Validate URL</label>
287                <input name="wphc-validate-url" type="checkbox" id="wphc-validate-url"'.($validate_url?' checked':'').'/>
288                <br /><span style="color: grey; font-size: 90%;">Retrieves the web page located at the URL included
289                in the trackback to check if it contains a link to your blog.  If it does not, it is spam!</span></p>';
290
291        // logging options
292        echo '<h3>Logging:</h3>';
293
294        $logging = htmlspecialchars($options['logging'], ENT_QUOTES);
295        echo '<p><label for="wphc-logging">Logging</label>
296                <input name="wphc-logging" type="checkbox" id="wphc-logging"'.($logging?' checked':'').'/>
297                <br /><span style="color: grey; font-size: 90%;">Logs the reason why a given comment failed the spam
298                check into the comment body.  Works only if moderation / akismet mode is enabled.</span></p>';
299
300        echo '<input type="hidden" id="wphc-submit" name="wphc-submit" value="1" />';
301        echo '<input type="submit" id="wphc-submit-override" name="wphc-submit-override" value="Save WP Hashcash Settings"/>';
302        echo '</form>';
303        echo '</div>';
304
305        echo '<div class="clear">';
306        echo '<p style="text-align: center; font-size: .85em;">&copy; Copyright '.date('Y').' <a href="http://elliottback.com">Elliott B&auml;ck</a></p>';
307        echo '</div>';
308
309        echo '</div>';
310}
311
312/**
313 * Add JS to the header
314 */
315function wphc_posthead() {
316        if( function_exists( 'is_site_admin' ) ) {
317                $options = wphc_option();
318                if( !$options['comments_active'] )
319                        return;
320        }
321        if((is_single() || is_page()))
322                wphc_addhead();
323}
324add_action('wp_head', 'wphc_posthead');
325
326function wphc_signuphead() {
327        if( function_exists( 'is_site_admin' ) ) {
328                $options = wphc_option();
329                if( !$options['signup_active'] )
330                        return;
331        }
332        wphc_addhead();
333}
334add_action('signup_header', 'wphc_signuphead');
335
336function wphc_addhead() {
337        echo "<script type=\"text/javascript\"><!--\n";
338        echo 'function addLoadEvent(func) {
339  if( typeof jQuery != \'undefined\' ) {
340    jQuery(document).ready( func );
341  } else if( typeof Prototype != \'undefined\' ) {
342    Event.observe( window, \'load\', func );
343  } else {
344    var oldonload = window.onload;
345    if (typeof window.onload != \'function\') {
346      window.onload = func;
347    } else {
348      window.onload = function() {
349        if (oldonload)
350          oldonload();
351       
352        func();
353      }
354    }
355  }
356}
357';
358        echo  wphc_getjs() . "\n";
359        echo "addLoadEvent(function(){var el=document.getElementById('wphc_value');if(el)el.value=wphc();});\n";
360        echo "//--></script>\n";
361}
362
363function wphc_getjs(){
364        $options = wphc_option();
365        $val = $options['key'][count($options['key']) - 1];
366        $js = 'function wphc_compute(){';
367
368        switch(rand(0, 3)){
369                /* Addition of n times of field value / n, + modulus:
370                 Time guarantee:  100 iterations or less */
371                case 0:
372                        $inc = rand($val / 100, $val - 1);
373                        $n = floor($val / $inc);
374                        $r = $val % $inc;
375               
376                        $js .= "var wphc_eax = $inc; ";
377                        for($i = 0; $i < $n - 1; $i++){
378                                $js .= "wphc_eax += $inc; ";
379                        }
380                       
381                        $js .= "wphc_eax += $r; ";
382                        $js .= 'return wphc_eax; ';
383                        break;
384
385                        /* Conversion from binary:
386                Time guarantee:  log(n) iterations or less */
387                case 1:
388                        $binval = strrev(base_convert($val, 10, 2));
389                        $js .= "var wphc_eax = \"$binval\"; ";
390                        $js .= 'var wphc_ebx = 0; ';
391                        $js .= 'var wphc_ecx = 0; ';
392                        $js .= 'while(wphc_ecx < wphc_eax.length){ ';
393                        $js .= 'if(wphc_eax.charAt(wphc_ecx) == "1") { ';
394                        $js .= 'wphc_ebx += Math.pow(2, wphc_ecx); ';
395                        $js .= '} ';
396                        $js .= 'wphc_ecx++; ';
397                        $js .= '} ';
398                        $js .= 'return wphc_ebx;';
399                       
400                break;
401               
402                /* Multiplication of square roots:
403                Time guarantee:  constant time */
404                case 2:
405                        $sqrt = floor(sqrt($val));
406                        $r = $val - ($sqrt * $sqrt);
407                        $js .= "return $sqrt * $sqrt + $r; ";
408                break;
409               
410                /* Sum of random numbers to the final value:
411                Time guarantee:  log(n) expected value */
412                case 3:
413                        $js .= 'return ';
414       
415                        $i = 0;
416                        while($val > 0){
417                                if($i++ > 0)
418                                        $js .= '+';
419                               
420                                $temp = rand(1, $val);
421                                $val -= $temp;
422                                $js .= $temp;
423                        }
424       
425                        $js .= ';';
426                break;
427        }
428               
429        $js .= '} wphc_compute();';
430       
431        // pack bytes
432        if( !function_exists( 'strToLongs' ) ) {
433        function strToLongs($s) {
434                $l = array();
435           
436                // pad $s to some multiple of 4
437                $s = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
438           
439                while(count($s) % 4 != 0){
440                        $s [] = ' ';
441                }
442       
443                for ($i = 0; $i < ceil(count($s)/4); $i++) {
444                        $l[$i] = ord($s[$i*4]) + (ord($s[$i*4+1]) << 8) + (ord($s[$i*4+2]) << 16) + (ord($s[$i*4+3]) << 24);
445                }
446       
447                return $l;
448        }
449        }
450       
451        // xor all the bytes with a random key
452        $key = rand(21474836, 2126008810);
453        $js = strToLongs($js);
454       
455        for($i = 0; $i < count($js); $i++){
456                $js[$i] = $js[$i] ^ $key;
457        }
458       
459        // libs function encapsulation
460        $libs = "function wphc(){\n";
461       
462        // write bytes to javascript, xor with key
463        $libs .= "\tvar wphc_data = [".join(',',$js)."]; \n";
464       
465        // do the xor with key
466        $libs .= "\n\tfor (var i=0; i<wphc_data.length; i++){\n";
467        $libs .= "\t\twphc_data[i]=wphc_data[i]^$key;\n";
468        $libs .= "\t}\n";
469       
470        // convert bytes back to string
471        $libs .= "\n\tvar a = new Array(wphc_data.length); \n";
472        $libs .= "\tfor (var i=0; i<wphc_data.length; i++) { \n";
473        $libs .= "\t\ta[i] = String.fromCharCode(wphc_data[i] & 0xFF, wphc_data[i]>>>8 & 0xFF, ";
474        $libs .= "wphc_data[i]>>>16 & 0xFF, wphc_data[i]>>>24 & 0xFF);\n";
475        $libs .= "\t}\n";
476       
477        $libs .= "\n\treturn eval(a.join('')); \n";
478       
479        // call libs function
480        $libs .= "}";
481       
482        // return code
483        return $libs;
484}
485
486/**
487 * Hook into the signups form
488 */
489function wphc_add_signupform(){
490        echo '<input type="hidden" id="wphc_value" name="wphc_value" value=""/>';
491}
492add_action('signup_hidden_fields', 'wphc_add_signupform');
493add_action('bp_after_registration_submit_buttons', 'wphc_add_signupform');
494
495function wphc_add_commentform(){
496        $options = wphc_option();
497       
498        switch($options['moderation']){
499                case 'delete':
500                        $verb = 'deleted';
501                        break;
502                case 'akismet':
503                        $verb = 'queued in Akismet';
504                        break;
505                case 'moderate':
506                default:
507                        $verb = 'placed in moderation';
508                        break;
509        }
510       
511        echo '<div><input type="hidden" id="wphc_value" name="wphc_value" value=""/></div>';
512        echo '<noscript><div><small>Wordpress Hashcash needs javascript to work, but your browser has javascript disabled. Your comment will be '.$verb.'!</small></div></noscript>';
513}
514
515add_action('comment_form', 'wphc_add_commentform');
516
517/**
518 * Validate our tag
519 */
520
521function wphc_check_signup_hidden_tag( $result ) {
522        // get our options
523        $options = wphc_option();
524        $spam = false;
525        if( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
526                return $result;
527
528        // Check the wphc values against the last five keys
529        $spam = !in_array($_POST["wphc_value"], $options['key']);
530       
531        if($spam){
532                $options['signups-spam'] = ((int) $options['signups-spam']) + 1;
533                wphc_option($options);
534                $result['errors']->add( 'blogname', __('You did not pass a spam check. Please enable JavaScript in your browser.') );
535        } else {
536                $options['signups-ham'] = ((int) $options['signups-ham']) + 1;
537                wphc_option($options);
538        }
539       
540        return $result;
541}
542
543add_filter( 'wpmu_validate_blog_signup', 'wphc_check_signup_hidden_tag' );
544add_filter( 'wpmu_validate_user_signup', 'wphc_check_signup_hidden_tag' );
545
546function wphc_check_signup_for_bp(){
547        global $bp;
548
549        // get our options
550        $options = wphc_option();
551        $spam = false;
552
553        // Check the wphc values against the last five keys
554        $spam = !in_array($_POST["wphc_value"], $options['key']);
555
556        if($spam){
557                $options['signups-spam'] = ((int) $options['signups-spam']) + 1;
558                wphc_option($options);
559                $bp->signup->errors['spam'] = __('You did not pass a spam check. Please enable JavaScript in your browser.');
560        } else {
561                $options['signups-ham'] = ((int) $options['signups-ham']) + 1;
562                wphc_option($options);
563        }
564}
565
566add_action('bp_signup_validate', 'wphc_check_signup_for_bp');
567
568function wphc_error_hook_register_page(){
569        do_action('bp_spam_errors');
570}
571
572add_action('bp_before_register_page', 'wphc_error_hook_register_page');
573
574function wphc_check_hidden_tag($comment) {
575        // admins can do what they like
576        if( is_admin() )
577                return $comment;
578       
579        // get our options
580        $type = $comment['comment_type'];
581        $options = wphc_option();
582        $spam = false;
583
584        if($type == "trackback" || $type == "pingback"){
585                // check the website's IP against the url it's sending as a trackback
586                if($options['validate-ip']){
587                        $server_ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
588                        $web_ip = gethostbyname(parse_url($comment['comment_author_url'], PHP_URL_HOST));
589                        $ipv = $server_ip != $web_ip;
590                        $spam = $spam || ($ipv);
591                       
592                        if($options['logging'] && $ipv) $comment['comment_content'] .= "\n\n[WORDPRESS HASHCASH] The comment's server IP (".$server_ip.") doesn't match the"
593                                . " comment's URL host IP (".$web_ip.") and so is spam.";
594                }
595
596                // look for our link in the page itself
597                if(!$spam && $options['validate-url']){
598                        if(!class_exists('Snoopy'))
599                                require_once( ABSPATH . WPINC . '/class-snoopy.php' );
600                               
601                        $permalink = get_permalink($comment['comment_post_ID']);
602                        $permalink = preg_replace('/\/$/', '', $permalink);
603                        $snoop = new Snoopy;
604                       
605                        if (@$snoop->fetchlinks($comment['comment_author_url'])){
606                                $found = false;
607                               
608                                if( !empty( $snoop->results ) )
609                                {
610                                        foreach($snoop->results as $url){
611                                                $url = preg_replace('/(\/|\/trackback|\/trackback\/)$/', '', $url);
612                                                if($url == $permalink)
613                                                        $found = true; 
614                                        }
615                                }
616                               
617                                if($options['logging'] && !$found)
618                                        $comment['comment_content'] .= "\n\n[WORDPRESS HASHCASH] The comment's actual post text did not contain your blog url (".$permalink.") and so is spam.";
619                               
620                                $spam = $spam || !$found;
621                        } else {
622                                $spam = true;
623                                if($options['logging'])
624                                        $comment['comment_content'] .= "\n\n[WORDPRESS HASHCASH] Snoopy failed to fetch results for the comment blog url (".$comment['comment_author_url'].") with error '".$snoop->error."' and so is spam.";
625                        }
626                }
627        } else {
628                // Check the wphc values against the last five keys
629                $spam = !in_array($_POST["wphc_value"], $options['key']);
630                if($options['logging'] && $spam)
631                        $comment['comment_content'] .= "\n\n[WORDPRESS HASHCASH] The poster sent us '".intval($_POST["wphc_value"])." which is not a hashcash value.";
632        }
633       
634        if($spam){
635                $options['comments-spam'] = ((int) $options['comments-spam']) + 1;
636                wphc_option($options);
637                       
638                switch($options['moderation']){
639                        case 'delete':
640                                add_filter('comment_post', create_function('$id', 'wp_delete_comment($id); die(\'This comment has been deleted by WP Hashcash\');'));
641                                break;
642                        case 'akismet':
643                                add_filter('pre_comment_approved', create_function('$a', 'return \'spam\';'));
644                                break;
645                        case 'moderate':
646                        default:
647                                add_filter('pre_comment_approved', create_function('$a', 'return 0;'));
648                                break;
649                }
650        } else {
651                $options['comments-ham'] = ((int) $options['comments-ham']) + 1;
652                wphc_option($options);
653        }
654       
655        return $comment;
656}
657
658add_filter('preprocess_comment', 'wphc_check_hidden_tag');
659?>
Note: See TracBrowser for help on using the repository browser.