r81231 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r81230‎ | r81231 | r81232 >
Date:05:40, 31 January 2011
Author:yaron
Status:deferred (Comments)
Tags:
Comment:
Adding files from the ReCAPTCHA extension, with minor modifications
Modified paths:
  • /trunk/extensions/ConfirmEdit/ReCaptcha.i18n.php (added) (history)
  • /trunk/extensions/ConfirmEdit/ReCaptcha.php (added) (history)
  • /trunk/extensions/ConfirmEdit/recaptchalib.php (added) (history)

Diff [purge]

Index: trunk/extensions/ConfirmEdit/ReCaptcha.php
@@ -0,0 +1,139 @@
 2+<?php
 3+
 4+/**
 5+ * Captcha class using the reCAPTCHA widget.
 6+ * Stop Spam. Read Books.
 7+ *
 8+ * @addtogroup Extensions
 9+ * @author Mike Crawford <mike.crawford@gmail.com>
 10+ * @copyright Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
 11+ * @licence MIT/X11
 12+ */
 13+
 14+if( !defined( 'MEDIAWIKI' ) ) {
 15+ exit;
 16+}
 17+
 18+$wgExtensionMessagesFiles['ReCaptcha'] = dirname( __FILE__ ) . '/ReCaptcha.i18n.php';
 19+
 20+require_once( 'recaptchalib.php' );
 21+
 22+// Set these in LocalSettings.php
 23+$wgReCaptchaPublicKey = '';
 24+$wgReCaptchaPrivateKey = '';
 25+// For backwards compatibility
 26+$recaptcha_public_key = '';
 27+$recaptcha_private_key = '';
 28+
 29+
 30+/**
 31+ * Make sure the keys are defined.
 32+ */
 33+function efReCaptcha() {
 34+ global $wgReCaptchaPublicKey, $wgReCaptchaPrivateKey;
 35+ global $recaptcha_public_key, $recaptcha_private_key;
 36+ global $wgServerName;
 37+
 38+ // Backwards compatibility
 39+ $wgReCaptchaPublicKey == '' ) {
 40+ $wgReCaptchaPublicKey = $recaptcha_public_key;
 41+ }
 42+ if ( $wgReCaptchaPrivateKey == '' ) {
 43+ $wgReCaptchaPrivateKey = $recaptcha_private_key;
 44+ }
 45+
 46+ if ($wgReCaptchaPublicKey == '' || $wgReCaptchaPrivateKey == '') {
 47+ die ('You need to set $wgReCaptchaPrivateKey and $wgReCaptchaPublicKey in LocalSettings.php to ' .
 48+ "use the reCAPTCHA plugin. You can sign up for a key <a href='" .
 49+ htmlentities(recaptcha_get_signup_url ($wgServerName, "mediawiki")) . "'>here</a>.");
 50+ }
 51+}
 52+
 53+
 54+class ReCaptcha extends SimpleCaptcha {
 55+
 56+ //reCAPTHCA error code returned from recaptcha_check_answer
 57+ private $recaptcha_error = null;
 58+
 59+
 60+ /**
 61+ * Displays the reCAPTCHA widget.
 62+ * If $this->recaptcha_error is set, it will display an error in the widget.
 63+ *
 64+ */
 65+ function getForm() {
 66+ global $wgReCaptchaPublicKey;
 67+ return "<script>var RecaptchaOptions = { tabindex : 1 }; </script> " .
 68+ recaptcha_get_html($wgReCaptchaPublicKey, $this->recaptcha_error);
 69+ }
 70+
 71+
 72+
 73+ /**
 74+ * Calls the library function recaptcha_check_answer to verify the users input.
 75+ * Sets $this->recaptcha_error if the user is incorrect.
 76+ * @return boolean
 77+ *
 78+ */
 79+ function passCaptcha() {
 80+ global $wgReCaptchaPrivateKey;
 81+ $recaptcha_response = recaptcha_check_answer ($wgReCaptchaPrivateKey,
 82+ wfGetIP (),
 83+ $_POST['recaptcha_challenge_field'],
 84+ $_POST['recaptcha_response_field']);
 85+ if (!$recaptcha_response->is_valid) {
 86+ $this->recaptcha_error = $recaptcha_response->error;
 87+ return false;
 88+ }
 89+ $recaptcha_error = null;
 90+ return true;
 91+
 92+ }
 93+
 94+
 95+
 96+ /**
 97+ * Called on all edit page saves. (EditFilter events)
 98+ * @return boolean - true if page save should continue, false if should display Captcha widget.
 99+ */
 100+ function confirmEdit( $editPage, $newtext, $section ) {
 101+ if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
 102+
 103+ if (!isset($_POST['recaptcha_response_field'])) {
 104+ //User has not yet been presented with Captcha, show the widget.
 105+ $editPage->showEditForm( array( &$this, 'editCallback' ) );
 106+ return false;
 107+ }
 108+
 109+ if( $this->passCaptcha() ) {
 110+ return true;
 111+ } else {
 112+ //Try again - show the widget
 113+ $editPage->showEditForm( array( &$this, 'editCallback' ) );
 114+ return false;
 115+ }
 116+
 117+ } else {
 118+ wfDebug( "ConfirmEdit: no need to show captcha.\n" );
 119+ return true;
 120+ }
 121+ }
 122+
 123+
 124+
 125+ /**
 126+ * Show a message asking the user to enter a captcha on edit
 127+ * The result will be treated as wiki text
 128+ *
 129+ * @param $action Action being performed
 130+ * @return string
 131+ */
 132+ function getMessage( $action ) {
 133+ $name = 'recaptcha-' . $action;
 134+ $text = wfMsg( $name );
 135+ # Obtain a more tailored message, if possible, otherwise, fall back to
 136+ # the default for edits
 137+ return wfEmptyMsg( $name, $text ) ? wfMsg( 'recaptcha-edit' ) : $text;
 138+ }
 139+
 140+}
