flydev

Markup Google reCAPTCHA

Recommended Posts

MarkupGoogleRecaptcha

Google reCAPTCHA for ProcessWire.

This module simply adds reCAPTCHA V2 or Invisible reCAPTCHA to your form.


How To Install

  1. Download the zip file at Github or from the modules repository
  2. Drop the module files in /site/modules/MarkupGoogleRecaptcha
  3. In your admin, click Modules > Refresh
  4. Click "install" for "MarkupGoogleRecaptcha"

Official install/uninstall doc: http://modules.processwire.com/install-uninstall/

 

API

You must create an API key prior to use this module. Goto https://www.google.com/recaptcha/admin to create your own. Next, add the API keys information to the module's settings.

api.thumb.png.b0775a282bf6a51d48816dc347d9ae35.png

 

Usage

  1. Call the module : $captcha = $modules->get("MarkupGoogleRecaptcha");
  2. Call $captcha->getScript(); somewhere to get the javascript used by reCAPTCHA
  3. Render reCAPTCHA in a standard HTML <form></form> by calling $captcha->render() or Render reCAPTCHA in an InputfieldForm by passing as argument your form to the render function: $captcha->render($form)
  4. Call verifyResponse() to get the result. It return TRUE if the challenge was successful.

 

Example

  • Using ProcessWire's form API :
$out = '';

$captcha = $modules->get("MarkupGoogleRecaptcha");
// if submitted, check response
if ($captcha->verifyResponse() === true)
{
    $out .= "Hi " . $input->post["name"].", thanks for submitting the form!";
}
else
{
    $form = $modules->get("InputfieldForm");
    $form->action = $page->url;
    $form->method = "post";
    $form->attr("id+name", "form");

    $field = $this->modules->get('InputfieldText');
    $field->name = "name";
    $field->placeholder = "name";
    $form->add($field);

    // CAPTCHA - our form as argument, the function will add an InputfieldMarkup to our form
    $captcha->render($form);

    // add a submit button
    $submit = $this->modules->get("InputfieldSubmit");
    $submit->name = "submit";
    $submit->value = 'Submit';
    $form->add($submit);

    $out .= $form->render();

    // include javascript 
    $out .= $captcha->getScript();
}



echo $out;

 

  • Example using plain HTML Form :
$captcha = $modules->get("MarkupGoogleRecaptcha");
// if submitted check response
if ($captcha->verifyResponse() === true) {
	$out .= "Hi " . $input->post["name"] . ", thanks for submitting the form!";
} else {
	$out .= "<form method='post' action='{$page->url}'>\n"
         . "\t<input type='text' name='name'>\n"
         . $captcha->render() // render reCaptcha
         . "\t<input type='submit'>\n"
         . "</form>\n";

	$out .= $captcha->getScript();
}

echo $out;

 

 

captcha.thumb.png.68d131c777de7c108ef831fdb87c1c39.png

Edited by flydev
Update
  • Like 9

Share this post


Link to post
Share on other sites

Hey,

I'm trying out this module on my site but for $captcha->verifyResponse() I am getting 1 not true?

I am workong on localhost which I have added to the domaine list with google so maybe thats the problem?

Thanks

Gar

Share this post


Link to post
Share on other sites

okay put it live and now getting

Parse error: syntax error, unexpected '[' in /var/www/vhosts/web1.plus-h.de/httpdocs/plus-h.de/site/assets/cache/FileCompiler/site/modules/MarkupGoogleRecaptcha/MarkupGoogleRecaptcha.module on line 6

Parse Error: syntax error, unexpected '[' (line 6 of /var/www/vhosts/web1.plus-h.de/httpdocs/plus-h.de/site/modules/MarkupGoogleRecaptcha/MarkupGoogleRecaptcha.module)

This error message was shown because: site is in debug mode. ($config->debug = true; => /site/config.php). Error has been logged.

Share this post


Link to post
Share on other sites

Looks like you're running PHP 5.3 on the live system. You could fix this error by replacing the short array notation [...] used throughout the module with its verbose notation as array(...), but you should really think of switching to a more current PHP release.

  • Like 5

Share this post


Link to post
Share on other sites

I have a pull-request for this module, pull-request adding multi language support to reCAPTCHA and multiple usage on one page. You can see usage on screenshot.

