samuraiartguy

Reusable Forms reCaptcha - FormHandler.php

Feb 11th, 2022
1,606
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.97 KB | None | 0 0
  1. this is FormHandler.php
  2.  
  3. <?php
  4. namespace FormGuide\Handlx;
  5. use FormGuide\PHPFormValidator\FormValidator;
  6. use PHPMailer;
  7. use FormGuide\Handlx\Microtemplate;
  8. use Gregwar\Captcha\CaptchaBuilder;
  9.  
  10. /**
  11.  * FormHandler
  12.  *  A wrapper class that handles common form handling tasks
  13.  *      - handles Form validations using PHPFormValidator class
  14.  *      - sends email using PHPMailer
  15.  *      - can handle captcha validation
  16.  *      - can handle file uploads and attaching the upload to email
  17.  *     
  18.  *  ==== Sample usage ====
  19.  *   $fh = FormHandler::create()->validate(function($validator)
  20.  *          {
  21.  *              $validator->fields(['name','email'])
  22.  *                        ->areRequired()->maxLength(50);
  23.  *              $validator->field('email')->isEmail();
  24.  *              
  25.  *           })->useMailTemplate(__DIR__.'/templ/email.php')
  26.  *           ->sendEmailTo('[email protected]');
  27.  *          
  28.  *   $fh->process($_POST);
  29.  */
  30. class FormHandler
  31. {
  32.     private $emails;
  33.     public $validator;
  34.     private $mailer;
  35.     private $mail_template;
  36.     private $captcha;
  37.     private $attachments;
  38.     private $recaptcha;
  39.  
  40.     public function __construct()
  41.     {
  42.         $this->emails = array();
  43.         $this->validator = FormValidator::create();
  44.         $this->mailer = new PHPMailer;
  45.         $this->mail_template='';
  46.  
  47.         $this->mailer->Subject = "Contact Form Submission ";
  48.  
  49.         $host = isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost';
  50.         $from_email ='forms@'.$host;
  51.         $this->mailer->setFrom($from_email,'Juliet Stewart Contact Form',false);  
  52.  
  53.         $this->captcha = false;
  54.  
  55.         $this->attachments = [];
  56.  
  57.         $this->recaptcha =null;  /* DISABLE RECAPTCHA DISPLAY? Apparently not   default = =null;*/
  58.  
  59.  
  60.     }
  61.  
  62.     /**
  63.      * sendEmailTo: add a recipient email address
  64.      * @param  string/array $email_s one or more emails. If more than one emails, pass the emails as array
  65.      * @return The form handler object itself so that the methods can be chained
  66.      */
  67.     public function sendEmailTo($email_s)
  68.     {
  69.         if(is_array($email_s))
  70.         {
  71.             $this->emails =array_merge($this->emails, $email_s);
  72.         }
  73.         else
  74.         {
  75.             $this->emails[] = $email_s;
  76.         }
  77.        
  78.         return $this;
  79.     }
  80.  
  81.     public function useMailTemplate($templ_path)
  82.     {
  83.         $this->mail_template = $templ_path;
  84.         return $this;
  85.     }
  86.  
  87.     /**
  88.      * [attachFiles find the file uplods and attach to the email]
  89.      * @param  array $fields The array of field names
  90.       */
  91.     public function attachFiles($fields)
  92.     {
  93.         $this->attachments = array_merge($this->attachments, $fields);
  94.         return $this;
  95.     }
  96.  
  97.     public function getRecipients()
  98.     {
  99.         return $this->emails;
  100.     }
  101.  
  102.     /**
  103.      * [validate add Validations. This function takes a call back function which receives the PHPFormValidator object]
  104.      * @param  function $validator_fn The funtion gets a validator parameter using which, you can add validations
  105.      */
  106.     public function validate($validator_fn)
  107.     {
  108.         $validator_fn($this->validator);
  109.         return $this;
  110.     }
  111.  
  112.     public function requireReCaptcha($config_fn=null)
  113.     {
  114.         $this->recaptcha = new ReCaptchaValidator();
  115.         $this->recaptcha->enable(true);
  116.         if($config_fn)
  117.         {
  118.             $config_fn($this->recaptcha);  
  119.         }
  120.         return $this;
  121.     }
  122.     public function getReCaptcha()
  123.     {
  124.         return $this->recaptcha;
  125.     }
  126.  
  127.     public function requireCaptcha($enable=true)
  128.     {
  129.         $this->captcha = $enable;
  130.         return $this;
  131.     }
  132.  
  133.     public function getValidator()
  134.     {
  135.         return $this->validator;
  136.     }
  137.  
  138.     public function configMailer($mailconfig_fn)
  139.     {
  140.         $mailconfig_fn($this->mailer);
  141.         return $this;
  142.     }
  143.  
  144.     public function getMailer()
  145.     {
  146.         return $this->mailer;
  147.     }
  148.  
  149.     public static function create()
  150.     {
  151.         return new FormHandler();
  152.     }
  153.  
  154.     public function process($post_data)
  155.     {
  156.         if($this->captcha === true)
  157.         {
  158.             $res = $this->validate_captcha($post_data);
  159.             if($res !== true)
  160.             {
  161.                 return $res;
  162.             }
  163.         }
  164.         if($this->recaptcha !== null &&
  165.            $this->recaptcha->isEnabled())
  166.         {
  167.             if($this->recaptcha->validate() !== true)
  168.             {
  169.                 return json_encode([
  170.                 'result'=>'recaptcha_validation_failed',
  171.                 'errors'=>['captcha'=>'ReCaptcha Validation Failed.']
  172.                 ]);
  173.             }
  174.         }
  175.  
  176.         $this->validator->test($post_data);
  177.  
  178.         //if(false == $this->validator->test($post_data))
  179.         if($this->validator->hasErrors())
  180.         {
  181.             return json_encode([
  182.                 'result'=>'validation_failed',
  183.                 'errors'=>$this->validator->getErrors(/*associative*/ true)
  184.                 ]);
  185.         }
  186.  
  187.         if(!empty($this->emails))
  188.         {
  189.             foreach($this->emails as $email)
  190.             {
  191.                 $this->mailer->addAddress($email);
  192.             }
  193.             $this->compose_mail($post_data);
  194.  
  195.             if(!empty($this->attachments))
  196.             {
  197.                 $this->attach_files();
  198.             }
  199.  
  200.             if(!$this->mailer->send())
  201.             {
  202.                 return json_encode([
  203.                     'result'=>'error_sending_email',
  204.                     'errors'=> ['mail'=> $this->mailer->ErrorInfo]
  205.                     ]);        
  206.             }
  207.         }
  208.        
  209.         return json_encode(['result'=>'success']);
  210.     }
  211.  
  212.     private function validate_captcha($post)
  213.     {
  214.         @session_start();
  215.         if(empty($post['captcha']))
  216.         {
  217.             return json_encode([
  218.                         'result'=>'captcha_error',
  219.                         'errors'=>['captcha'=>'Captcha code not entered']
  220.                         ]);
  221.         }
  222.         else
  223.         {
  224.             $usercaptcha = trim($post['captcha']);
  225.  
  226.             if($_SESSION['user_phrase'] !== $usercaptcha)
  227.             {
  228.                 return json_encode([
  229.                         'result'=>'captcha_error',
  230.                         'errors'=>['captcha'=>'Captcha code does not match']
  231.                         ]);    
  232.             }
  233.         }
  234.         return true;
  235.     }
  236.  
  237.  
  238.     private function attach_files()
  239.     {
  240.        
  241.         foreach($this->attachments as $file_field)
  242.         {
  243.             if (!array_key_exists($file_field, $_FILES))
  244.             {
  245.                 continue;
  246.             }
  247.             $filename = $_FILES[$file_field]['name'];
  248.  
  249.             $uploadfile = tempnam(sys_get_temp_dir(), sha1($filename));
  250.  
  251.             if (!move_uploaded_file($_FILES[$file_field]['tmp_name'],
  252.                 $uploadfile))
  253.             {
  254.                 continue;
  255.             }
  256.  
  257.             $this->mailer->addAttachment($uploadfile, $filename);
  258.         }
  259.     }
  260.  
  261.     private function compose_mail($post)
  262.     {
  263.         $content = "Form submission: \n\n";
  264.         foreach($post as $name=>$value)
  265.         {
  266.             $content .= ucwords($name).":\n";
  267.             $content .= "$value\n\n";
  268.         }
  269.         $this->mailer->Body  = $content;
  270.     }
  271. }
Advertisement
Add Comment
Please, Sign In to add comment