Index: trunk/extensions/ConfirmEdit/ReCaptcha.i18n.php
@@ -0,0 +1,120 @@
 2+<?php
 3+/**
 4+ * Internationalisation file for the ReCaptcha module of the ConfirmEdit
 5+ * extension.
 6+ *
 7+ * @addtogroup Extensions
 8+*/
 9+
 10+$messages = array();
 11+
 12+/* English */
 13+$messages['en'] = array(
 14+ 'recaptcha-edit' => 'To help protect against automated edit spam, please type the two words you see in the box below:',
 15+ 'recaptcha-addurl' => 'Your edit includes new external links. To help protect against automated
 16+spam, please type the two words you see in the box below:',
 17+ 'recaptcha-badpass' => 'To help protect against automated password cracking, please type the two words you see in the box below:',
 18+ 'recaptcha-createaccount' => 'To help protect against automated account creation, please type the two words you see in the box below:',
 19+ 'recaptcha-createaccount-fail' => "Incorrect or missing reCAPTCHA answer.",
 20+ 'recaptcha-create' => 'To help protect against automated page creation, please type the two words you see in the box below:',
 21+
 22+);
 23+
 24+/* French */
 25+$messages['fr'] = array(
 26+ 'recaptcha-edit' => "Pour nous protéger des robots, merci d'écrire les deux mots visibles dans le cadre qui suit:",
 27+ 'recaptcha-addurl' => "Votre contribution contient des liens vers un site externe. Pour nous protéger des robots, merci d'écrire les deux mots visibles dans le cadre qui suit:",
 28+ 'recaptcha-badpass' => "Pour nous protéger des essais automatiques de cassage de mot de passe, merci d'écrire les deux mots visibles dans le cadre qui suit:",
 29+ 'recaptcha-createaccount' => "Pour nous protéger des créations automatiques de compte, merci d'écrire les deux mots visibles dans le cadre qui suit:",
 30+ 'recaptcha-createaccount-fail' => "Réponse de reCAPTCHA fausse ou manquante.",
 31+ 'recaptcha-create' => "Pour nous protéger des créations automatiques de pages, merci d'écrire les deux mots visibles dans le cadre qui suit:",
 32+);
 33+
 34+/* Spanish */
 35+$message['es'] = array(
 36+ 'recaptcha-edit' => 'Para protegernos de los robots, escribid por favor las dos palabras visibles en el cuadro abajo:',
 37+ 'recaptcha-addurl' => 'Su aportación contiene enlaces externos. Para protegernos de los robots, escribid por favor las dos palabras visibles en el cuadro abajo:',
 38+ 'recaptcha-badpass' => 'Para protegernos de los robots que intentan adivinar contraseñas, escribid por favor las dos palabras visibles en el cuadro abajo:',
 39+ 'recaptcha-createaccount' => 'Para protegernos de la creación automática de cuentas, escribid por favor las dos palabras visibles en el cuadro abajo:',
 40+ 'recaptcha-createaccount-fail' => "La respuesta al reCAPTCHA esta falsa o faltante.",
 41+ 'recaptcha-create' => 'Para protegernos de la creación automática de páginas, escribid por favor las dos palabras visibles en el cuadro abajo:',
 42+);
 43+
 44+/* Polish */
 45+$messages['pl'] = array(
 46+ 'recaptcha-edit' => 'Aby uchronić nas przed robotami, proszę wpisać dwa widoczne słowa w poniższym polu:',
 47+ 'recaptcha-addurl' => 'Twoja edycja zawiera linki zewnętrzne. Aby uchronić nas przed robotami, proszę wpisać dwa widoczne słowa w poniższym polu:',
 48+ 'recaptcha-badpass' => 'Aby uchronić nas przed złamaniem automatycznym haseł, proszę wpisać dwa widoczne słowa w poniższym polu:',
 49+ 'recaptcha-createaccount' => 'Aby uchronić nas przed automatycznym stworzeniem użytkowników, proszę wpisać dwa widoczne słowa w poniższym polu:',
 50+ 'recaptcha-createaccount-fail' => "Odpowiedź na reCAPTCHA jest fałszywa lub brakująca.",
 51+ 'recaptcha-create' => 'Aby uchronić nas przed tworzeniem stron przez robotów, proszę wpisać dwa widoczne słowa w poniższym polu:',
 52+);
 53+
 54+/* German */
 55+$messages['de'] = array(
 56+ 'recaptcha-edit' => 'Zum Schutz vor automatisiertem Spam, gib bitte die beiden folgenden Wörter in das untenstehende Feld ein:',
 57+ 'recaptcha-addurl' => 'Deine Bearbeitung enthält neue externe Links. Zum Schutz vor automatisiertem Spam gebe bitte die beiden folgenden Wörter in das untenstehende Feld ein:',
 58+ 'recaptcha-badpass' => 'Zum Schutz gegen automatisiertes Knacken von Passwörtern, gebe bitte die beiden folgenden Wörter in das untenstehende Feld ein:',
 59+ 'recaptcha-createaccount' => 'Zum Schutz gegen automatisierte Erstellung von Benutzerkonten gebe bitte die beiden folgenden Wörter in das untenstehende Feld ein:',
 60+ 'recaptcha-createaccount-fail' => "Fehlerhafte oder fehlende reCAPTCHA Antwort.",
 61+ 'recaptcha-create' => 'Zum Schutz gegen automatisierte Erstellung von Seiten gebe bitte die beiden folgenden Wörter in das untenstehende Feld ein:',
 62+);
 63+
 64+/* Portuguese */
 65+$messages['pt'] = array(
 66+ 'recaptcha-edit' => 'Para proteger-nos de spam, por favor escreva as duas palavras visíveis abaixo:',
 67+ 'recaptcha-addurl' => 'A sua edição contem ligações externas. Para proteger-nos de spam, por favor escreva as duas palavras visíveis abaixo:',
 68+ 'recaptcha-badpass' => 'Para proteger-nos de robots que tentam adivinhar senhas, por favor escreva as duas palavras visíveis abaixo:',
 69+ 'recaptcha-createaccount' => 'Para proteger-nos de criação automática de contas, por favor escreva as duas palavras visíveis abaixo:',
 70+ 'recaptcha-createaccount-fail' => "A resposta ao reCAPTCHA é errada.",
 71+ 'recaptcha-create' => 'Para proteger-nos da criação automática de páginas, por favor escreva as duas palavras visíveis abaixo:',
 72+);
 73+
 74+/* Brazilian Portuguese */
 75+$messages['pt_br'] = array(
 76+ 'recaptcha-edit' => 'Para ajudar a prevenir contra vandalismos, por favor digite as duas palavras que voc&amp;ecirc; v&amp;ecirc; na caixa abaixo:',
 77+ 'recaptcha-addurl' => 'A sua edi&amp;ccedil;&amp;atilde;o inclui liga&amp;ccedil;&amp;otilde;es externas. Para ajudar a prevenir contra vandalismos, por favor digite as duas palavras que voc&amp;ecirc; v&amp;ecirc; na caixa abaixo:',
 78+ 'recaptcha-badpass' => 'Para ajudar a prevenir contra tentativas de desbloquear senhas, por favor digite as duas palavras que voc&amp;ecirc; v&amp;ecirc; na caixa abaixo:',
 79+ 'recaptcha-createaccount' => 'Para ajudar a prevenir contra cria&amp;ccedil;&amp;atilde;o automatizada de usu&amp;aacute;rios, por favor digite as duas palavras que voc&amp;ecirc; v&amp;ecirc; na caixa abaixo:',
 80+ 'recaptcha-createaccount-fail' => "Resposta incorreta ao reCAPTCHA.",
 81+ 'recaptcha-create' => 'Para ajudar a prevenir contra cria&amp;ccedil;&amp;atilde;o automatizada de p&amp;aacute;ginas, por favor digite as duas palavras que voc&amp;ecirc; v&amp;ecirc; na caixa abaixo:',
 82+);
 83+
 84+/* Swedish */
 85+$messages['sv'] = array(
 86+ 'recaptcha-edit' => 'Den här sidan skyddas mot spam-robotar, bevisa att du är en människa genom att skriva de två orden du ser i boxen nedan:',
 87+ 'recaptcha-addurl' => 'Din förändring av sidan innehåller nya externa länkar, vilket är typiskt för spam. Bevisa att du är en människa genom att skriva de två orden du ser i boxen nedan:',
 88+ 'recaptcha-badpass' => 'För att skydda wikin mot robotar som gissar användares lösenord behöver användare bevisa att de är människor. Skriv ner de två orden som du ser i boxen nedan:',
 89+ 'recaptcha-createaccount' => 'För att skydda wikin mot robotar som skapar konton behöver användare bevisa att de är människor. Var vänlig och skriv ner de två orden du ser i boxen nedan:',
 90+ 'recaptcha-createaccount-fail' => "Du har angivit ett felaktig svar för reCAPTCHA.",
 91+ 'recaptcha-create' => 'För att skydda wikin mot robotar som skapar nya artiklar. Var vänlig och skriv ner de två orden som finns i boxen nedan:',
 92+);
 93+
 94+/* Vietnamese */
 95+$messages['vi'] = array(
 96+ 'recaptcha-edit' => 'Để giúp tránh các sửa đổi rác tự động, xin hãy gõ hai từ mà bạn nhìn thấy vào ô dưới đây:',
 97+ 'recaptcha-addurl' => 'Sửa đổi của bạn có chứa liên kết ngoài mới. Để giúp tránh các sửa đổi rác tự động, xin hãy gõ hai từ mà bạn nhìn vào ô dưới đây:',
 98+ 'recaptcha-badpass' => 'Để giúp tránh bẻ khóa mật khẩu tự động, xin hãy gõ hai từ mà bạn nhìn vào ô dưới đây:',
 99+ 'recaptcha-createaccount' => 'Để giúp tránh việc mở tài khoản tự động, xin hãy gõ hai từ mà bạn nhìn vào ô dưới đây:',
 100+ 'recaptcha-createaccount-fail' => "Thiếu câu trả lời reCAPTCHA hoặc câu trả lời không đúng.",
 101+ 'recaptcha-create' => 'Để giúp tránh việc tạo trang tự động, xin hãy gõ hai từ mà bạn nhìn vào ô dưới đây:',
 102+);
 103+
 104+$messages['he'] = array(
 105+ 'recaptcha-edit' => 'אינכם משתמש רשום.כהגנה מפני ספאם אוטומטי, אנא הקלידו את שתי המילים שלהלן. תודה.',
 106+ 'recaptcha-addurl' => 'אינכם משתמש רשום.כהגנה מפני ספאם אוטומטי, אנא הקלידו את שתי המילים שלהלן. תודה.',
 107+ 'recaptcha-badpass' => 'כהגנה מפני מפצחי סיסמאות אוטומטיים אנא הקלידו את שתי המילים שלהלן:',
 108+ 'recaptcha-createaccount' => 'כהגנה מפני יצירת חשבונות פיקטיביים ע"י אוטומטים אנא הקלידו את שתי המילים שלהלן:',
 109+ 'recaptcha-createaccount-fail' => 'לא הוקלדו מילות האישור, או שהוקלדו מילים לא נכונות. נסו שנית.',
 110+ 'recaptcha-create' => 'אינכם משתמש רשום.כהגנה מפני ספאם אוטומטי, אנא הקלידו את שתי המילים שלהלן. תודה.',
 111+);
 112+
 113+/* Japanese - 日本語 */
 114+$messages['ja'] = array(
 115+ 'recaptcha-edit' => '自動編集スパムからの保護のため、下の画像に表示されている2つの言葉を入力 してください。',
 116+ 'recaptcha-addurl' => 'あなたの編集は新しい外部リンクを含んでいます。自動スパムからの保護のた め、下の画像に表示されている2つの言葉を入力してください。',
 117+ 'recaptcha-badpass' => '自動パスワードクラッキングからの保護のために、下の画像に表示されている2 つの言葉を入力してください。',
 118+ 'recaptcha-createaccount' => '自動アカウント登録からの保護のために、下の画像に表示されている2つの言葉 を入力してください。',
 119+ 'recaptcha-createaccount-fail' => '入力された文字列が正しくありません。',
 120+ 'recaptcha-create' => '自動ページ作成からの保護のために、下の画像に表示されている2つの言葉を入 力してください。',
 121+);