For set reCAPTCHA language, (reCAPTCHA Language Codes) :

<?php if(modules()->isInstalled('MarkupGoogleRecaptcha')) { echo modules()->MarkupGoogleRecaptcha->render($lang = "en"); }; ?>

For multiple reCAPTCHA usage, after all form render, call multiple usage script :

<?php if(modules()->isInstalled('MarkupGoogleRecaptcha')) { echo modules()->MarkupGoogleRecaptcha->getScriptMulti(); }; ?>

 

  • Like 2

Share this post


Link to post
Share on other sites

Good day!

Thank you @flydev for the very useful module and @ukyo for making it possible to have multiple instances of reCAPCHA on the same page.

I am having just that: two forms on the same page both with reCAPCHA via the module. Both work using jQuery ajax. After an unsuccessful call I get response with error messages. Right here I need to reset reCAPCHA like described here in the JavaScript API section. But as I have two instances of reCAPCHA on the page I need to explicitly specify the opt_widget_id option. Is there a way to I get it with the module?

Share this post


Link to post
Share on other sites

You have an option, don't call getScriptMulti(); function.

<?php if(modules()->isInstalled('MarkupGoogleRecaptcha')) { echo modules()->MarkupGoogleRecaptcha->getScriptMulti(); }; ?>

Write your own javascript by referencing getScriptMulti(); function.

    public function getScriptMulti() {
        $return = "<script type=\"text/javascript\">
                    var onloadReCaptchaCallback = function(){
                        jQuery('.g-recaptcha').each(function() {
                            var _this = jQuery(this);
                            var recaptchaID = _this.data('id'),
                                hl = _this.data('hl'),
                                sitekey = _this.data('sitekey'),
                                theme = _this.data('theme'),
                                type = _this.data('type'),
                                size = _this.data('size'),
                                index = _this.data('index');
                            if(recaptchaID !== undefined) {
                                var recaptchaWidget = grecaptcha.render(recaptchaID, {
                                    'hl' : hl,
                                    'sitekey' : sitekey,
                                    'theme' : theme,
                                    'type' : type,
                                    'size' : size,
                                    'index' : index
                                });
                                grecaptcha.getResponse(recaptchaWidget);
                                // grecaptcha.reset(recaptchaWidget);
                            }
                        });
                    };
                </script>";
        $return .= "<script src='".self::SITE_RECAPTCHA_API_URL."?onload=onloadReCaptchaCallback&render=explicit' async defer></script>";

        return $return;
    }

 

  • Like 2

Share this post


Link to post
Share on other sites

Just bumped the module to version 2.

- Added  Google Invisible reCAPTCHA.

 

To use it, no change is necessary on the frontend, you just have to configure the module to use reCAPTCHA V2 or Invisible reCAPTCHA.

I will update the readme to reflect the change made by @ukyo and the new available options.

 

  • Like 3

Share this post


Link to post
Share on other sites

@Lyndaa,

Moderator note

I have removed the link from your post. We do not allow links to third parties for first posters. This is to discourage spam (including subtle advertising). In fact, I don't see how your post is related to ProcessWire at all. I will revisit this and remove your post altogether unless you can otherwise show how it is related to ProcessWire.

  • Like 1

Share this post


Link to post
Share on other sites

I am wondering to add the reCAPTCHA to the login form of the Login-Register module.

I tried to make it by using the MarkupGoogleRecaptcha API in a hook, but without success:

// ready.php file
wire()->addHookAfter('LoginRegister::buildLoginForm', function($event) {

  $form = $event->return;

  // call the module and render reCAPTCHA
  $captcha = wire('modules')->get("MarkupGoogleRecaptcha");
  $captcha->render($form);

  // add JavaScript to the form
  $js = $captcha->getScript();
  // ... str_replace("</form>", "{$js}</form>", $form);

  // Call verifyResponse() to get the result.
  // ...

  $event->return = $form;

});

Furthermore, I do know if it is possible to add reCAPTCHA from within a hook.

Can someone help me in adding the reCAPTCHA to the login form of the Login-Register module?

Share this post


Link to post
Share on other sites

Hi @LAPS

try the following :  In ready.php put the following code :

