验证码插件
本部分描述了如何开发验证码插件。
验证码插件的工作原理如下:插件在 `onCaptchaSetup` 事件中注册验证码提供程序,然后系统将根据全局配置中选择的内容以及表单中验证码字段的配置方式来使用它。
此组中的事件:
onCaptchaSetup
onCaptchaSetup
事件签名
function onCaptchaSetup(Joomla\CMS\Event\Captcha\CaptchaSetupEvent $event){}
事件属性
/**
* @var Joomla\CMS\Captcha\CaptchaRegistry $subject
*/
$subject = $event->getCaptchaRegistry();
创建验证码插件
验证码插件包含两个主要部分
- 验证码提供程序类,它提供用于渲染输入和验证的验证码逻辑。
- 验证码组中的插件,它注册提供程序,以便系统知道它的存在。
以下示例假设您已经知道如何创建 Joomla 插件。
让我们创建一个简单的 蜜罐 验证码。
首先,在 `plugins/captcha/honeypot/` 文件夹下创建一个插件,命名为 `honeypot`,假设命名空间为 `JoomlaExample\Plugin\Captcha\Honeypot`。
然后创建一个蜜罐验证码提供程序,它将位于 `plugins/captcha/honeypot/src/Provider/HoneypotCaptchaProvider.php` 下。
namespace JoomlaExample\Plugin\Captcha\Honeypot\Provider;
use Joomla\CMS\Captcha\CaptchaProviderInterface;
use Joomla\CMS\Form\FormField;
/**
* Provider for Honeypot Captcha
*/
final class HoneypotCaptchaProvider implements CaptchaProviderInterface
{
/**
* Return Captcha name, CMD string.
*
* @return string
*/
public function getName(): string
{
return 'honeypot';
}
/**
* Render the captcha input
*
* @param string $name Input name given in the form
* @param array $attributes The class of the field and other attributes, from the form.
*
* @return string The HTML to be embedded in the form
*
* @throws \RuntimeException
*/
public function display(string $name = '', array $attributes = []): string
{
return '<input type="hidden" value="" name="' . $name . '" id="' . ($attributes['id'] ?? '') . '" class="' . ($attributes['class'] ?? '') . '"/>';
}
/**
* Validate the input data
*
* @param string $code Answer provided by user
*
* @return bool If the answer is correct, false otherwise
*
* @throws \RuntimeException
*/
public function checkAnswer(string $code = null): bool
{
return !$code;
}
/**
* Method to react on the setup of a captcha field. Gives the possibility
* to change the field and/or the XML element for the field.
*
* @param FormField $field Captcha field instance
* @param \SimpleXMLElement $element XML form definition
*
* @return void
*
* @throws \RuntimeException
*/
public function setupField(FormField $field, \SimpleXMLElement $element): void
{
// Hide the label for this captcha type
$element['hiddenLabel'] = 'true';
}
}
使用插件和事件在系统中注册提供程序
namespace JoomlaExample\Plugin\Captcha\Honeypot\Extension;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Event\SubscriberInterface;
use JoomlaExample\Plugin\Captcha\Honeypot\Provider\HoneypotCaptchaProvider;
final class HoneypotCaptcha extends CMSPlugin implements SubscriberInterface
{
/**
* Returns an array of events this plugin will listen to.
*
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'onCaptchaSetup' => 'onCaptchaSetup',
];
}
/**
* Register Captcha instance
*
* @param CaptchaSetupEvent $event
*
* @return void
*/
public function onCaptchaSetup(CaptchaSetupEvent $event)
{
$event->getCaptchaRegistry()->add(new HoneypotCaptchaProvider());
}
}
一切就绪 🎉 插件安装并启用后,此新验证码将在全局配置中可用。