Advertisement
jasteele123

concrete5 telephone form validation

May 5th, 2013
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.12 KB | None | 0 0
  1. <?php /* blocks/form/controller.php - overrides concrete/core/controllers/blocks/form.php */
  2. defined('C5_EXECUTE') or die('Access Denied.');
  3.  
  4. class FormBlockStatistics extends Concrete5_Controller_Block_FormStatistics {}
  5. class MiniSurvey extends Concrete5_Controller_Block_FormMinisurvey {}
  6.  
  7. /**
  8.  * Overrides the core form block controller to validate telephone input type
  9.  * Allows almost any format, validates by checking the minimum number of digits
  10.  * @see const MIN_PHONE_LEN below
  11.  * @author John Steele <jasteele12+c5 @ gmail dot com>
  12.  * // original location: concrete/core/controllers/blocks/form.php
  13.  * // override location: blocks/form/conroller.php
  14.  */
  15. class FormBlockController extends Concrete5_Controller_Block_Form {
  16.  
  17. // J.S.
  18.     const MIN_PHONE_LEN = 10;   // US ###-###-####, (###) ###-####, ##########, non-US is 7 (I believe)
  19.  
  20.     private function _valid_phone($str) {
  21.         $ret = false;
  22.         $justNumbers = preg_replace('/\D/', '', $str);  // strip any non-digits
  23.         if(strlen($justNumbers) >= self::MIN_PHONE_LEN) {
  24.             $ret = true;
  25.         }
  26.             // Log::AddEntry('str: '. $str. ', len: '. strlen($justNumbers). ', MIN: '. self::MIN_PHONE_LEN, 'telephone_test');
  27.         return $ret;
  28.     }
  29. // /J.S.
  30.  
  31.     //users submits the completed survey
  32.     function action_submit_form() {
  33.    
  34.         $ip = Loader::helper('validation/ip');
  35.         Loader::library("file/importer");
  36.        
  37.         if (!$ip->check()) {
  38.             $this->set('invalidIP', $ip->getErrorMessage());           
  39.             return;
  40.         }  
  41.  
  42.         $txt = Loader::helper('text');
  43.         $db = Loader::db();
  44.        
  45.         //question set id
  46.         $qsID=intval($_POST['qsID']);
  47.         if($qsID==0)
  48.             throw new Exception(t("Oops, something is wrong with the form you posted (it doesn't have a question set id)."));
  49.            
  50.         //get all questions for this question set
  51.         $rows=$db->GetArray("SELECT * FROM {$this->btQuestionsTablename} WHERE questionSetId=? AND bID=? order by position asc, msqID", array( $qsID, intval($this->bID)));
  52.  
  53.         // check captcha if activated
  54.         if ($this->displayCaptcha) {
  55.             $captcha = Loader::helper('validation/captcha');
  56.             if (!$captcha->check()) {
  57.                 $errors['captcha'] = t("Incorrect captcha code");
  58.                 $_REQUEST['ccmCaptchaCode']='';
  59.             }
  60.         }
  61.        
  62.         //checked required fields
  63.         foreach($rows as $row){
  64.             if ($row['inputType']=='datetime'){
  65.                 if (!isset($datetime)) {
  66.                     $datetime = Loader::helper("form/date_time");
  67.                 }
  68.                 $translated = $datetime->translate('Question'.$row['msqID']);
  69.                 if ($translated) {
  70.                     $_POST['Question'.$row['msqID']] = $translated;
  71.                 }
  72.             }
  73. // J.S.
  74. /*
  75.             Log::AddEntry('inputType: '. $row['inputType'].
  76.                           ', Question'. $row['msqID']. ': '. $_POST['Question'. $row['msqID']], 'telephone_test');
  77. */
  78.                 // if anything entered, check minimum # of digits (required or not)
  79.             if ($row['inputType'] == 'telephone' &&
  80.                 strlen(trim($_POST['Question'. $row['msqID']])) &&
  81.                 !$this->_valid_phone($_POST['Question'. $row['msqID']])) {
  82.                 $errors['telephone'] = t('You must enter at least %s telephone digits', self::MIN_PHONE_LEN);
  83.             }
  84. // /J.S.
  85.             if( intval($row['required'])==1 ){
  86.                 $notCompleted=0;
  87. // J.S.
  88.                     // if telephone required, check minimum # of digits
  89.                 if ($row['inputType'] == 'telephone' &&
  90.                     !$this->_valid_phone($_POST['Question'. $row['msqID']])) {
  91.                     $errors['telephone'] = t('You must enter at least %s telephone digits', self::MIN_PHONE_LEN);
  92.                 }
  93. // /J.S.
  94.                 if ($row['inputType'] == 'email') {
  95.                     if (!Loader::helper('validation/strings')->email($_POST['Question' . $row['msqID']])) {
  96.                         $errors['emails'] = t('You must enter a valid email address.');
  97.                     }
  98.                 }
  99.                 if($row['inputType']=='checkboxlist'){
  100.                     $answerFound=0;
  101.                     foreach($_POST as $key=>$val){
  102.                         if( strstr($key,'Question'.$row['msqID'].'_') && strlen($val) ){
  103.                             $answerFound=1;
  104.                         }
  105.                     }
  106.                     if(!$answerFound) $notCompleted=1;
  107.                 }elseif($row['inputType']=='fileupload'){      
  108.                     if( !isset($_FILES['Question'.$row['msqID']]) || !is_uploaded_file($_FILES['Question'.$row['msqID']]['tmp_name']) )                
  109.                         $notCompleted=1;
  110.                 }elseif( !strlen(trim($_POST['Question'.$row['msqID']])) ){
  111.                     $notCompleted=1;
  112.                 }
  113.                 if($notCompleted) $errors['CompleteRequired'] = t("Complete required fields *") ;
  114.             }
  115.         }
  116.        
  117.         //try importing the file if everything else went ok
  118.         $tmpFileIds=array();   
  119.         if(!count($errors)) foreach($rows as $row){
  120.             if( $row['inputType']!='fileupload' ) continue;
  121.             $questionName='Question'.$row['msqID'];            
  122.             if  ( !intval($row['required']) &&
  123.                     (
  124.                     !isset($_FILES[$questionName]['tmp_name']) || !is_uploaded_file($_FILES[$questionName]['tmp_name'])
  125.                     )
  126.                 ){
  127.                     continue;
  128.             }
  129.             $fi = new FileImporter();
  130.             $resp = $fi->import($_FILES[$questionName]['tmp_name'], $_FILES[$questionName]['name']);
  131.             if (!($resp instanceof FileVersion)) {
  132.                 switch($resp) {
  133.                     case FileImporter::E_FILE_INVALID_EXTENSION:
  134.                         $errors['fileupload'] = t('Invalid file extension.');
  135.                         break;
  136.                     case FileImporter::E_FILE_INVALID:
  137.                         $errors['fileupload'] = t('Invalid file.');
  138.                         break;
  139.                    
  140.                 }
  141.             }else{
  142.                 $tmpFileIds[intval($row['msqID'])] = $resp->getFileID();
  143.                 if(intval($this->addFilesToSet)) {
  144.                     Loader::model('file_set');
  145.                     $fs = new FileSet();
  146.                     $fs = $fs->getByID($this->addFilesToSet);
  147.                     if($fs->getFileSetID()) {
  148.                         $fs->addFileToSet($resp);
  149.                     }
  150.                 }
  151.             }
  152.         }
  153.        
  154.         if(count($errors)){        
  155.             $this->set('formResponse', t('Please correct the following errors:') );
  156.             $this->set('errors',$errors);
  157.             $this->set('Entry',$E);        
  158.         }else{ //no form errors        
  159.             //save main survey record  
  160.             $u = new User();
  161.             $uID = 0;
  162.             if ($u->isRegistered()) {
  163.                 $uID = $u->getUserID();
  164.             }
  165.             $q="insert into {$this->btAnswerSetTablename} (questionSetId, uID) values (?,?)";
  166.             $db->query($q,array($qsID, $uID));
  167.             $answerSetID=$db->Insert_ID();
  168.             $this->lastAnswerSetId=$answerSetID;
  169.            
  170.             $questionAnswerPairs=array();
  171.  
  172.             if( strlen(FORM_BLOCK_SENDER_EMAIL)>1 && strstr(FORM_BLOCK_SENDER_EMAIL,'@') ){
  173.                 $formFormEmailAddress = FORM_BLOCK_SENDER_EMAIL;
  174.             }else{
  175.                 $adminUserInfo=UserInfo::getByID(USER_SUPER_ID);
  176.                 $formFormEmailAddress = $adminUserInfo->getUserEmail();
  177.             }
  178.             $replyToEmailAddress = $formFormEmailAddress;
  179.             //loop through each question and get the answers
  180.             foreach( $rows as $row ){  
  181.                 //save each answer
  182.                 if($row['inputType']=='checkboxlist'){
  183.                     $answer = Array();
  184.                     $answerLong="";
  185.                     $keys = array_keys($_POST);
  186.                     foreach ($keys as $key){
  187.                         if (strpos($key, 'Question'.$row['msqID'].'_') === 0){
  188.                             $answer[]=$txt->sanitize($_POST[$key]);
  189.                         }
  190.                     }
  191.                 }elseif($row['inputType']=='text'){
  192.                     $answerLong=$txt->sanitize($_POST['Question'.$row['msqID']]);
  193.                     $answer='';
  194.                 }elseif($row['inputType']=='fileupload'){
  195.                      $answer=intval( $tmpFileIds[intval($row['msqID'])] );
  196.                 }elseif($row['inputType']=='url'){
  197.                     $answerLong="";
  198.                     $answer=$txt->sanitize($_POST['Question'.$row['msqID']]);
  199.                 }elseif($row['inputType']=='email'){
  200.                     $answerLong="";
  201.                     $answer=$txt->sanitize($_POST['Question'.$row['msqID']]);
  202.                     if(!empty($row['options'])) {
  203.                         $settings = unserialize($row['options']);
  204.                         if(is_array($settings) && array_key_exists('send_notification_from', $settings) && $settings['send_notification_from'] == 1) {
  205.                             $email = $txt->email($answer);
  206.                             if(!empty($email)) {
  207.                                 $replyToEmailAddress = $email;
  208.                             }
  209.                         }
  210.                     }
  211.                 }elseif($row['inputType']=='telephone'){
  212.                     $answerLong="";
  213.                     $answer=$txt->sanitize($_POST['Question'.$row['msqID']]);
  214.                 }else{
  215.                     $answerLong="";
  216.                     $answer=$txt->sanitize($_POST['Question'.$row['msqID']]);
  217.                 }
  218.                
  219.                 if( is_array($answer) )
  220.                     $answer=join(',',$answer);
  221.                                    
  222.                 $questionAnswerPairs[$row['msqID']]['question']=$row['question'];
  223.                 $questionAnswerPairs[$row['msqID']]['answer']=$txt->sanitize( $answer.$answerLong );
  224.                
  225.                 $v=array($row['msqID'],$answerSetID,$answer,$answerLong);
  226.                 $q="insert into {$this->btAnswersTablename} (msqID,asID,answer,answerLong) values (?,?,?,?)";
  227.                 $db->query($q,$v);
  228.             }
  229.             $foundSpam = false;
  230.            
  231.             $submittedData = '';
  232.             foreach($questionAnswerPairs as $questionAnswerPair){
  233.                 $submittedData .= $questionAnswerPair['question']."\r\n".$questionAnswerPair['answer']."\r\n"."\r\n";
  234.             }
  235.             $antispam = Loader::helper('validation/antispam');
  236.             if (!$antispam->check($submittedData, 'form_block')) {
  237.                 // found to be spam. We remove it
  238.                 $foundSpam = true;
  239.                 $q="delete from {$this->btAnswerSetTablename} where asID = ?";
  240.                 $v = array($this->lastAnswerSetId);
  241.                 $db->Execute($q, $v);
  242.                 $db->Execute('delete from {$this->btAnswersTablename} where asID = ?', array($this->lastAnswerSetId));
  243.             }
  244.            
  245.             if(intval($this->notifyMeOnSubmission)>0 && !$foundSpam){  
  246.                 if ($this->sendEmailFrom !== false) {
  247.                     $formFormEmailAddress = $this->sendEmailFrom;
  248.                 } else if( strlen(FORM_BLOCK_SENDER_EMAIL)>1 && strstr(FORM_BLOCK_SENDER_EMAIL,'@') ){
  249.                     $formFormEmailAddress = FORM_BLOCK_SENDER_EMAIL;  
  250.                 }else{
  251.                     $adminUserInfo=UserInfo::getByID(USER_SUPER_ID);
  252.                     $formFormEmailAddress = $adminUserInfo->getUserEmail();
  253.                 }
  254.                
  255.                 $mh = Loader::helper('mail');
  256.                 $mh->to( $this->recipientEmail );
  257.                 $mh->from( $formFormEmailAddress );
  258.                 $mh->replyto( $replyToEmailAddress );
  259.                 $mh->addParameter('formName', $this->surveyName);
  260.                 $mh->addParameter('questionSetId', $this->questionSetId);
  261.                 $mh->addParameter('questionAnswerPairs', $questionAnswerPairs);
  262.                 $mh->load('block_form_submission');
  263.                 $mh->setSubject(t('%s Form Submission', $this->surveyName));
  264.                 //echo $mh->body.'<br>';
  265.                 @$mh->sendMail();
  266.             }
  267.            
  268.             if (!$this->noSubmitFormRedirect) {
  269.                 if ($this->redirectCID > 0) {
  270.                     $pg = Page::getByID($this->redirectCID);
  271.                     if (is_object($pg) && $pg->cID) {
  272.                         $this->redirect($pg->getCollectionPath());
  273.                     }
  274.                 }
  275.                 $c = Page::getCurrentPage();
  276.                 header("Location: ".Loader::helper('navigation')->getLinkToCollection($c, true)."?surveySuccess=1&qsid=".$this->questionSetId."#".$this->questionSetId);
  277.                 exit;
  278.             }
  279.         }
  280.     }      
  281. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement