diff options
author | ctrlaltca@gmail.com <> | 2011-10-02 21:13:53 +0000 |
---|---|---|
committer | ctrlaltca@gmail.com <> | 2011-10-02 21:13:53 +0000 |
commit | 72dd599070900fabb1e1501a7b39067703acec35 (patch) | |
tree | 9e38fddbdea9daddf19038b8fa4b0d2bddb142b5 | |
parent | 63e50106808370c249b48796ab5d08429f2c9550 (diff) |
Added TReCaptcha control (ticket #345) and added a notice about the lack of security of TCaptcha (ticket #344)
-rw-r--r-- | .gitattributes | 4 | ||||
-rw-r--r-- | framework/3rdParty/ReCaptcha/LICENSE | 22 | ||||
-rw-r--r-- | framework/3rdParty/ReCaptcha/recaptchalib.php | 277 | ||||
-rw-r--r-- | framework/3rdParty/readme.html | 7 | ||||
-rw-r--r-- | framework/Exceptions/messages/messages.txt | 9 | ||||
-rw-r--r-- | framework/Web/UI/WebControls/TCaptcha.php | 6 | ||||
-rw-r--r-- | framework/Web/UI/WebControls/TCaptchaValidator.php | 6 | ||||
-rw-r--r-- | framework/Web/UI/WebControls/TReCaptcha.php | 199 | ||||
-rw-r--r-- | framework/Web/UI/WebControls/TReCaptchaValidator.php | 72 |
9 files changed, 600 insertions, 2 deletions
diff --git a/.gitattributes b/.gitattributes index d8c68e21..d517e514 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2294,6 +2294,8 @@ framework/3rdParty/PhpShell/PHP/Shell/Options.php -text framework/3rdParty/PhpShell/README -text framework/3rdParty/PhpShell/php-shell-cmd.php -text framework/3rdParty/PhpShell/php-shell-init.php -text +framework/3rdParty/ReCaptcha/LICENSE -text +framework/3rdParty/ReCaptcha/recaptchalib.php -text framework/3rdParty/SafeHtml/HTMLSax3.php -text framework/3rdParty/SafeHtml/HTMLSax3/Decorators.php -text framework/3rdParty/SafeHtml/HTMLSax3/States.php -text @@ -2998,6 +3000,8 @@ framework/Web/UI/WebControls/TRadioButton.php -text framework/Web/UI/WebControls/TRadioButtonList.php -text framework/Web/UI/WebControls/TRangeValidator.php -text framework/Web/UI/WebControls/TRatingList.php -text +framework/Web/UI/WebControls/TReCaptcha.php -text +framework/Web/UI/WebControls/TReCaptchaValidator.php -text framework/Web/UI/WebControls/TRegularExpressionValidator.php -text framework/Web/UI/WebControls/TRepeatInfo.php -text framework/Web/UI/WebControls/TRepeater.php -text diff --git a/framework/3rdParty/ReCaptcha/LICENSE b/framework/3rdParty/ReCaptcha/LICENSE new file mode 100644 index 00000000..b612f71f --- /dev/null +++ b/framework/3rdParty/ReCaptcha/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net +AUTHORS: + Mike Crawford + Ben Maurer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/framework/3rdParty/ReCaptcha/recaptchalib.php b/framework/3rdParty/ReCaptcha/recaptchalib.php new file mode 100644 index 00000000..32c4f4d7 --- /dev/null +++ b/framework/3rdParty/ReCaptcha/recaptchalib.php @@ -0,0 +1,277 @@ +<?php +/* + * This is a PHP library that handles calling reCAPTCHA. + * - Documentation and latest version + * http://recaptcha.net/plugins/php/ + * - Get a reCAPTCHA API Key + * https://www.google.com/recaptcha/admin/create + * - Discussion group + * http://groups.google.com/group/recaptcha + * + * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net + * AUTHORS: + * Mike Crawford + * Ben Maurer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * The reCAPTCHA server URL's + */ +define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api"); +define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api"); +define("RECAPTCHA_VERIFY_SERVER", "www.google.com"); + +/** + * Encodes the given data into a query string format + * @param $data - array of string elements to be encoded + * @return string - encoded request + */ +function _recaptcha_qsencode ($data) { + $req = ""; + foreach ( $data as $key => $value ) + $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; + + // Cut the last '&' + $req=substr($req,0,strlen($req)-1); + return $req; +} + + + +/** + * Submits an HTTP POST to a reCAPTCHA server + * @param string $host + * @param string $path + * @param array $data + * @param int port + * @return array response + */ +function _recaptcha_http_post($host, $path, $data, $port = 80) { + + $req = _recaptcha_qsencode ($data); + + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; + $http_request .= "Content-Length: " . strlen($req) . "\r\n"; + $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; + $http_request .= "\r\n"; + $http_request .= $req; + + $response = ''; + if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { + die ('Could not open socket'); + } + + fwrite($fs, $http_request); + + while ( !feof($fs) ) + $response .= fgets($fs, 1160); // One TCP-IP packet + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); + + return $response; +} + + + +/** + * Gets the challenge HTML (javascript and non-javascript version). + * This is called from the browser, and the resulting reCAPTCHA HTML widget + * is embedded within the HTML form it was called from. + * @param string $pubkey A public key for reCAPTCHA + * @param string $error The error given by reCAPTCHA (optional, default is null) + * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) + + * @return string - The HTML to be embedded in the user's form. + */ +function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) +{ + if ($pubkey == null || $pubkey == '') { + die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); + } + + if ($use_ssl) { + $server = RECAPTCHA_API_SECURE_SERVER; + } else { + $server = RECAPTCHA_API_SERVER; + } + + $errorpart = ""; + if ($error) { + $errorpart = "&error=" . $error; + } + return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script> + + <noscript> + <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> + <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> + <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> + </noscript>'; +} + + + + +/** + * A ReCaptchaResponse is returned from recaptcha_check_answer() + */ +class ReCaptchaResponse { + var $is_valid; + var $error; +} + + +/** + * Calls an HTTP POST function to verify if the user's guess was correct + * @param string $privkey + * @param string $remoteip + * @param string $challenge + * @param string $response + * @param array $extra_params an array of extra variables to post to the server + * @return ReCaptchaResponse + */ +function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) +{ + if ($privkey == null || $privkey == '') { + die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); + } + + if ($remoteip == null || $remoteip == '') { + die ("For security reasons, you must pass the remote ip to reCAPTCHA"); + } + + + + //discard spam submissions + if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { + $recaptcha_response = new ReCaptchaResponse(); + $recaptcha_response->is_valid = false; + $recaptcha_response->error = 'incorrect-captcha-sol'; + return $recaptcha_response; + } + + $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", + array ( + 'privatekey' => $privkey, + 'remoteip' => $remoteip, + 'challenge' => $challenge, + 'response' => $response + ) + $extra_params + ); + + $answers = explode ("\n", $response [1]); + $recaptcha_response = new ReCaptchaResponse(); + + if (trim ($answers [0]) == 'true') { + $recaptcha_response->is_valid = true; + } + else { + $recaptcha_response->is_valid = false; + $recaptcha_response->error = $answers [1]; + } + return $recaptcha_response; + +} + +/** + * gets a URL where the user can sign up for reCAPTCHA. If your application + * has a configuration page where you enter a key, you should provide a link + * using this function. + * @param string $domain The domain where the page is hosted + * @param string $appname The name of your application + */ +function recaptcha_get_signup_url ($domain = null, $appname = null) { + return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); +} + +function _recaptcha_aes_pad($val) { + $block_size = 16; + $numpad = $block_size - (strlen ($val) % $block_size); + return str_pad($val, strlen ($val) + $numpad, chr($numpad)); +} + +/* Mailhide related code */ + +function _recaptcha_aes_encrypt($val,$ky) { + if (! function_exists ("mcrypt_encrypt")) { + die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); + } + $mode=MCRYPT_MODE_CBC; + $enc=MCRYPT_RIJNDAEL_128; + $val=_recaptcha_aes_pad($val); + return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); +} + + +function _recaptcha_mailhide_urlbase64 ($x) { + return strtr(base64_encode ($x), '+/', '-_'); +} + +/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ +function recaptcha_mailhide_url($pubkey, $privkey, $email) { + if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { + die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . + "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>"); + } + + + $ky = pack('H*', $privkey); + $cryptmail = _recaptcha_aes_encrypt ($email, $ky); + + return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); +} + +/** + * gets the parts of the email to expose to the user. + * eg, given johndoe@example,com return ["john", "example.com"]. + * the email is then displayed as john...@example.com + */ +function _recaptcha_mailhide_email_parts ($email) { + $arr = preg_split("/@/", $email ); + + if (strlen ($arr[0]) <= 4) { + $arr[0] = substr ($arr[0], 0, 1); + } else if (strlen ($arr[0]) <= 6) { + $arr[0] = substr ($arr[0], 0, 3); + } else { + $arr[0] = substr ($arr[0], 0, 4); + } + return $arr; +} + +/** + * Gets html to display an email address given a public an private key. + * to get a key, go to: + * + * http://www.google.com/recaptcha/mailhide/apikey + */ +function recaptcha_mailhide_html($pubkey, $privkey, $email) { + $emailparts = _recaptcha_mailhide_email_parts ($email); + $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); + + return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) . + "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]); + +} + + +?> diff --git a/framework/3rdParty/readme.html b/framework/3rdParty/readme.html index e545615c..bbf3a3a7 100644 --- a/framework/3rdParty/readme.html +++ b/framework/3rdParty/readme.html @@ -19,6 +19,13 @@ projects. </tr>
<tr>
+ <td><a href="ReCaptcha">ReCaptcha</a></td>
+ <td><a href="http://www.google.com/recaptcha">ReCaptcha - Stop spam, read books</a></td>
+ <td><a href="ReCaptcha/LICENSE">BSD-like</a></td>
+ <td>System.Web.UI.WebControls.TReCaptcha</td>
+ <td>ReCaptcha php documentation available at http://recaptcha.net/plugins/php</td>
+</tr>
+<tr>
<td><a href="TextHighlighter">Text_Highlighter</a></td>
<td><a href="http://pear.php.net/package/Text_Highlighter/">Text_Highlighter - Generic Syntax Highlighter</a> (v0.7.0 beta)</td>
<td><a href="http://www.php.net/license/3_01.txt">The PHP License</a></td>
diff --git a/framework/Exceptions/messages/messages.txt b/framework/Exceptions/messages/messages.txt index fd85920c..cc72d6a2 100644 --- a/framework/Exceptions/messages/messages.txt +++ b/framework/Exceptions/messages/messages.txt @@ -455,6 +455,15 @@ captcha_gd2_required = TCaptcha requires PHP GD2 extension. captcha_imagettftext_required = TCaptcha requires PHP GD2 extension with TrueType font support. captcha_imagepng_required = TCaptcha requires PHP GD2 extension with PNG image format support. +captchavalidator_captchacontrol_required = TReCaptchaValidator.CaptchaControl must point to an existing TCaptcha control. +captchavalidator_captchacontrol_inexistent = TReCaptchaValidator.CaptchaControl {0} must point to an existing TCaptcha control. +captchavalidator_captchacontrol_invalid = TReCaptchaValidator.CaptchaControl {0} must point to an existing TCaptcha control. + +recaptcha_privatekey_unknown = TReCaptcha.PrivateKey is unknown. To use reCAPTCHA you must get an API key. +recaptcha_publickey_unknown = TReCaptcha.PublicKey is unknown. To use reCAPTCHA you must get an API key. + +recaptchavalidator_captchacontrol_invalid = TReCaptchaValidator.ControlToValidate must be an instance of TReCaptcha. + slider_handle_class_invalid = TSlider.HandleClass '{0}' is not a valid user class. The class must extends TSliderHandle. cachepagestatepersister_cachemoduleid_invalid = TCachePageStatePersister.CacheModuleID '{0}' does not point to a valid cache module. diff --git a/framework/Web/UI/WebControls/TCaptcha.php b/framework/Web/UI/WebControls/TCaptcha.php index 9ca6aa76..7eff1294 100644 --- a/framework/Web/UI/WebControls/TCaptcha.php +++ b/framework/Web/UI/WebControls/TCaptcha.php @@ -4,7 +4,7 @@ *
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.pradosoft.com/
- * @copyright Copyright © 2005-2011 PradoSoft + * @copyright Copyright © 2005-2011 PradoSoft
* @license http://www.pradosoft.com/license/
* @version $Id$
* @package System.Web.UI.WebControls
@@ -15,6 +15,10 @@ Prado::using('System.Web.UI.WebControls.TImage'); /**
* TCaptcha class.
*
+ * Notice: while this class is easy to use and implement, it does not provide full security.
+ * In fact, it's easy to bypass the checks reusing old, already-validated tokens (reply attack).
+ * A better alternative is provided by {@link TReCaptcha}.
+ *
* 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.
*
diff --git a/framework/Web/UI/WebControls/TCaptchaValidator.php b/framework/Web/UI/WebControls/TCaptchaValidator.php index 7854b639..b01cd786 100644 --- a/framework/Web/UI/WebControls/TCaptchaValidator.php +++ b/framework/Web/UI/WebControls/TCaptchaValidator.php @@ -4,7 +4,7 @@ *
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.pradosoft.com/
- * @copyright Copyright © 2005-2011 PradoSoft + * @copyright Copyright © 2005-2011 PradoSoft
* @license http://www.pradosoft.com/license/
* @version $Id$
* @package System.Web.UI.WebControls
@@ -16,6 +16,10 @@ Prado::using('System.Web.UI.WebControls.TCaptcha'); /**
* TCaptchaValidator class
*
+ * Notice: while this class is easy to use and implement, it does not provide full security.
+ * In fact, it's easy to bypass the checks reusing old, already-validated tokens (reply attack).
+ * A better alternative is provided by {@link TReCaptchaValidator}.
+ *
* 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
diff --git a/framework/Web/UI/WebControls/TReCaptcha.php b/framework/Web/UI/WebControls/TReCaptcha.php new file mode 100644 index 00000000..bb956bcb --- /dev/null +++ b/framework/Web/UI/WebControls/TReCaptcha.php @@ -0,0 +1,199 @@ +<?php
+
+/**
+ * TReCaptcha class file
+ *
+ * @author Bérczi Gábor <gabor.berczi@devworx.hu>
+ * @link http://www.devworx.hu/
+ * @copyright Copyright © 2011 DevWorx
+ * @license http://www.pradosoft.com/license/
+ * @package System.Web.UI.WebControls
+ */
+
+ Prado::using('System.3rdParty.ReCaptcha.recaptchalib');
+
+/**
+ * TReCaptcha class.
+ *
+ * TReCaptcha displays a reCAPTCHA (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. It can
+ * also prevent multiple submits of the same form either by accident, or on purpose (ie. spamming).
+ *
+ * The reCAPTCHA to solve (a string consisting of two separate words) displayed is automatically
+ * generated by the reCAPTCHA system at recaptcha.net. However, in order to use the services
+ * of the site you will need to register and get a public and a private API key pair, and
+ * supply those to the reCAPTCHA control through setting the {@link setPrivateKey PrivateKey}
+ * and {@link setPublicKey PublicKey} properties.
+ *
+ * Currently the reCAPTCHA API supports only one reCAPTCHA field per page, so you MUST make sure that all
+ * your input is protected and validated by a single reCAPTCHA control. Placing more than one reCAPTCHA
+ * control on the page will lead to unpredictable results, and the user will most likely unable to solve
+ * any of them successfully.
+ *
+ * Upon postback, user input can be validated by calling {@link validate()}.
+ * The {@link TReCaptchaValidator} control can also be used to do validation, which provides
+ * server-side validation. Calling (@link validate()) will invalidate the token supplied, so all consecutive
+ * calls to the method - without solving a new captcha - will return false. Therefore if implementing a multi-stage
+ * input process, you must make sure that you call validate() only once, either at the end of the input process, or
+ * you store the result till the end of the processing.
+ *
+ * The following template shows a typical use of TReCaptcha control:
+ * <code>
+ * <com:TReCaptcha ID="Captcha"
+ * PublicKey="..."
+ * PrivateKey="..."
+ * />
+ * <com:TReCaptchaValidator ControlToValidate="Captcha"
+ * ErrorMessage="You are challenged!" />
+ * </code>
+ *
+ * @author Bérczi Gábor <gabor.berczi@devworx.hu>
+ * @package System.Web.UI.WebControls
+ * @since 3.2
+ */
+class TReCaptcha extends TControl implements IValidatable
+{
+ private $_isValid=true;
+
+ const ChallengeFieldName = 'recaptcha_challenge_field';
+ const ResponseFieldName = 'recaptcha_response_field';
+
+ /**
+ * Returns true if this control validated successfully.
+ * Defaults to true.
+ * @return bool wether this control validated successfully.
+ */
+ public function getIsValid()
+ {
+ return $this->_isValid;
+ }
+ /**
+ * @param bool wether this control is valid.
+ */
+ public function setIsValid($value)
+ {
+ $this->_isValid=TPropertyValue::ensureBoolean($value);
+ }
+
+ public function getValidationPropertyValue()
+ {
+ return $this->Request[$this->getChallengeFieldName()];
+ }
+
+ public function getPublicKey()
+ {
+ return $this->getViewState('PublicKey');
+ }
+
+ public function setPublicKey($value)
+ {
+ return $this->setViewState('PublicKey', TPropertyValue::ensureString($value));
+ }
+
+ public function getPrivateKey()
+ {
+ return $this->getViewState('PrivateKey');
+ }
+
+ public function setPrivateKey($value)
+ {
+ return $this->setViewState('PrivateKey', TPropertyValue::ensureString($value));
+ }
+
+ public function getThemeName()
+ {
+ return $this->getViewState('ThemeName');
+ }
+
+ public function setThemeName($value)
+ {
+ return $this->setViewState('ThemeName', TPropertyValue::ensureString($value));
+ }
+
+ public function getCustomTranslations()
+ {
+ return TPropertyValue::ensureArray($this->getViewState('CustomTranslations'));
+ }
+
+ public function setCustomTranslations($value)
+ {
+ return $this->setViewState('CustomTranslations', TPropertyValue::ensureArray($value));
+ }
+
+ public function getLanguage()
+ {
+ return $this->getViewState('Language');
+ }
+
+ public function setLanguage($value)
+ {
+ return $this->setViewState('Language', TPropertyValue::ensureString($value));
+ }
+
+ protected function getChallengeFieldName()
+ {
+ return /*$this->ClientID.'_'.*/self::ChallengeFieldName;
+ }
+
+ protected function getResponseFieldName()
+ {
+ return /*$this->ClientID.'_'.*/self::ResponseFieldName;
+ }
+
+ public function getClientSideOptions()
+ {
+ $options = array();
+ if ($theme = $this->getThemeName())
+ $options['theme'] = $theme;
+ if ($lang = $this->getLanguage())
+ $options['lang'] = $lang;
+ if ($trans = $this->getCustomTranslations())
+ $options['custom_translations'] = $trans;
+ return $options;
+ }
+
+ public function validate()
+ {
+ $resp = recaptcha_check_answer(
+ $this->getPrivateKey(),
+ $_SERVER["REMOTE_ADDR"],
+ $_POST[$this->getChallengeFieldName()],
+ $_POST[$this->getResponseFieldName()]
+ );
+ return ($resp->is_valid==1);
+ }
+
+ /**
+ * Checks for API keys
+ * @param mixed event parameter
+ */
+ public function onPreRender($param)
+ {
+ parent::onPreRender($param);
+ if("" == $this->getPublicKey())
+ throw new TConfigurationException('recaptcha_publickey_unknown');
+ if("" == $this->getPrivateKey())
+ throw new TConfigurationException('recaptcha_privatekey_unknown');
+ }
+
+ public function render($writer)
+ {
+ $writer->write(TJavaScript::renderScriptBlock(
+ 'var RecaptchaOptions = '.TJavaScript::jsonEncode($this->getClientSideOptions()).';'
+ ));
+
+ $html = recaptcha_get_html($this->getPublicKey());
+ /*
+ reCAPTCHA currently does not support multiple validations per page
+ $html = str_replace(
+ array(self::ChallengeFieldName,self::ResponseFieldName),
+ array($this->getChallengeFieldName(),$this->getResponseFieldName()),
+ $html
+ );
+ */
+ $writer->write($html);
+ }
+
+}
+
+?>
\ No newline at end of file diff --git a/framework/Web/UI/WebControls/TReCaptchaValidator.php b/framework/Web/UI/WebControls/TReCaptchaValidator.php new file mode 100644 index 00000000..ae94ea59 --- /dev/null +++ b/framework/Web/UI/WebControls/TReCaptchaValidator.php @@ -0,0 +1,72 @@ +<?php
+
+/**
+ * TReCaptchaValidator class file
+ *
+ * @author Bérczi Gábor <gabor.berczi@devworx.hu>
+ * @link http://www.devworx.hu/
+ * @copyright Copyright © 2011 DevWorx
+ * @license http://www.pradosoft.com/license/
+ * @package System.Web.UI.WebControls
+ */
+
+Prado::using('System.Web.UI.WebControls.TBaseValidator');
+Prado::using('System.Web.UI.WebControls.TReCaptcha');
+
+/**
+ * TReCaptchaValidator class
+ *
+ * TReCaptchaValidator validates user input against a reCAPTCHA represented by
+ * a {@link TReCaptcha} control. The input control fails validation if its value
+ * is not the same as the token displayed in reCAPTCHA. Note, if the user does
+ * not enter any thing, it is still considered as failing the validation.
+ *
+ * To use TReCaptchaValidator, specify the {@link setControlToValidate ControlToValidate}
+ * to be the ID path of the {@link TReCaptcha} control.
+ *
+ * @author Bérczi Gábor <gabor.berczi@devworx.hu>
+ * @package System.Web.UI.WebControls
+ * @since 3.2
+ */
+class TReCaptchaValidator extends TBaseValidator
+{
+ protected $_isvalid = null;
+
+ /**
+ * 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 '';
+ }
+
+ public function getEnableClientScript()
+ {
+ return false;
+ }
+
+ /**
+ * 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 RECAPTCHA control.
+ *
+ * @return boolean whether the validation succeeds
+ */
+ protected function evaluateIsValid()
+ {
+ // check validity only once (if trying to evaluate multiple times, all redundant checks would fail)
+ if (is_null($this->_isvalid))
+ {
+ $control = $this->getValidationTarget();
+ if(!($control instanceof TCaptcha))
+ throw new TConfigurationException('recaptchavalidator_captchacontrol_invalid');
+ $this->_isvalid = $control->validate();
+ }
+ return ($this->_isvalid==true);
+ }
+
+}
+
+?>
\ No newline at end of file |