$captchaobj = null;

    wire()->addHookProperty('LoginRegister::captcha', function ($event) {
        $event->return = wire('modules')->get("MarkupGoogleRecaptcha");
    });

    wire()->addHookAfter('LoginRegister::buildLoginForm', function ($event) {
        /* @var $form InputfieldForm */
        $obj = $event->object;
        $form = $event->return;
        $form->description = false; // remove the description
        $f = new InputfieldMarkup();
        $f->markupText = $obj->captcha->render();
        foreach ($form->children as $field) {
            if ($field instanceof InputfieldSubmit) { // find the submit button
                $form->insertBefore($f, $field);      // insert reCAPTCHA before the submit button
            }
        }

        $event->return = $form;
    });

    wire()->addHookBefore('LoginRegister::processLoginForm', function ($event) use (&$captchaobj) {
        $obj = $event->object;
        $captchaobj = $obj->captcha;
    });

    wire()->addHookBefore('Session::login', function ($event) use (&$captchaobj) {
        if (!is_null($captchaobj) && $captchaobj->verifyResponse() == false) {
            $event->arguments(0, '');
            $event->arguments(1, '');
            $event->arguments(2, false);
            $event->return = false;
        }
    });

 

Just one thing, I couldn't get the invisible mode to work with LoginRegister, only the reCAPTCHA v2.

edit:  a small hint about the getScript() :  you should call it from the main file, I mean, your "index.php" and only if the user isn't loggedin.

if(!$user->isLoggedin()) {
	echo $modules->get("MarkupGoogleRecaptcha")->getScript();
}

 

  • Like 1
  • Haha 1

Share this post


Link to post
Share on other sites

Hi @flydev,

thank you for you reply.

However, your code seems do not work. In particular, it seems do not output the JavaScript-related code ($captcha->getScript()). Can be this the problem?

Note: I am testing MarkupGoogleRecaptcha in localhost, so in Google Admin I added the domains 'localhost' and '127.0.0.1'.

LoginRegister form.png

Share this post


Link to post
Share on other sites
3 minutes ago, LAPS said:

In particular, it seems do not output the JavaScript-related code ($captcha->getScript()). Can be this the problem?

Yes it is. Read my last edit in my previous post.

 

Localhost for testing is fine, no problem with that.

Share this post


Link to post
Share on other sites

@flydev,

Thank you for your hint. Now the reCAPTCHA is visible in the login form (see the attached image).

However, even when submitting the correct user credentials, I get always the "Login failed" message. What's wrong?

LoginRegister form.png

Share this post


Link to post
Share on other sites

Good, now I think that your google challenge is not successful. Be sure that you saved the changes in your list of supported domains once you added the localhost.

 

Anything in the developer console ?

Share this post


Link to post
Share on other sites
12 minutes ago, flydev said:

Good, now I think that your google challenge is not successful. Be sure that you saved the changes in your list of supported domains once you added the localhost.

In Google Admin I set 'localhost' and '127.0.0.1' (see attached image).

I tried to submit the login form from both 'http://localhost:8888/login' and 'http://127.0.0.1:8888/login' without success: I get the "Login failed" message.

 

Note: If it can help, in Google Admin I cannot set 'localhost:8888' nor '127.0.0.1:8888' since I get the error "URL starts with an invalid scheme".

Domains.png

Share this post


Link to post
Share on other sites

Did the challenge work ? I mean, the reCapatcha widget is "green-checked" ?

To be sure that the problem is not in the code I give you (I am currently using the same snippet on a website) ,  you should try to get the challenge working on a regular module call in a regular form. Can you test it  and report back ?

Share this post


Link to post
Share on other sites
14 minutes ago, flydev said:

Did the challenge work ? I mean, the reCapatcha widget is "green-checked" ?

Yes, the reCapatcha widget is "green-checked".

14 minutes ago, flydev said:

To be sure that the problem is not in the code I give you (I am currently using the same snippet on a website) ,  you should try to get the challenge working on a regular module call in a regular form. Can you test it  and report back ?

I tested it in a regular form, and it works as expected. It does not work just for the Login-Register login form.

Share this post


Link to post
Share on other sites

Thank you - I will check, as now, I don't know why isn't working :lol:

  • Like 2

Share this post


Link to post
Share on other sites
5 hours ago, flydev said:

Thank you - I will check, as now, I don't know why isn't working :lol:

OK, we are close to the solution.

