Commit 96fd37de by Qiang Xue

Fixes issue #49: finished CAPTCHA feature.

parent c5bad9ea
...@@ -6,6 +6,15 @@ use app\models\ContactForm; ...@@ -6,6 +6,15 @@ use app\models\ContactForm;
class SiteController extends Controller class SiteController extends Controller
{ {
public function actions()
{
return array(
'captcha' => array(
'class' => 'yii\web\CaptchaAction',
),
);
}
public function actionIndex() public function actionIndex()
{ {
echo $this->render('index'); echo $this->render('index');
......
...@@ -26,7 +26,7 @@ class ContactForm extends Model ...@@ -26,7 +26,7 @@ class ContactForm extends Model
// email has to be a valid email address // email has to be a valid email address
array('email', 'email'), array('email', 'email'),
// verifyCode needs to be entered correctly // verifyCode needs to be entered correctly
//array('verifyCode', 'captcha', 'allowEmpty' => !Captcha::checkRequirements()), array('verifyCode', 'captcha'),
); );
} }
......
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\widgets\Captcha;
/** /**
* @var yii\base\View $this * @var yii\base\View $this
...@@ -30,6 +31,15 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -30,6 +31,15 @@ $this->params['breadcrumbs'][] = $this->title;
<?php echo $form->field($model, 'email')->textInput(); ?> <?php echo $form->field($model, 'email')->textInput(); ?>
<?php echo $form->field($model, 'subject')->textInput(); ?> <?php echo $form->field($model, 'subject')->textInput(); ?>
<?php echo $form->field($model, 'body')->textArea(array('rows' => 6)); ?> <?php echo $form->field($model, 'body')->textArea(array('rows' => 6)); ?>
<?php
$field = $form->field($model, 'verifyCode');
echo $field->begin();
echo $field->label();
$this->widget(Captcha::className());
echo Html::activeTextInput($model, 'verifyCode', array('class' => 'input-medium'));
echo $field->error();
echo $field->end();
?>
<div class="form-actions"> <div class="form-actions">
<?php echo Html::submitButton('Submit', null, null, array('class' => 'btn btn-primary')); ?> <?php echo Html::submitButton('Submit', null, null, array('class' => 'btn btn-primary')); ?>
</div> </div>
......
...@@ -28,4 +28,11 @@ return array( ...@@ -28,4 +28,11 @@ return array(
), ),
'depends' => array('yii', 'yii/validation'), 'depends' => array('yii', 'yii/validation'),
), ),
'yii/captcha' => array(
'sourcePath' => __DIR__ . '/assets',
'js' => array(
'yii.captcha.js',
),
'depends' => array('yii'),
),
); );
...@@ -116,8 +116,8 @@ ...@@ -116,8 +116,8 @@
}); });
}, },
options: function() { data: function() {
return this.data('yiiActiveForm').settings; return this.data('yiiActiveForm');
}, },
submitForm: function () { submitForm: function () {
...@@ -384,4 +384,4 @@ ...@@ -384,4 +384,4 @@
} }
}; };
})(window.jQuery); })(window.jQuery);
\ No newline at end of file
/**
* Yii Captcha widget.
*
* This is the JavaScript widget used by the yii\widgets\Captcha widget.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
(function ($) {
$.fn.yiiCaptcha = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiCaptcha');
return false;
}
};
var defaults = {
refreshUrl: undefined,
hashKey: undefined
};
var methods = {
init: function (options) {
return this.each(function () {
var $e = $(this);
var settings = $.extend({}, defaults, options || {});
$e.data('yiiCaptcha', {
settings: settings
});
$e.on('click.yiiCaptcha', function() {
methods.refresh.apply($e);
return false;
});
});
},
refresh: function () {
var $e = this,
settings = this.data('yiiCaptcha').settings;
$.ajax({
url: $e.data('yiiCaptcha').settings.refreshUrl,
dataType: 'json',
cache: false,
success: function(data) {
$e.attr('src', data['url']);
$('body').data(settings.hashKey, [data['hash1'], data['hash2']]);
}
});
},
destroy: function () {
return this.each(function () {
$(window).unbind('.yiiCaptcha');
$(this).removeData('yiiCaptcha');
});
},
data: function() {
return this.data('yiiCaptcha');
}
};
})(window.jQuery);
...@@ -21,6 +21,7 @@ use yii\helpers\Html; ...@@ -21,6 +21,7 @@ use yii\helpers\Html;
*/ */
class CaptchaValidator extends Validator class CaptchaValidator extends Validator
{ {
public $skipOnEmpty = false;
/** /**
* @var boolean whether the comparison is case sensitive. Defaults to false. * @var boolean whether the comparison is case sensitive. Defaults to false.
*/ */
...@@ -70,7 +71,7 @@ class CaptchaValidator extends Validator ...@@ -70,7 +71,7 @@ class CaptchaValidator extends Validator
/** /**
* Returns the CAPTCHA action object. * Returns the CAPTCHA action object.
* @throws InvalidConfigException * @throws InvalidConfigException
* @return CaptchaAction the action object * @return \yii\web\CaptchaAction the action object
*/ */
public function getCaptchaAction() public function getCaptchaAction()
{ {
......
## Spicy Rice font
* **Author:** Brian J. Bonislawsky, Astigmatic (AOETI, Astigmatic One Eye Typographic Institute)
* **License:** SIL Open Font License (OFL), version 1.1, [notes and FAQ](http://scripts.sil.org/OFL)
## Links
* [Astigmatic](http://www.astigmatic.com/)
* [Google WebFonts](http://www.google.com/webfonts/specimen/Spicy+Rice)
* [fontsquirrel.com](http://www.fontsquirrel.com/fonts/spicy-rice)
* [fontspace.com](http://www.fontspace.com/astigmatic-one-eye-typographic-institute/spicy-rice)
...@@ -152,7 +152,7 @@ class ActiveField extends Component ...@@ -152,7 +152,7 @@ class ActiveField extends Component
$options['enableAjaxValidation'] = 1; $options['enableAjaxValidation'] = 1;
} }
if ($enableClientValidation || $enableAjaxValidation) { if ($enableClientValidation && !empty($options['validate']) || $enableAjaxValidation) {
$inputID = Html::getInputId($this->model, $this->attribute); $inputID = Html::getInputId($this->model, $this->attribute);
$options['name'] = $inputID; $options['name'] = $inputID;
$names = array( $names = array(
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\widgets;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\CaptchaAction;
/**
* Captcha renders a CAPTCHA image element.
*
* Captcha is used together with [[CaptchaAction]] provide [CAPTCHA](http://en.wikipedia.org/wiki/Captcha)
* - a way of preventing Website spamming.
*
* The image element rendered by Captcha will display a CAPTCHA image generated by
* an action whose route is specified by [[captchaAction]]. This action must be an instance of [[CaptchaAction]].
*
* When the user clicks on the CAPTCHA image, it will cause the CAPTCHA image
* to be refreshed with a new CAPTCHA.
*
* You may use [[\yii\validators\CaptchaValidator]] to validate the user input matches
* the current CAPTCHA verification code.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Captcha extends Widget
{
/**
* @var string the route of the action that generates the CAPTCHA images.
* The action represented by this route must be an action of [[CaptchaAction]].
*/
public $captchaAction = 'site/captcha';
/**
* @var array HTML attributes to be applied to the rendered image element.
*/
public $options = array();
/**
* Renders the widget.
*/
public function run()
{
$this->checkRequirements();
if (!isset($this->options['id'])) {
$this->options['id'] = $this->getId();
}
$id = $this->options['id'];
$options = Json::encode($this->getClientOptions());
$this->view->registerAssetBundle('yii/captcha');
$this->view->registerJs("jQuery('#$id').yiiCaptcha($options);");
$url = Yii::$app->getUrlManager()->createUrl($this->captchaAction, array('v' => uniqid()));
echo Html::img($url, $this->options);
}
/**
* Returns the options for the captcha JS widget.
* @return array the options
*/
protected function getClientOptions()
{
$options = array(
'refreshUrl' => Html::url(array($this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1)),
'hashKey' => "yiiCaptcha/{$this->captchaAction}",
);
return $options;
}
/**
* Checks if there is graphic extension available to generate CAPTCHA images.
* This method will check the existence of ImageMagick and GD extensions.
* @return string the name of the graphic extension, either "imagick" or "gd".
* @throws InvalidConfigException if neither ImageMagick nor GD is installed.
*/
public static function checkRequirements()
{
if (extension_loaded('imagick')) {
$imagick = new \Imagick();
$imagickFormats = $imagick->queryFormats('PNG');
if (in_array('PNG', $imagickFormats)) {
return 'imagick';
}
}
if (extension_loaded('gd')) {
$gdInfo = gd_info();
if (!empty($gdInfo['FreeType Support'])) {
return 'gd';
}
}
throw new InvalidConfigException('GD with FreeType or ImageMagick PHP extensions are required.');
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment