-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_captcha_img.plugin.php
1514 lines (1297 loc) · 44 KB
/
_captcha_img.plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file implements the Captcha Image plugin.
*
* The core functionality was provided by Ben Franske and then converted and improved
* by Daniel HAHLER into a plugin.
*
* Based on hn_captcha Version 1.2 by Horst Nogajski
* - hn_captcha is a fork of ocr_captcha by Julien Pachet
*
* This file is part of the b2evolution/evocms project - {@link http://b2evolution.net/}.
* See also {@link http://sourceforge.net/projects/evocms/}.
*
* @copyright 2006 by Daniel HAHLER - {@link http://daniel.hahler.de/}.
*
* @license http://b2evolution.net/about/license.html GNU General Public License (GPL)
* {@internal
* b2evolution is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* b2evolution 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with b2evolution; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the copyright holders give permission to link
* the code of this program with the PHP/SWF Charts library by maani.us (or with
* modified versions of this library that use the same license as PHP/SWF Charts library
* by maani.us), and distribute linked combinations including the two. You must obey the
* GNU General Public License in all respects for all of the code used other than the
* PHP/SWF Charts library by maani.us. If you modify this file, you may extend this
* exception to your version of the file, but you are not obligated to do so. If you do
* not wish to do so, delete this exception statement from your version.
* }}
*
* @package plugins
*
* @author blueyed: Daniel HAHLER
* @author Ben Franske, http://ben.franske.com
*/
if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
/**
* The Captcha Image Plugin.
*
* It displays an captcha image through {@link CaptchaValidated()} and validates
* it in {@link CaptchaValidated()}.
*
* The image gets served by an htsrv method ({@link htsrv_display_captcha()} and the
* private/public keys get stored in the user's Session.
*
* @todo If a comment gets previewed, re-use the same captcha image and re-use eventually posted code in input field
* @todo Make sure font files are really font files..
*/
class captcha_img_plugin extends Plugin
{
var $version = '2.0.4';
var $group = 'antispam';
/**
* High priority: Should get called early, so other plugins can skip their
* action in case there are already errors from us (e.g. the OpenID plugin).
* @var integer
*/
var $priority = 20;
/**
* Delete unnecessary captcha data from DB table.
*
* @todo This should be added to the "scheduler", once available
*/
function PluginInit( & $params )
{
$this->name = $this->T_('Captcha images');
$this->short_desc = $this->T_('Use generated images to tell humans and robots apart.');
if( $params['is_installed'] && rand(0, 100) == 42 )
{
register_shutdown_function( array(&$this, 'purge_obsolete_db_data') );
}
return true;
}
function GetDefaultSettings( & $params )
{
global $Settings;
return array(
'protect_trackback_url' => array(
'label' => $this->T_('Protect trackback URLs'),
'type' => 'checkbox',
'defaultvalue' => '1',
),
'TTF_folder' => array(
'label' => $this->T_( 'Fonts folder' ),
'defaultvalue' => 'fonts/',
'note' => $this->T_('Path to a folder with TrueType fonts for captcha text, relative to the plugin file.'),
'size' => 20,
),
'timeout_key' => array(
'label' => $this->T_('Timeout for keys'),
'defaultvalue' => 120, // timeout: 2 hours
'note' => $this->T_('in minutes. When does the generated captcha expire?'),
'size' => 5,
'type' => 'integer',
),
'use_websafecolors' => array(
'label' => $this->T_('Websafe colors'),
'defaultvalue' => 0,
'note' => $this->T_('Use web safe colors (only 216 colors)?'),
'type' => 'checkbox',
),
'noise' => array(
'label' => $this->T_('Noise'),
'defaultvalue' => 1,
'note' => $this->T_('Use background noise characters instead of a grid.'),
'type' => 'checkbox',
),
'noisefactor' => array(
'label' => $this->T_('Noise factor'),
'defaultvalue' => 9,
'note' => $this->T_('Noise multiplier (number of characters gets multipled by this to define noise).'),
'type' => 'integer',
'size' => 5,
),
'minchars' => array(
'label' => $this->T_('Min chars'),
'defaultvalue' => 4,
'note' => $this->T_('The minimum number of characters to use.'),
'type' => 'integer',
'size' => 4,
),
'maxchars' => array(
'label' => $this->T_('Max chars'),
'defaultvalue' => 6,
'note' => $this->T_('The maximum number of characters to use.'),
'type' => 'integer',
'size' => 5,
),
'min_fontsize' => array(
'label' => $this->T_('Min font size'),
'defaultvalue' => 20,
'note' => $this->T_('The minimum font size to use.'),
'type' => 'integer',
'size' => 5,
),
'max_fontsize' => array(
'label' => $this->T_('Max font size'),
'defaultvalue' => 30,
'note' => $this->T_('The maximum font size to use.'),
'type' => 'integer',
'size' => 5,
),
'max_rotation' => array(
'label' => $this->T_('Max rotation'),
'defaultvalue' => 25,
'note' => $this->T_('The maximum degrees a char should be rotated. 25 means a random rotation between -25 and 25.'),
'type' => 'integer',
'size' => 5,
),
'jpegquality' => array(
'label' => $this->T_('JPEG quality'),
'defaultvalue' => 80,
'note' => $this->T_('JPEG image quality.'),
'type' => 'integer',
'size' => 5,
'maxlength' => 3,
),
'validchars' => array(
'label' => $this->T_('Valid characters'),
'defaultvalue' => 'abcdefghjkmnpqrstuvwxyz23456789@#$%&ABCDEFGHJKLMNPQRSTUVWXYZ23456789@#$%&',
'note' => $this->T_('Valid characters to use in generated images.'),
'size' => 50,
),
'case_sensitive' => array(
'label' => $this->T_('Case sensitive'),
'defaultvalue' => 0,
'note' => $this->T_('Use case sensitive keys?'),
'type' => 'checkbox',
),
'use_for' => array(
'label' => $this->T_('Use for'),
'layout' => 'begin_fieldset',
),
'use_for_anonymous' => array(
'label' => $this->T_('Use for anonymous'),
'defaultvalue' => 1,
'note' => $this->T_('Should this plugin be used for anonymous users?'),
'type' => 'checkbox',
),
'use_for_members_level_below' => array(
'label' => $this->T_('Use for members'),
'defaultvalue' => 0,
'note' => $this->T_('Use this plugin for members of the target blog, if their level is below this.'),
'type' => 'integer',
'size' => 3,
'valid_range' => array( 'min'=>0, 'max'=>11),
),
'use_for_level_below' => array(
'label' => $this->T_('Use for registered'),
'defaultvalue' => ($Settings->get('newusers_level') + 1), // the default level for new users does not allow them to bypass the captcha
'note' => $this->T_('Use this plugin for registered users, if their level is below this.'),
'type' => 'integer',
'size' => 3,
'valid_range' => array( 'min'=>0, 'max'=>11),
),
array( 'layout' => 'end_fieldset' ),
array( 'layout' => 'separator' ),
'post_process_cmd' => array(
'label' => $this->T_('Post-process'),
'defaultvalue' => '',
'note' => $this->T_('A command to post-process the image.'),
'size' => 50,
'type' => 'textarea',
),
);
}
/**
* We want a table to store our Captcha data (private key, timestamp, ..).
*
* @return array
*/
function GetDbLayout()
{
return array(
'CREATE TABLE '.$this->get_sql_table('data').' (
cpt_public VARCHAR( 32 ) NOT NULL,
cpt_private VARCHAR( 50 ) NOT NULL,
cpt_sess_ID INT UNSIGNED NOT NULL,
cpt_timestamp TIMESTAMP NOT NULL,
cpt_invalid TINYINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY( cpt_public ),
KEY cpt_timestamp( cpt_timestamp )
)',
// Holds keys for whitelisted trackback URLs:
'CREATE TABLE '.$this->get_sql_table('trackbacks_wl').' (
tbwl_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
tbwl_item_ID INT UNSIGNED NOT NULL,
tbwl_key VARCHAR( 32 ) NOT NULL,
tbwl_timestamp TIMESTAMP NOT NULL,
PRIMARY KEY( tbwl_ID )
)',
);
}
/**
* We require b2evo 1.9.x.
*/
function GetDependencies()
{
return array( 'requires' => array('app_min' => '1.9.0') );
}
/**
* Gets called, when the Plugins API detects that we've been updated (version has changed).
* @return boolean
*/
function PluginVersionChanged( & $params )
{
if( version_compare( $params['old_version'], '0.1.2-dev', '<' ) )
{ // Delete old-format data:
global $DB;
$DB->query( 'DELETE FROM '.$this->get_sql_table('data') );
}
return true;
}
/**
* We have one htsrv method to display the captcha image.
*
* @return array
*/
function GetHtsrvMethods()
{
return array( 'display_captcha', 'test_page', 'test_page_img' );
}
/**
* Check GD requirements and fonts path.
*/
function BeforeEnable()
{
if( $error = $this->validate_gd_requirements() )
{
return $error;
}
if( $error = $this->load_fonts() )
{
return $error;
}
return true;
}
/**
* Check various settings.
*/
function PluginSettingsValidateSet( & $params )
{
$error = '';
if( $params['name'] == 'TTF_folder' )
{ // check new path
$params['value'] = trailing_slash($params['value']);
$error = $this->load_fonts( $params['value'] );
}
// TODO: min-max ordering, ...
// TODO: post-process
if( $error )
{
return $error;
}
}
/**
* We generate and save a random salt to use for testing.
*/
function AfterInstall()
{
$this->Settings->set( 'public_key_salt', md5( mt_rand() ) );
$this->Settings->dbupdate();
}
/**
* Validate the given private key against our stored one.
*
* This event is provided for other plugins and gets used internally
* for other events we're hooking into.
*
* @param array Associative list of parameters.
* - 'validate_error': gets set, in case of error (by reference)
* - 'prefix': key/prefix to use for the form params (string, OPTIONALLY!)
*
* @return boolean|NULL
*/
function CaptchaValidated( & $params )
{
global $DB, $localtimenow, $Session;
$prefix = isset($params['prefix']) ? $params['prefix'] : 'captcha_img_'.$this->ID;
$this->posted_public = param( $prefix.'_key', 'string', '', true );
if( empty($this->posted_public) )
{
$this->debug_log( 'CaptchaValidated: $posted_public is empty!' );
$params['validate_error'] = $this->T_('You do not seem to come from the intended page!');
return false;
}
$this->posted_private = param( $prefix.'_private', 'string', '', true );
$saved_private = $DB->get_var( '
SELECT cpt_private FROM '.$this->get_sql_table('data').'
WHERE cpt_public = '.$DB->quote($this->posted_public).'
AND cpt_sess_ID = '.$Session->ID.'
AND UNIX_TIMESTAMP(cpt_timestamp) > '.( $localtimenow - $this->Settings->get('timeout_key')*60 ) );
if( empty($saved_private) )
{
$this->debug_log( 'No private key found!' );
$params['validate_error'] = sprintf( $this->T_('No stored private key has been found. You probably do not have cookies enabled or the timeout of %d minutes has expired.'), $this->Settings->get('timeout_key')*60 );
return false;
}
if( $this->Settings->get('case_sensitive') )
{
$posted_private = $this->posted_private;
}
else
{ // case insensitive:
$posted_private = strtoupper( $this->posted_private );
$saved_private = strtoupper( $saved_private );
}
if( $posted_private != $saved_private )
{
$this->debug_log( 'Posted ('.$posted_private.') and saved ('.$saved_private.') private key do not match!' );
$params['validate_error'] = $this->T_('The entered code does not match the expected one.');
$DB->query( '
UPDATE '.$this->get_sql_table('data').'
SET cpt_invalid = cpt_invalid + 1
WHERE cpt_public = '.$DB->quote($this->posted_public) );
return false;
}
// NOTE: the captcha data gets deleted in CaptchaValidatedCleanup()!
return true;
}
/**
* Cleanup used captcha data.
*
* @param array Associative list of parameters.
* - 'prefix': key/prefix to use for the form params (string, OPTIONALLY)
*/
function CaptchaValidatedCleanup( & $params )
{
global $DB, $Session;
$prefix = isset($params['prefix']) ? $params['prefix'] : 'captcha_img_'.$this->ID;
$posted_public = param( $prefix.'_key', 'string', '', true );
$DB->query( '
DELETE FROM '.$this->get_sql_table('data').'
WHERE cpt_public = '.$DB->quote($posted_public).'
AND cpt_sess_ID = '.$Session->ID );
}
/**
* When a comment form gets displayed, we inject our captcha and an input field to
* enter the private key (displayed in the image).
*
* The private key gets saved into the user's Session.
*
* @param array Associative array of parameters
* - 'Form': the form where payload should get added (by reference, OPTIONALLY!)
* - 'form_use_fieldset':
* - 'prefix': key/prefix to use for the form params (string, OPTIONALLY!)
* @return boolean|NULL true, if displayed; false, if error; NULL if it does not apply
*/
function CaptchaPayload( & $params )
{
global $DB, $Session, $localtimenow;
if( $this->load_fonts() )
{ // Error: no fonts available, disable the Plugin
$this->set_status( 'needs_config' );
return false;
}
$prefix = isset($params['prefix']) ? $params['prefix'] : 'captcha_img_'.$this->ID;
$this->private_key = $this->generate_private_key();
$this->public_key = md5( mt_rand() );
while( $DB->get_var( 'SELECT COUNT(*) FROM '.$this->get_sql_table('data').' WHERE cpt_public = "'.$this->public_key.'"' ) )
{ // public key is PK in the table, so make sure, it does not exist yet..
$this->public_key = md5( mt_rand() );
}
// TODO: here's a minor timing issue, which _may_ resolve in a SQL error below (duplicate KEY)
// Use MySQL's RAND() function for the public key ("insert into foo select MD5(RAND()*100000000") and retry on duplicate key!?
// Save the private and public key to DB
$DB->query( 'INSERT INTO '.$this->get_sql_table('data').'
( cpt_public, cpt_private, cpt_sess_ID, cpt_timestamp ) VALUES
( '.$DB->quote( $this->public_key ).', '.$DB->quote( $this->private_key ).', '.$Session->ID.', FROM_UNIXTIME('.$localtimenow.') )' );
$this->debug_log( 'Private key is: ('.$this->private_key.')' );
$this->debug_log( 'Public key is: (DB ID '.$this->public_key.')' );
if( ! isset( $params['Form'] ) )
{ // there's no Form where we add to, but we create our own form:
$Form = new Form( regenerate_url() );
$Form->begin_form();
// Include previous $_POST and $_GET params (to come to the same page again):
$Form->hiddens_by_key( array_merge($_GET, $_POST),
/* exclude, because used as hidden or input field: */
array($prefix.'_private', $prefix.'_key') );
}
else
{
$Form = & $params['Form'];
if( ! isset($params['form_use_fieldset']) || $params['form_use_fieldset'] )
{
$Form->begin_fieldset();
}
// Remove any hidden fields which we use ourself as hidden (especially *_key, which is an INPUT):
// (This is required in the login form for example)
foreach( $Form->hiddens as $k => $v )
{
if( strpos( $v, 'name="'.$prefix.'_' ) )
{ // exclude own hidden field (added by Form::hiddens_by_key())
unset($Form->hiddens[$k]);
}
}
}
$Form->hidden( $prefix.'_key', $this->public_key );
$img_src = $this->get_htsrv_url('display_captcha', array('pubkey'=>$this->public_key));
$captcha_img = '<img src="'.$img_src.'" alt="'.$this->T_('This is a captcha-picture. It is used to prevent mass-access by robots.').'" id="'.$prefix.'_'.$this->public_key.'"';
if( ! $this->post_process_alters_dimensions() )
{
list($width, $height) = $this->get_image_dimensions($this->private_key);
$captcha_img .= ' width="'.$width.'" height="'.$height.'"';
}
$captcha_img .= ' />';
// Javascript link to reload the image:
$captcha_img .= '<script type="text/javascript">
//<![CDATA[
document.write( \' <a href="#" onclick="document.getElementById(\\\''.$prefix.'_'.$this->public_key.'\\\').src = \\\''.$img_src.'&reload=\\\'+(new Date()).getTime(); return false;">'
.get_icon('reload', 'imgtag', array('alt'=>$this->T_('Reload'), 'title'=>$this->T_('Reload image!'))).'<\/a>\' );
//]]>
</script>
';
$captcha_img .= "<br />\n";
$note = $this->T_( 'Please enter the characters from the image above.' )
.' '.( $this->Settings->get('case_sensitive') ? '('.$this->T_('case sensitive').')' : '('.$this->T_('case insensitive').')' );
global $app_version;
if( version_compare($app_version, '2.0-dev', '>=') )
{ // b2evo 2.0 or above (API changed):
$Form->text_input( $prefix.'_private', '', 7, $this->T_('Captcha'), $note, array( 'maxlength' => '', 'id' => $prefix.'_'.$this->public_key.'_private', 'input_prefix' => $captcha_img ) );
}
else
{
$Form->text_input( $prefix.'_private', '', 7, $this->T_('Captcha'), array( 'note' => $note, 'maxlength' => '', 'id' => $prefix.'_'.$this->public_key.'_private', 'input_prefix' => $captcha_img ) );
}
if( ! isset($params['Form']) )
{ // there's no Form where we add to, but our own form:
$Form->end_form( array( array( 'submit', 'submit', $this->T_('Validate me'), 'ActionButton' ) ) );
}
else
{
if( ! isset($params['form_use_fieldset']) || $params['form_use_fieldset'] )
{
$Form->end_fieldset();
}
}
return true;
}
/**
* We display our captcha with comment forms.
*/
function DisplayCommentFormFieldset( & $params )
{
if( ! $this->does_apply( $params ) )
{
return;
}
$prefix = 'captcha_img_'.$this->ID;
$params['prefix'] = & $prefix;
if( $v = $this->session_get('validated_in_preview') )
{ // Captcha has been validated in preview: insert just the hidden fields:
$this->session_delete('validated_in_preview');
$this->debug_log('DisplayCommentFormFieldset: validated in preview');
$params['Form']->hidden($prefix.'_key', $v['posted_public']);
$params['Form']->hidden($prefix.'_private', $v['posted_private']);
return;
}
$this->CaptchaPayload( $params );
}
/**
* Validate the given private key against our stored one.
*
* In case of error we add a message of category 'error' which prevents the comment from
* being posted.
*/
function BeforeCommentFormInsert( & $params )
{
if( ! $this->does_apply($params) )
{
return;
}
$prefix = 'captcha_img_'.$this->ID;
$params['prefix'] = & $prefix;
if( ! empty($params['is_preview'])
|| ( isset($params['action']) && $params['action'] == 'preview' ) /* b2evo 1.10+ */ )
{
/*
* If this is a comment preview, check if the captcha has been validated and remember it then, so
* that {@link DisplayCommentFormFieldset()} can insert it just as hidden fields.
*/
if( $this->CaptchaValidated($params) )
{
$this->debug_log( 'CommentFormSent: validated in preview' );
$this->session_set('validated_in_preview', array(
'posted_public' => $this->posted_public,
'posted_private' => $this->posted_private,
), 30 /* 30 seconds */);
}
return;
}
if( $this->CaptchaValidated($params) === false )
{
global $Request;
$validate_error = $params['validate_error'];
if( isset($Request) )
{
$Request->param_error( $prefix.'_private', sprintf( /* TRANS: %s gets replaced by the reason/hint */ $this->T_('The captcha code was invalid: %s'), $validate_error ) );
}
else
{ // b2evo 2.0:
param_error( $prefix.'_private', sprintf( /* TRANS: %s gets replaced by the reason/hint */ $this->T_('The captcha code was invalid: %s'), $validate_error ) );
}
}
}
/**
* Cleanup after a comment has been inserted.
*/
function AfterCommentFormInsert( & $params )
{
$this->CaptchaValidatedCleanup();
}
/**
* We display our captcha with the register form.
*/
function DisplayRegisterFormFieldset( & $params )
{
if( ! $this->does_apply( $params ) )
{
return;
}
$this->CaptchaPayload( $params );
}
/**
* Validate the given private key against our stored one.
*
* In case of error we add a message of category 'error' which prevents the
* user from being registered.
*/
function RegisterFormSent( & $params )
{
$this->BeforeCommentFormInsert( $params ); // we do the same as when validating comment forms
}
/**
* Cleanup captcha data.
*/
function AfterUserRegistration( & $params )
{
$this->CaptchaValidatedCleanup();
}
/**
* We display our captcha with the message form.
*/
function DisplayMessageFormFieldset( & $params )
{
if( ! $this->does_apply( $params ) )
{
return;
}
$this->CaptchaPayload( $params );
}
/**
* Validate the given private key against our stored one.
*
* In case of error we add a message of category 'error' which prevents the
* user from being registered.
*/
function MessageFormSent( & $params )
{
$this->BeforeCommentFormInsert( $params ); // we do the same as when validating comment forms
}
/**
* Cleanup.
*/
function MessageFormSentCleanup( & $params )
{
$this->CaptchaValidatedCleanup();
}
/**
* Called, if a public trackback address gets displayed: we require the user
* to solve a captcha first, before he sees a one-time URL.
*
* This gets checked in {@link captcha_img_plugin::BeforeTrackbackInsert()}.
*
* @return true|NULL NULL, if we do not protect trackback URLs
*/
function DisplayTrackbackAddr( & $params )
{
if( ! $this->Settings->get('protect_trackback_url') )
{
return;
}
if( ! $this->does_apply($params) || $this->CaptchaValidated($params) )
{ // either we do not apply or the captcha has been validated:
global $DB;
$wl_key = generate_random_key(32);
$DB->query('
INSERT INTO '.$this->get_sql_table('trackbacks_wl').'
( tbwl_key, tbwl_item_ID )
VALUES ( "'.$wl_key.'", '.$params['Item']->ID.' )' );
$url = url_add_param( $params['Item']->get_trackback_url(),
'wlkey_'.$this->ID.'='.$wl_key );
// Display URL:
echo str_replace( '%url%', $url, $params['template'] );
}
else
{
// TODO: Provide fieldset with explanation
$Form = new Form( regenerate_url() );
$Form->switch_layout('inline');
$Form->begin_form();
$params['Form'] = & $Form;
$params['form_use_fieldset'] = false;
$r = $this->CaptchaPayload($params);
$Form->button( array( 'submit', 'submit', $this->T_('Display trackback URL'), 'ActionButton' ) );
$Form->hiddens_by_key( get_memorized() );
$Form->hidden('redir', 'no'); // prevent canonical redirect
$Form->end_form();
}
return true;
}
/**
* Check if the URL is a generated one-time address, from {@link captcha_img_plugin::DisplayTrackbackAddr()}.
*
* We add a message of category "error", in case the URL is invalid and delete
* the one-time key from our DB table in case of success.
*
* @return NULL
*/
function BeforeTrackbackInsert( & $params )
{
global $DB;
if( ! $this->Settings->get('protect_trackback_url') )
{
return;
}
$wl_key = param( 'wlkey_'.$this->ID, 'string', '', true );
if( strlen($wl_key) != 32 )
{
$this->msg( $this->T_('Invalid trackback URL!'), 'error' );
}
elseif( ! $DB->get_var( '
SELECT COUNT(*) FROM '.$this->get_sql_table('trackbacks_wl').'
WHERE tbwl_key = '.$DB->quote($wl_key).'
AND tbwl_item_ID = '.$params['Comment']->Item->ID ) )
{
$this->msg( $this->T_('Invalid key in trackback URL!'), 'error' );
}
else
{ // OK. Delete whitelist key:
$DB->query( '
DELETE FROM '.$this->get_sql_table('trackbacks_wl').'
WHERE tbwl_key = '.$DB->quote($wl_key).'
AND tbwl_item_ID = '.$params['Comment']->Item->ID );
}
}
/**
* Display link to test the Plugin.
*/
function PluginSettingsEditDisplayAfter( & $params )
{
global $current_User;
echo '<div class="input"><a target="b2evo_plug'.$this->ID.'_test" href="'.$this->get_htsrv_url( 'test_page',
array( 'test_captcha_valid' => md5($this->Settings->get('public_key_salt').$current_User->ID) ) ).'">'
.$this->T_('Create test image... (please save any changes before)').'</a></div>';
}
/**
* Delete obsolete captcha data from DB table.
*
* Gets called as a shutdown function.
*
* @todo Optimize table from time to time
* @see PluginInit()
*/
function purge_obsolete_db_data()
{
global $DB, $localtimenow;
// Trackback whitelist keys:
$DB->query( '
DELETE FROM '.$this->get_sql_table('trackbacks_wl').'
WHERE UNIX_TIMESTAMP(tbwl_timestamp) < '.( $localtimenow - $this->Settings->get('timeout_key')*60 ) );
// Captcha data:
$DB->query( '
DELETE FROM '.$this->get_sql_table('data').'
WHERE UNIX_TIMESTAMP(cpt_timestamp) < '.( $localtimenow - $this->Settings->get('timeout_key')*60 ) );
}
/**
* A htsrv method to display the captcha image.
*
* This gets included through {@link get_htsrv_url()} in {@link CaptchaPayload()}.
*
* The private key to display in the image gets retrieved from the user's Session.
*
* @param array
* 'pubkey': display the captcha for the given public key (where the private part is stored in the user's session)
*/
function htsrv_display_captcha( $params )
{
global $DB, $Session;
if( ! isset($params['pubkey']) )
{
$this->debug_log( 'Public key not provided!' );
return false;
}
$this->debug_log( 'Public key: '.$params['pubkey'] );
$private_key = $DB->get_var( '
SELECT cpt_private FROM '.$this->get_sql_table('data').'
WHERE cpt_public = '.$DB->quote( $params['pubkey'] ).'
AND cpt_sess_ID = '.$Session->ID );
if( empty($private_key) )
{
$this->debug_log( 'Private key is empty!' );
return false;
}
$image = $this->get_captcha_img( $private_key );
if( ! $image )
{
$this->debug_log( 'get_captcha_img() returned '.var_export($image, true) );
return false;
}
header( 'Content-Type: image/jpeg' );
header( 'Content-Length: '.strlen($image) );
echo $image;
die;
}
/**
* Output the HTML page in test mode.
*
* This displays a test image and the Debuglog of it's creation.
*
* @param array
* 'test_captcha_valid': used to check if the user is allowed to test the captcha plugin
* 'test_private_key': private key to use for testing (this is passed, as sometimes a browser might request the image twice)
* 'test_output_ID': if given, it's used as ID to store Debuglog output into the user's session
*/
function htsrv_test_page( & $params )
{
global $current_User;
// Display all errors:
$old_error_reporting = error_reporting(E_ALL);
$old_display_errors = ini_set('display_errors', 'on');
$output_ID = mt_rand();
if( ! isset($current_User->ID) // no user logged in
|| empty( $params['test_captcha_valid'] ) || $params['test_captcha_valid'] != md5($this->Settings->get('public_key_salt').$current_User->ID) )
{
return false;
}
// create Debuglog anew, as it will be of class Log_noop if !$debug - do not assign by reference as it fails to overwrite it and is deprecated in PHP5 anyway
global $Debuglog;
$Debuglog = new Log( 'note' );
$this->debug_log( 'params: '.var_export($params, true) );
$private_key = $this->generate_private_key();
$image = $this->get_captcha_img( $private_key );
$image = base64_encode($image); // workaround, because sess_data is not binary (BLOB before b2evo 1.10)
$this->session_set( 'test_img_'.$output_ID, $image, 30, true ); // timeout: 30s and save immediately
unset($image);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test: <?php echo $this->classname ?>, ID <?php echo $this->ID ?></title>
</head>
<body>
<div style="text-align:center">
<p><?php echo $this->T_('A generated image should show up below. The image only gets displayed once - use the test link again for a new try.') ?></p>
<?php
// Callback to get the image (saved into session above):
echo '<img src="'.$this->get_htsrv_url( 'test_page_img', array(
'test_captcha_valid' => $params['test_captcha_valid'],
'test_output_ID' => $output_ID ) )
.'" alt="Captcha test image" style="border:2px solid black; padding:10px;" ';
if( ! $this->post_process_alters_dimensions() )
{
list($width, $height) = $this->get_image_dimensions($private_key);
echo ' width="'.$width.'" height="'.$height.'"';
}
echo ' />';
?>
</div>
<div class="debug">
<h2>Debuglog for image creation</h2>
<?php
$Debuglog->display(
array( 'all' => array( 'string' => '<h4 id="debug_info_cat_%s">%s:</h4>', 'template' => false ) ),
'', true, array( $this->classname.'_'.$this->ID, 'all' ) )
?>
</div>
<?php
debug_info();
?>
</body>
</html>
<?php
error_reporting($old_error_reporting);
ini_set('display_errors', $old_display_errors);
}
/**
* (External) helper for {@link htsrv_test_page()}.
*
* Display the captcha image in test mode. This gets requested through a HTTP callback (out of an IMG html tag).
*
* @param array Passed from {@link htsrv_test_page()}:
* 'test_captcha_valid': key to validate request
* 'test_output_ID': output ID to get the image out of session data
*/
function htsrv_test_page_img( $params )
{
global $Session, $current_User;
// Check perms:
if( empty($params['test_output_ID']) || empty( $params['test_captcha_valid'] ) )
{
debug_die( 'Invalid request!' );
}
if( empty($current_User)
|| $params['test_captcha_valid'] != md5($this->Settings->get('public_key_salt').$current_User->ID) )
{