If it can help, I am using:

  • ProcessWire v3.0.62
  • Login/Register v0.0.2 with option "Features to use" set to all (including "Use email address for login rather that user name") and option "Profile form fields" set to "E-mail Address (required)" and "Set Password (required)" more "First name" and "Last name".

Furthermore, after the login form submission (failed) in the Session logs I get these 2 rows:

2 seconds ago --- Error: Failed login for '' - Unknown user:
2 seconds ago --- Error: Failed login for 'my_email-email.com' - Unknown user: my_email-email.com

 

  • Like 2

Share this post


Link to post
Share on other sites

Hi @flydev. Great module. I'm using it on a custom form. I'd like to add it to an existing site where I've used Ryan's Form Template Processor module. (It's a long form; I'd rather not start from scratch). I've had a look at what you did with the log in form above; would I take a similar approach? Is there an easy way to slot the Captcha form in before the submit button (instead of outside the generated form)? I'm pretty new to hooks, if that's what's needed. Any suggestions appreciated.

  • Thanks 1

Share this post


Link to post
Share on other sites

hi @strandoo thanks you.

 

I never used the module you are talking about but I read the module code on Github and it look like you can insert the ReCaptcha before the submit button by hooking into the function ___buildForm().

Please try the following (not tested) and let me know. In ready.php put :

wire()->addHookAfter('FormTemplateProcessor::buildForm', function ($event) {
        /* @var $form InputfieldForm */
        $form = $event->return;
        $f = new InputfieldMarkup();
        $f->markupText = wire('modules')->get("MarkupGoogleRecaptcha")->render();
        foreach ($form->children as $field) {
            if ($field instanceof InputfieldSubmit) { // find the submit button
                $form->insertBefore($f, $field);      // insert reCAPTCHA before the submit button
            }
        }

        $event->return = $form;
    });

 

Share this post


Link to post
Share on other sites