Index: trunk/extensions/ConfirmEdit/recaptchalib.php
@@ -0,0 +1,275 @@
 2+<?php
 3+/*
 4+ * This is a PHP library that handles calling reCAPTCHA.
 5+ * - Documentation and latest version
 6+ * http://recaptcha.net/plugins/php/
 7+ * - Get a reCAPTCHA API Key
 8+ * http://recaptcha.net/api/getkey
 9+ * - Discussion group
 10+ * http://groups.google.com/group/recaptcha
 11+ *
 12+ * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
 13+ * AUTHORS:
 14+ * Mike Crawford
 15+ * Ben Maurer
 16+ *
 17+ * Permission is hereby granted, free of charge, to any person obtaining a copy
 18+ * of this software and associated documentation files (the "Software"), to deal
 19+ * in the Software without restriction, including without limitation the rights
 20+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 21+ * copies of the Software, and to permit persons to whom the Software is
 22+ * furnished to do so, subject to the following conditions:
 23+ *
 24+ * The above copyright notice and this permission notice shall be included in
 25+ * all copies or substantial portions of the Software.
 26+ *
 27+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 28+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 29+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 30+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 31+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 32+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 33+ * THE SOFTWARE.
 34+ */
 35+
 36+/**
 37+ * The reCAPTCHA server URL's
 38+ */
 39+$recaptcha_api_server = 'http://api.recaptcha.net';
 40+$recaptcha_api_secure_server = 'https://api-secure.recaptcha.net';
 41+$recaptcha_verify_server = 'api-verify.recaptcha.net';
 42+
 43+
 44+/**
 45+ * Encodes the given data into a query string format
 46+ * @param $data - array of string elements to be encoded
 47+ * @return string - encoded request
 48+ */
 49+function _recaptcha_qsencode ($data) {
 50+ $req = "";
 51+ foreach ( $data as $key => $value )
 52+ $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
 53+
 54+ // Cut the last '&'
 55+ $req=substr($req,0,strlen($req)-1);
 56+ return $req;
 57+}
 58+
 59+
 60+
 61+/**
 62+ * Submits an HTTP POST to a reCAPTCHA server
 63+ * @param string $host
 64+ * @param string $path
 65+ * @param array $data
 66+ * @param int port
 67+ * @return array response
 68+ */
 69+function _recaptcha_http_post($host, $path, $data, $port = 80) {
 70+
 71+ $req = _recaptcha_qsencode ($data);
 72+
 73+ $http_request = "POST $path HTTP/1.0\r\n";
 74+ $http_request .= "Host: $host\r\n";
 75+ $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
 76+ $http_request .= "Content-Length: " . strlen($req) . "\r\n";
 77+ $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
 78+ $http_request .= "\r\n";
 79+ $http_request .= $req;
 80+
 81+ $response = '';
 82+ if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
 83+ die ('Could not open socket');
 84+ }
 85+
 86+ fwrite($fs, $http_request);
 87+
 88+ while ( !feof($fs) )
 89+ $response .= fgets($fs, 1160); // One TCP-IP packet
 90+ fclose($fs);
 91+ $response = explode("\r\n\r\n", $response, 2);
 92+
 93+ return $response;
 94+}
 95+
 96+
 97+
 98+/**
 99+ * Gets the challenge HTML (javascript and non-javascript version).
 100+ * This is called from the browser, and the resulting reCAPTCHA HTML widget
 101+ * is embedded within the HTML form it was called from.
 102+ * @param string $pubkey A public key for reCAPTCHA
 103+ * @param string $error The error given by reCAPTCHA (optional, default is null)
 104+ * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
 105+
 106+ * @return string - The HTML to be embedded in the user's form.
 107+ */
 108+function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
 109+{
 110+ global $recaptcha_api_server, $recaptcha_api_ssl_server;
 111+
 112+ if ($pubkey == null || $pubkey == '') {
 113+ die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
 114+ }
 115+
 116+ if ($use_ssl) {
 117+ $server = $recaptcha_api_ssl_server;
 118+ } else {
 119+ $server = $recaptcha_api_server;
 120+ }
 121+ $errorpart = "";
 122+ if ($error) {
 123+ $errorpart = "&amp;error=" . $error;
 124+ }
 125+ return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
 126+
 127+ <noscript>
 128+ <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br>
 129+ <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
 130+ <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
 131+ </noscript>';
 132+}
 133+
 134+
 135+
 136+
 137+/**
 138+ * A ReCaptchaResponse is returned from recaptcha_check_answer()
 139+ */
 140+class ReCaptchaResponse {
 141+ var $is_valid;
 142+ var $error;
 143+}
 144+
 145+
 146+/**
 147+ * Calls an HTTP POST function to verify if the user's guess was correct
 148+ * @param string $privkey
 149+ * @param string $remoteip
 150+ * @param string $challenge
 151+ * @param string $response
 152+ * @return ReCaptchaResponse
 153+ */
 154+function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response)
 155+{
 156+ if ($privkey == null || $privkey == '') {
 157+ die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
 158+ }
 159+
 160+ if ($remoteip == null || $remoteip == '') {
 161+ die ("For security reasons, you must pass the remote ip to reCAPTCHA");
 162+ }
 163+
 164+
 165+
 166+ //discard spam submissions
 167+ if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
 168+ $recaptcha_response = new ReCaptchaResponse();
 169+ $recaptcha_response->is_valid = false;
 170+ $recaptcha_response->error = 'incorrect-captcha-sol';
 171+ return $recaptcha_response;
 172+ }
 173+
 174+ global $recaptcha_verify_server;
 175+ $response = _recaptcha_http_post ($recaptcha_verify_server, "/verify",
 176+ array (
 177+ 'privatekey' => $privkey,
 178+ 'remoteip' => $remoteip,
 179+ 'challenge' => $challenge,
 180+ 'response' => $response
 181+ )
 182+ );
 183+
 184+ $answers = explode ("\n", $response [1]);
 185+ $recaptcha_response = new ReCaptchaResponse();
 186+
 187+ if (trim ($answers [0]) == 'true') {
 188+ $recaptcha_response->is_valid = true;
 189+ }
 190+ else {
 191+ $recaptcha_response->is_valid = false;
 192+ $recaptcha_response->error = $answers [1];
 193+ }
 194+ return $recaptcha_response;
 195+
 196+}
 197+
 198+/**
 199+ * gets a URL where the user can sign up for reCAPTCHA. If your application
 200+ * has a configuration page where you enter a key, you should provide a link
 201+ * using this function.
 202+ * @param string $domain The domain where the page is hosted
 203+ * @param string $appname The name of your application
 204+ */
 205+function recaptcha_get_signup_url ($domain = null, $appname = null) {
 206+ return "http://recaptcha.net/api/getkey?" . _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname));
 207+}
 208+
 209+
 210+
 211+/* Mailhide related code */
 212+
 213+function _recaptcha_aes_encrypt($val,$ky) {
 214+ if (! function_exists ("mcrypt_encrypt")) {
 215+ die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
 216+ }
 217+ $mode=MCRYPT_MODE_CBC;
 218+ $enc=MCRYPT_RIJNDAEL_128;
 219+ $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
 220+ return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
 221+}
 222+
 223+
 224+function _recaptcha_mailhide_urlbase64 ($x) {
 225+ return strtr(base64_encode ($x), '+/', '-_');
 226+}
 227+
 228+/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
 229+function recaptcha_mailhide_url($pubkey, $privkey, $email) {
 230+ if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
 231+ die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
 232+ "you can do so at <a href='http://mailhide.recaptcha.net/apikey'>http://mailhide.recaptcha.net/apikey</a>");
 233+ }
 234+
 235+
 236+ $ky = pack('H*', $privkey);
 237+ $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
 238+
 239+ return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
 240+}
 241+
 242+/**
 243+ * gets the parts of the email to expose to the user.
 244+ * eg, given johndoe@example,com return ["john", "example.com"].
 245+ * the email is then displayed as john...@example.com
 246+ */
 247+function _recaptcha_mailhide_email_parts ($email) {
 248+ $arr = preg_split("/@/", $email );
 249+
 250+ if (strlen ($arr[0]) <= 4) {
 251+ $arr[0] = substr ($arr[0], 0, 1);
 252+ } else if (strlen ($arr[0]) <= 6) {
 253+ $arr[0] = substr ($arr[0], 0, 3);
 254+ } else {
 255+ $arr[0] = substr ($arr[0], 0, 4);
 256+ }
 257+ return $arr;
 258+}
 259+
 260+/**
 261+ * Gets html to display an email address given a public an private key.
 262+ * to get a key, go to:
 263+ *
 264+ * http://mailhide.recaptcha.net/apikey
 265+ */
 266+function recaptcha_mailhide_html($pubkey, $privkey, $email) {
 267+ $emailparts = _recaptcha_mailhide_email_parts ($email);
 268+ $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
 269+
 270+ return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
 271+ "' 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]);
 272+
 273+}
 274+
 275+
 276+?>

Follow-up revisions

RevisionCommit summaryAuthorDate
r81239Followup r81231, r81229...reedy09:50, 31 January 2011

Comments

#Comment by Reedy (talk | contribs)   07:28, 31 January 2011

svn:eol-style native is missing

Remove trailing ?>

Status & tagging log