summaryrefslogtreecommitdiff
path: root/framework
diff options
context:
space:
mode:
authorxue <>2007-08-28 22:05:18 +0000
committerxue <>2007-08-28 22:05:18 +0000
commit669beed5392d22421d03b2a2d1bf12f5f0db9012 (patch)
tree948d01ac16e86c827ae803e90554c33bba832f85 /framework
parentff402bd8de1edd97bb06d30d7600212b5fc22f16 (diff)
added TCaptcha, TCaptchaValidator.
Diffstat (limited to 'framework')
-rw-r--r--framework/Web/Javascripts/source/prado/validator/validation3.js67
-rw-r--r--framework/Web/UI/WebControls/TCaptcha.php241
-rw-r--r--framework/Web/UI/WebControls/TCaptchaValidator.php117
-rw-r--r--framework/Web/UI/WebControls/assets/captcha.php35
4 files changed, 460 insertions, 0 deletions
diff --git a/framework/Web/Javascripts/source/prado/validator/validation3.js b/framework/Web/Javascripts/source/prado/validator/validation3.js
index 046ac817..3d43a5f3 100644
--- a/framework/Web/Javascripts/source/prado/validator/validation3.js
+++ b/framework/Web/Javascripts/source/prado/validator/validation3.js
@@ -1377,3 +1377,70 @@ Prado.WebUI.TDataTypeValidator = Class.extend(Prado.WebUI.TBaseValidator,
return this.convert(this.options.DataType, value) != null;
}
});
+
+/**
+ * TCaptchaValidator verifies if the input data is the same as the token shown in the associated CAPTCHA contorl.
+ */
+Prado.WebUI.TCaptchaValidator = Class.extend(Prado.WebUI.TBaseValidator,
+{
+ /**
+ * @return boolean true if the input value is not empty nor equal to the initial value.
+ */
+ evaluateIsValid : function()
+ {
+ var a = this.getValidationValue();
+ if (a.length <= 0)
+ return false;
+ var b = this.options.TokenHash;
+ if (this.options.CaseSensitive)
+ return(this.crc32(a) == b);
+ else
+ return(this.crc32(a.toUpperCase()) == b);
+ },
+
+ crc32 : function(str)
+ {
+ function Utf8Encode(string)
+ {
+ string = string.replace(/\r\n/g,"\n");
+ var utftext = "";
+
+ for (var n = 0; n < string.length; n++)
+ {
+ var c = string.charCodeAt(n);
+
+ if (c < 128) {
+ utftext += String.fromCharCode(c);
+ }
+ else if((c > 127) && (c < 2048)) {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+
+ }
+
+ return utftext;
+ };
+
+ str = Utf8Encode(str);
+
+ var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
+ var crc = 0;
+ var x = 0;
+ var y = 0;
+
+ crc = crc ^ (-1);
+ for( var i = 0, iTop = str.length; i < iTop; i++ )
+ {
+ y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
+ x = "0x" + table.substr( y * 9, 8 );
+ crc = ( crc >>> 8 ) ^ x;
+ }
+ return crc ^ (-1);
+ }
+});
diff --git a/framework/Web/UI/WebControls/TCaptcha.php b/framework/Web/UI/WebControls/TCaptcha.php
new file mode 100644
index 00000000..a9467333
--- /dev/null
+++ b/framework/Web/UI/WebControls/TCaptcha.php
@@ -0,0 +1,241 @@
+<?php
+/**
+ * TCaptcha class file
+ *
+ * @author Qiang Xue <qiang.xue@gmail.com>
+ * @link http://www.pradosoft.com/
+ * @copyright Copyright &copy; 2005-2007 PradoSoft
+ * @license http://www.pradosoft.com/license/
+ * @version $Id$
+ * @package System.Web.UI.WebControls
+ */
+
+Prado::using('System.Web.UI.WebControls.TImage');
+
+/**
+ * TCaptcha class.
+ *
+ * TCaptcha displays a CAPTCHA (a token displayed as an image) that can be used
+ * to determine if the input is entered by a real user instead of some program.
+ *
+ * The token (a string consisting of alphanumeric characters) displayed is automatically
+ * generated and can be configured in several ways. To specify the length of characters
+ * in the token, set {@link setTokenLength TokenLength}. To use case-insensitive
+ * comparison and generate upper-case-only token, set {@link setCaseSensitive CaseSensitive}
+ * to false.
+ *
+ * Upon postback, user input can be validated by calling {@link validate()}.
+ * The {@link TCaptchaValidator} control can also be used to do validation, which provides
+ * client-side validation besides the server-side validation. By default, the token will
+ * remain the same during multiple postbacks. A new one can be generated by calling
+ * {@link regenerateToken()} manually.
+ *
+ * @author Qiang Xue <qiang.xue@gmail.com>
+ * @version $Id$
+ * @package System.Web.UI.WebControls
+ * @since 3.1.1
+ */
+class TCaptcha extends TImage
+{
+ const MIN_TOKEN_LENGTH=2;
+ const MAX_TOKEN_LENGTH=40;
+
+ /**
+ * @return integer the length of the token. Defaults to 6.
+ */
+ public function getTokenLength()
+ {
+ return $this->getViewState('TokenLength',6);
+ }
+
+ /**
+ * @param integer the length of the token. It must be between 2 and 40.
+ */
+ public function setTokenLength($value)
+ {
+ $length=TPropertyValue::ensureInteger($value);
+ if($length>=self::MIN_TOKEN_LENGTH && $length<=self::MAX_TOKEN_LENGTH)
+ $this->setViewState('TokenLength',$length,6);
+ else
+ throw new TConfigurationException('captcha_TokenLength_invalid',self::MIN_TOKEN_LENGTH,self::MAX_TOKEN_LENGTH);
+ }
+
+ /**
+ * @return boolean whether the token should be treated as case-sensitive. Defaults to true.
+ */
+ public function getCaseSensitive()
+ {
+ return $this->getViewState('CaseSensitive',true);
+ }
+
+ /**
+ * @param boolean whether the token should be treated as case-sensitive. If false, only upper-case letters will appear in the token.
+ */
+ public function setCaseSensitive($value)
+ {
+ $this->setViewState('CaseSensitive',TPropertyValue::ensureBoolean($value),true);
+ }
+
+ /**
+ * @return string the public key used for generating the token. A random one will be generated if this is not set.
+ */
+ public function getPublicKey()
+ {
+ if(($publicKey=$this->getViewState('PublicKey',''))==='')
+ {
+ $publicKey=$this->generateRandomKey();
+ $this->setPublicKey($publicKey);
+ }
+ return $publicKey;
+ }
+
+ /**
+ * @param string the public key used for generating the token. A random one will be generated if this is not set.
+ */
+ public function setPublicKey($value)
+ {
+ $this->setViewState('PublicKey',$value,'');
+ }
+
+ /**
+ * @return string the token that will be displayed
+ */
+ public function getToken()
+ {
+ return $this->generateToken($this->getPublicKey(),$this->getPrivateKey(),$this->getTokenLength(),$this->getCaseSensitive()); return $this->generateToken();
+ }
+
+ /**
+ * @return string the private key used for generating the token. This is randomly generated and kept in a file for persistency.
+ */
+ public function getPrivateKey()
+ {
+ $fileName=$this->generatePrivateKeyFile();
+ $content=file_get_contents($fileName);
+ $matches=array();
+ if(preg_match("/privateKey='(.*?)'/ms",$content,$matches)>0)
+ return $matches[1];
+ else
+ throw new TConfigurationException('captcha_private_unknown');
+ }
+
+ /**
+ * Validates a user input with the token.
+ * @param string user input
+ * @return boolean if the user input is not the same as the token.
+ */
+ public function validate($input)
+ {
+ return $this->getToken()===($this->getCaseSensitive()?$input:strtoupper($input));
+ }
+
+ /**
+ * Regenerates the token to be displayed.
+ * By default, a token, once generated, will remain the same during the following page postbacks.
+ * Calling this method will generate a new token.
+ */
+ public function regenerateToken()
+ {
+ $this->clearViewState('RegenerateToken');
+ $this->setPublicKey('');
+ }
+
+ /**
+ * Configures the image URL that shows the token.
+ * @param mixed event parameter
+ */
+ public function onPreRender($param)
+ {
+ parent::onPreRender($param);
+ if($this->getViewState('RegenerateToken',true))
+ {
+ $this->getToken(); // call to ensure the token is regenerated
+ $url=$this->getApplication()->getAssetManager()->publishFilePath($this->getCaptchaScriptFile());
+ $url.='?pk='.urlencode($this->getPublicKey());
+ $url.='&amp;length='.$this->getTokenLength();
+ $url.='&amp;case='.($this->getCaseSensitive()?'1':'0');
+ $this->setImageUrl($url);
+ $this->generatePrivateKeyFile();
+
+ $this->setViewState('RegenerateToken',false);
+ }
+ }
+
+ /**
+ * @return string the file path of the PHP script generating the token image
+ */
+ protected function getCaptchaScriptFile()
+ {
+ return dirname(__FILE__).DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'captcha.php';
+ }
+
+ /**
+ * Generates a file with a randomly generated private key.
+ * @return string the path of the file keeping the private key
+ */
+ protected function generatePrivateKeyFile()
+ {
+ $captchaScript=$this->getCaptchaScriptFile();
+ $path=dirname($this->getApplication()->getAssetManager()->getPublishedPath($captchaScript));
+ $fileName=$path.DIRECTORY_SEPARATOR.'captcha_key.php';
+ if(!is_file($fileName))
+ {
+ @mkdir($path);
+ $key=$this->generateRandomKey();
+ $content="<?php
+\$privateKey='$key';
+?>";
+ file_put_contents($fileName,$content);
+ }
+ return $fileName;
+ }
+
+ /**
+ * @return string a randomly generated key
+ */
+ protected function generateRandomKey()
+ {
+ return md5(rand().rand().rand().rand());
+ }
+
+ /**
+ * Generates the token.
+ * @param string public key
+ * @param string private key
+ * @param integer the length of the token
+ * @param boolean whether the token is case sensitive
+ * @return string the token generated.
+ */
+ protected function generateToken($publicKey,$privateKey,$tokenLength,$caseSensitive)
+ {
+ $token=substr($this->hash2string(md5($publicKey.$privateKey)).$this->hash2string(md5($privateKey.$publicKey)),0,$tokenLength);
+ return $caseSensitive?$token:strtoupper($token);
+ }
+
+ /**
+ * Converts a hash string into a string with characters consisting of alphanumeric characters.
+ * @param string the hexadecimal representation of the hash string
+ * @param string the alphabet used to represent the converted string. If empty, it means 0-9, a-z and A-Z.
+ * @return string the converted string
+ */
+ protected function hash2string($hex,$alphabet='')
+ {
+ if(strlen($alphabet)<2)
+ $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ $hexLength=strlen($hex);
+ $base=strlen($alphabet);
+ $result='';
+ for($i=0;$i<$hexLength;$i+=6)
+ {
+ $number=hexdec(substr($hex,$i,6));
+ while($number)
+ {
+ $result.=$alphabet[$number%$base];
+ $number=floor($number/$base);
+ }
+ }
+ return $result;
+ }
+}
+
+?> \ No newline at end of file
diff --git a/framework/Web/UI/WebControls/TCaptchaValidator.php b/framework/Web/UI/WebControls/TCaptchaValidator.php
new file mode 100644
index 00000000..4385bbfe
--- /dev/null
+++ b/framework/Web/UI/WebControls/TCaptchaValidator.php
@@ -0,0 +1,117 @@
+<?php
+/**
+ * TCaptchaValidator class file
+ *
+ * @author Qiang Xue <qiang.xue@gmail.com>
+ * @link http://www.pradosoft.com/
+ * @copyright Copyright &copy; 2005-2007 PradoSoft
+ * @license http://www.pradosoft.com/license/
+ * @version $Id$
+ * @package System.Web.UI.WebControls
+ */
+
+Prado::using('System.Web.UI.WebControls.TBaseValidator');
+Prado::using('System.Web.UI.WebControls.TCaptcha');
+
+/**
+ * TCaptchaValidator class
+ *
+ * TCaptchaValidator validates user input against a CAPTCHA represented by
+ * a {@link TCaptcha} control. The input control fails validation if its value
+ * is not the same as the token displayed in CAPTCHA. Note, if the user does
+ * not enter any thing, it is still considered as failing the validation.
+ *
+ * To use TCaptchaValidator, specify the {@link setControlToValidate ControlToValidate}
+ * to be the ID path of the input control (usually a {@link TTextBox} control}.
+ * Also specify the {@link setCaptchaControl CaptchaControl} to be the ID path of
+ * the CAPTCHA control that the user input should be compared with.
+ *
+ * @author Qiang Xue <qiang.xue@gmail.com>
+ * @version $Id$
+ * @package System.Web.UI.WebControls
+ * @since 3.1.1
+ */
+class TCaptchaValidator extends TBaseValidator
+{
+ /**
+ * Gets the name of the javascript class responsible for performing validation for this control.
+ * This method overrides the parent implementation.
+ * @return string the javascript class name
+ */
+ protected function getClientClassName()
+ {
+ return 'Prado.WebUI.TCaptchaValidator';
+ }
+
+ /**
+ * @return string the ID path of the CAPTCHA control to validate
+ */
+ public function getCaptchaControl()
+ {
+ return $this->getViewState('CaptchaControl','');
+ }
+
+ /**
+ * Sets the ID path of the CAPTCHA control to validate.
+ * The ID path is the dot-connected IDs of the controls reaching from
+ * the validator's naming container to the target control.
+ * @param string the ID path
+ */
+ public function setCaptchaControl($value)
+ {
+ $this->setViewState('CaptchaControl',TPropertyValue::ensureString($value),'');
+ }
+
+ /**
+ * This method overrides the parent's implementation.
+ * The validation succeeds if the input control has the same value
+ * as the one displayed in the corresponding CAPTCHA control.
+ *
+ * @return boolean whether the validation succeeds
+ */
+ protected function evaluateIsValid()
+ {
+ $value=$this->getValidationValue($this->getValidationTarget());
+ $control=$this->findCaptchaControl();
+ return $control->validate(trim($value));
+ }
+
+ /**
+ * @return TCaptchaControl the CAPTCHA control to be validated against
+ * @throws TConfigurationException if the CAPTCHA cannot be found according to {@link setCaptchaControl CaptchaControl}
+ */
+ protected function findCaptchaControl()
+ {
+ if(($id=$this->getCaptchaControl())==='')
+ throw new TConfigurationException('captchavalidator_captchacontrol_required');
+ else if(($control=$this->findControl($id))===null)
+ throw new TConfigurationException('captchavalidator_captchacontrol_inexistent',$id);
+ else if(!($control instanceof TCaptcha))
+ throw new TConfigurationException('captchavalidator_captchacontrol_invalid',$id);
+ else
+ return $control;
+ }
+
+ /**
+ * Returns an array of javascript validator options.
+ * @return array javascript validator options.
+ */
+ protected function getClientScriptOptions()
+ {
+ $options=parent::getClientScriptOptions();
+ $control=$this->findCaptchaControl();
+ if($control->getCaseSensitive())
+ {
+ $options['TokenHash']=crc32($control->getToken());
+ $options['CaseSensitive']=true;
+ }
+ else
+ {
+ $options['TokenHash']=crc32(strtoupper($control->getToken()));
+ $options['CaseSensitive']=false;
+ }
+ return $options;
+ }
+}
+
+?> \ No newline at end of file
diff --git a/framework/Web/UI/WebControls/assets/captcha.php b/framework/Web/UI/WebControls/assets/captcha.php
new file mode 100644
index 00000000..aa3fdcc0
--- /dev/null
+++ b/framework/Web/UI/WebControls/assets/captcha.php
@@ -0,0 +1,35 @@
+<?php
+
+require_once(dirname(__FILE__).'/captcha_key.php');
+
+if(isset($_GET['pk']))
+ echo $_GET['pk'].$privateKey;
+else
+ echo $privateKey;
+
+function generateToken($publicKey,$privateKey,$tokenLength,$caseSensitive)
+{
+ $token=substr(hash2string(md5($publicKey.$privateKey)).hash2string(md5($privateKey.$publicKey)),0,$tokenLength);
+ return $caseSensitive?$token:strtoupper($token);
+}
+
+function hash2string($hex,$alphabet='')
+{
+ if(strlen($alphabet)<2)
+ $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ $hexLength=strlen($hex);
+ $base=strlen($alphabet);
+ $result='';
+ for($i=0;$i<$hexLength;$i+=6)
+ {
+ $number=hexdec(substr($hex,$i,6));
+ while($number)
+ {
+ $result.=$alphabet[$number%$base];
+ $number=floor($number/$base);
+ }
+ }
+ return $result;
+}
+
+?> \ No newline at end of file