Hi @flydev My, that was quick! I did put this in my ready.php file, but don't see a captcha. Do I need to include your '$captcha = $modules->get("MarkupGoogleRecaptcha");' on the page? (I've tried it both ways). I've also tried this $f->markupText = 'Foobar'; (instead of your module) and 'Foobar' appears above the submit button, as expected.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Macrura
      Field Descriptions Extended
      This module enables you to extend field descriptions by dividing short descriptions with a longer text that is revealed in a toggle.
      Modules Directory: http://modules.processwire.com/modules/field-descriptions-extended/
      Github: https://github.com/outflux3/FieldDescriptionsExtended
      Extending your field descriptions using the standard field's description field.
      Once this module is installed, it will automatically search your description field for the presence of 5 dashes (-----).
      Any content above the 5 dashes will be visible and the content below the dashes will be hidden. A 'More...' link will appear at the end of the short description which when clicked will reveal the rest of the description.
      Using Simple Markdown Editor with the description field
      If you have Simple Markdown Editor (InputfieldSimpleMDE) installed, you can enable the field description to have that editor.
      *When using Simple MDE, you can use the button (Insert Horizontal Line) instead of typing 5 dashes. More about SimpleMDE.
      Extending your field descriptions using content from a ProcessWire Page for the field description.
      You may use the content from a ProcessWire page as a field description. This would allow you to easily insert images, links, and use hanna codes.
      To use page content for your field descriptions, please follow these instructions:
      Install Select Fields module (FieldtypeFields) http://modules.processwire.com/modules/fieldtype-fields/ Create a new field using this field type, e.g. field_select. Add the field to any template you will be using for your field descriptions. Setup your help pages (for example under a settings branch) where you will store the field description content,using the template containing the Field Select. Add content to a page and select the field where that content should show. To show a short text before the link to the longer content, separate them with 5 dashes Be sure to update your settings on this page, first enable page content descriptions,then specify the name of the Select Fields field, template to search, and content field. If you create a field description using this method, please note that the description field must be blank for contexts where you want the page content to appear.
      You can freely use template context for field descriptions, but the Page Content method is not context sensitive and will display under all contexts where the description is blank.
      ----
      original post:
      This is a new module, hope to release soon, which allows extended field descriptions, in currently 2 ways.
      The main feature of the module is that you can have a short description and then a 'more...' link which drops down a longer block of text.
      This is achieved by separating the intro/visible text and the rest with 5 dashes.

      Example setup:

      the 2nd way is if you are using AdminThemeUiKit, you can show extended field instructions in a panel. The content of the panel is edited on a regular PW page. This use case would probably not be that common, but if you had a field that required some extended instructions for how to use, this could be useful; Also, since this allows you to target information and instructions down at the field level, it could reduce the amount of documentation needed on a global level, since it is a lot more context targeted.

    • By Robin S
      Breadcrumb Dropdowns
      Adds dropdown menus of page edit links to the breadcrumbs in Page Edit.

      Installation
      Install the Breadcrumb Dropdowns module. The module requires ProcessWire >= v3.0.83 and AdminThemeUikit.
      There is a checkbox option in the module config that determines if the breadcrumb dropdowns will include pages that the user does not have permission to edit.
      Features/details
      The module adds an additional breadcrumb item at the end for the currently edited page. That's because I think it's more intuitive for the dropdown under each breadcrumb item to show the item's sibling pages rather than the item's child pages. In the dropdown menus the current page and the current page's parents are highlighted in a crimson colour to make it easier to quickly locate them in case you want to edit the next or previous sibling page. If the option to include uneditable pages is selected then those pages are indicated by a reduced text opacity and the "not-allowed" cursor is shown on hover. There is a limit of 25 sibling pages per dropdown for performance reasons and to avoid the dropdown becoming unwieldy. Incompatibilities
      This module replaces the AdminThemeUikit::renderBreadcrumbs method so will potentially be incompatible with other modules that hook the same method.
       
      https://modules.processwire.com/modules/breadcrumb-dropdowns/
      https://github.com/Toutouwai/BreadcrumbDropdowns
    • By joshuag
      Hey guys, 
      Thought I would share a quick preview of Designme. A module we (Eduardo @elabx and I) are building for visually laying out your templates/edit screens. 🙂
      This is a really quick, zero polish screen grab. FYI. 
      Video #2 - UPDATE
      This new video shows the following features in Designme:
      Re-arranging fields via Drag & Drop Re-sizing fields via Dragging. Adjusting field settings - with live refresh. Working on "hidden" fields while Designme is active. Creating New fields. Deleting fields. Creating/Deleting Tabs. Dragging fields between tabs. Creating fieldsets. Tagging/Un-tagging fields. Fields without headers expand when hovered (like checkboxes). Live filtering of fields in the sidebar. Ability to adjust (all) Template settings without leaving Designme. Template File Tree Editing Template files source code with ACE Editor. Editing Multiple files with ACE Editor. (New Tabs) Saving files. Techie stuff Fields load their own js/css dependancies. *ready to use on creation (*most fields)  Everything happens via Ajax to ProcessPageEdit (via module + hooks). Designme has a JS api that you can use.  All actions trigger events.  We would love any detailed feedback on what you see so far. If you are interested in testing Designme. Let me know below. 🙂
       
       
      Video #1. 
       
    • By dreerr
      TemplateEnginePug (formally TemplateEngineJade)
       
      This module adds Pug templates to the TemplateEngineFactory. It uses https://github.com/pug-php/pug to render templates.
      doctype html html(lang='en') head meta(http-equiv='content-type', content='text/html; charset=utf-8') title= $page->title link(rel='stylesheet', type='text/css', href=$config->urls->templates . 'styles/main.css') body include header.pug h1= $page->title if $page->editable() p: a(href=$page->editURL) Edit Project on GitHub: github.com/dreerr/TemplateEnginePug
      Project in modules directory: modules.processwire.com/modules/template-engine-pug/
       
      For common problems/features/questions about the Factory, use the TemplateEngineFactory thread.
       
    • By tpr
      ProcessNetteTester
      Run Nette Tester tests within ProcessWire admin.
      (continued from here)

      Features
      AJAX interface for running Nette Tester tests, in bulk or manually display counter, error message and execution time in a table run all tests at once or launch single tests show formatted test error messages and report PHP syntax errors stop on first failed test (optional) hide passed tests (optional) display failed/total instead passed/total (optional) re-run failed tests only (optional) auto scroll (optional) include or exclude tests based on query parameters start/stop all tests with the spacebar reset one test or all tests (ctrl+click) https://modules.processwire.com/modules/process-nette-tester/
      https://github.com/rolandtoth/ProcessNetteTester