Merge pull request #4959 from rohankatkar/batch-17
[civicrm-core.git] / CRM / Event / Form / Registration / Confirm.php
index a057480bc141a8d09ed7b274325fd7c7c38764b9..4fdd2cd163f627ed966bf17dac1e4aae019cedd4 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.5                                                |
+ | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
  | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
@@ -44,7 +44,6 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * The values for the contribution db object
    *
    * @var array
-   * @protected
    */
   public $_values;
 
@@ -52,7 +51,6 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * The total amount
    *
    * @var float
-   * @public
    */
   public $_totalAmount;
 
@@ -60,9 +58,8 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * Set variables up before form is built
    *
    * @return void
-   * @access public
    */
-  function preProcess() {
+  public function preProcess() {
     parent::preProcess();
 
     // lineItem isn't set until Register postProcess
@@ -95,12 +92,14 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
       if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
-        if (is_object($payment))
+        if (is_object($payment)) {
           $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
-        else
+        }
+        else {
           CRM_Core_Error::fatal($paymentObjError);
+        }
 
-        $params['payer'] = $expressParams['payer'];
+        $params['payer'] = CRM_Utils_Array::value('payer', $expressParams);
         $params['payer_id'] = $expressParams['payer_id'];
         $params['payer_status'] = $expressParams['payer_status'];
 
@@ -122,6 +121,9 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
           $params['discountAmount'] = $this->_params[0]['discountAmount'];
           $params['discountMessage'] = $this->_params[0]['discountMessage'];
         }
+        if (!empty($this->_params[0]['amount_priceset_level_radio'])) {
+          $params['amount_priceset_level_radio'] = $this->_params[0]['amount_priceset_level_radio'];
+        }
         $params['amount_level'] = $this->_params[0]['amount_level'];
         $params['currencyID'] = $this->_params[0]['currencyID'];
         $params['payment_action'] = 'Sale';
@@ -164,7 +166,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
         $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
       }
       if (isset($registerParams['credit_card_exp_date'])) {
-        $registerParams['year']  = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
+        $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
         $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
       }
       if ($this->_values['event']['is_monetary']) {
@@ -207,9 +209,8 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * no help display needed
    *
    * @return int
-   * @access public
    */
-  function getAction() {
+  public function getAction() {
     if ($this->_action & CRM_Core_Action::PREVIEW) {
       return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
     }
@@ -222,7 +223,6 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * Build the form object
    *
    * @return void
-   * @access public
    */
   public function buildQuickForm() {
     $this->assignToTemplate();
@@ -238,7 +238,9 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
         $taxAmount += $v['tax_amount'];
         if (is_array($v)) {
           foreach (array(
-            'first_name', 'last_name') as $name) {
+                     'first_name',
+                     'last_name',
+                   ) as $name) {
             if (isset($v['billing_' . $name]) &&
               !isset($v[$name])
             ) {
@@ -275,7 +277,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
         }
       }
 
-      $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
+      $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
       $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
       $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
       if ($invoicing) {
@@ -329,17 +331,17 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
       $this->addButtons(array(
           array(
             'type' => 'back',
-            'name' => ts('<< Go Back'),
+            'name' => ts('Go Back'),
           ),
         )
       );
     }
     else {
-      $contribButton = ts('Continue >>');
+      $contribButton = ts('Continue');
       $this->addButtons(array(
           array(
             'type' => 'back',
-            'name' => ts('<< Go Back'),
+            'name' => ts('Go Back'),
           ),
           array(
             'type' => 'next',
@@ -388,17 +390,43 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
 
     // Assign Participant Count to Lineitem Table
     $this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
+    $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
+  }
+
+  public static function formRule($fields, $files, $self) {
+    $errors = array();
+    $eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
+    if ($eventFull && empty($self->_allowConfirmation)) {
+      if (empty($self->_allowWaitlist)) {
+        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_eventId}", FALSE, NULL, FALSE, TRUE));
+      }
+    }
+    $self->_feeBlock = $self->_values['fee'];
+    CRM_Event_Form_Registration_Register::formatFieldsForOptionFull($self);
+
+    if (!empty($self->_priceSetId)) {
+      $priceSetErrors = self::validatePriceSet($self, $self->_params);
+      //get price set fields errors in.
+      $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
+    }
+
+    if (!empty($errors)) {
+      $soldOutOptions = implode("<br/>", $priceSetErrors['soldOutOptions']);
+      CRM_Core_Session::setStatus(ts('You have been returned to the start of the registration process and any sold out events have been removed from your selections. You will not be able to continue until you review your booking and select different events if you wish. The following events were sold out:'), ts('Unfortunately some of your options have now sold out for one or more participants.'), 'error');
+      CRM_Core_Session::setStatus(ts("{$soldOutOptions}"), ts('Sold out:'), 'error');
+      CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=true&qfKey=" . $fields['qfKey']));
+    }
+    return empty($errors) ? TRUE : $errors;
   }
 
   /**
    * Process the form submission
    *
-   * @access public
    *
    * @return void
    */
   public function postProcess() {
-    $now           = date('YmdHis');
+    $now = date('YmdHis');
 
     $this->_params = $this->get('params');
     if (!empty($this->_params[0]['contact_id'])) {
@@ -555,10 +583,12 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
           }
         }
         elseif ($this->_contributeMode == 'express' && !empty($value['is_primary'])) {
-          if (is_object($payment))
+          if (is_object($payment)) {
             $result = $payment->doExpressCheckout($value);
-          else
+          }
+          else {
             CRM_Core_Error::fatal($paymentObjError);
+          }
         }
         elseif (!empty($value['is_primary'])) {
           CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
@@ -610,8 +640,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
           }
 
           //passing contribution id is already registered.
-          $contribution =
-            self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
+          $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
           $value['contributionID'] = $contribution->id;
           $value['contributionTypeID'] = $contribution->financial_type_id;
           $value['receive_date'] = $contribution->receive_date;
@@ -620,7 +649,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
           $value['contributionTypeID'] = $contribution->financial_type_id;
         }
         $value['contactID'] = $contactID;
-        $value['eventID']   = $this->_eventId;
+        $value['eventID'] = $this->_eventId;
         $value['item_name'] = $value['description'];
       }
 
@@ -654,7 +683,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
 
       // handle register date CRM-4320
       if ($this->_allowConfirmation) {
-        $registerDate = CRM_Utils_Array::value( 'participant_register_date', $params );
+        $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
       }
       elseif (!empty($params['participant_register_date']) &&
         is_array($params['participant_register_date']) &&
@@ -692,7 +721,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
       }
 
       $entityTable = 'civicrm_participant';
-      $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
+      $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
       $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
       $totalTaxAmount = 0;
       $dataArray = array();
@@ -765,79 +794,58 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
       // do a transfer only if a monetary payment greater than 0
       if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
         if ($payment && is_object($payment)) {
+          //CRM 14512 provide line items of all participants to payment gateway
+          $primaryContactId = $this->get('primaryContactId');
 
-      /* CRM 14512 provide line items of all participants to payment gateway *************/
-                 
-                 //make note of primary contact id
-                 $primaryContactId = $this->get('primaryContactId');
-               
-                 //build an array of cId/pId of participants
-                 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID,
-                       NULL, $primaryContactId, $isTest,
-                       TRUE
-                 );
-                
-                 //need to copy, since we are unsetting on the way.
-                 $copyParticipantCountLines = $participantCount;
-                       
-                 //lets carry all participant params w/ values.
-                 foreach ($additionalIDs as $participantID => $contactId) {
-                         
-                       $participantNum = NULL;
-                       
-                       $participantNum = $participantID;
-                       
-                       if ($participantID == $registerByID) {
-                               
-                               $participantNum = 0;  // is primary particpant          
-                                                 
-                               } else {
-                               
-                                       if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
-                                       
-                                               //if no participant found break.          
-                                               if ($participantNum === NULL) {           
-                                                       break;          
-                                               }
-                                       
-                                               //unset current particpant so we don't check them again
-                                               unset($copyParticipantCountLines[$participantNum]);       
-                                               //}
-                                       }
-                       }
-                       
-                               // get values of line items 
-                               if ($this->_amount) {
-                               
-                                       $amount = array();                      
-                                       $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
-                                       $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
-                                       $params[$participantNum]['amounts'] = $amount;
-                               }
-                                                       
-                               if ($this->_lineItem) {
-                                       
-                                       $lineItems  = $this->_lineItem;
-                                       $lineItem   = array();
-                                       
-                                       if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
-                                               $lineItem[] = $lineItemValue;
-                                       }
-                                       
-                                       $params[$participantNum]['lineItem'] = $lineItem;
-                               }        
-                       
-               //only add additional particpants and not the primary particpant as we already have that
-               //added to $primaryParticipant so that this change doesn't break or require changes to existing gateway implementations
-               $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];   
-                                       
-                               }
-                                               
-               //get event custom field information
-               $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']); 
-               $primaryParticipant['eventCustomFields'] = $groupTree;          
-                 
-            /*  END CRM 14512 */
+          //build an array of cId/pId of participants
+          $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
+
+          //need to copy, since we are unsetting on the way.
+          $copyParticipantCountLines = $participantCount;
+
+          //lets carry all participant params w/ values.
+          foreach ($additionalIDs as $participantID => $contactId) {
+            $participantNum = NULL;
+            $participantNum = $participantID;
+            if ($participantID == $registerByID) {
+              $participantNum = 0;  // is primary particpant
+            }
+            else {
+              if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
+                //if no participant found break.
+                if ($participantNum === NULL) {
+                  break;
+                }
+                //unset current particpant so we don't check them again
+                unset($copyParticipantCountLines[$participantNum]);
+              }
+            }
+            // get values of line items
+            if ($this->_amount) {
+              $amount = array();
+              $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
+              $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
+              $params[$participantNum]['amounts'] = $amount;
+            }
+
+            if (!empty($this->_lineItem)) {
+              $lineItems = $this->_lineItem;
+              $lineItem = array();
+              if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
+                $lineItem[] = $lineItemValue;
+              }
+              $params[$participantNum]['lineItem'] = $lineItem;
+            }
+
+            //only add additional particpants and not the primary particpant as we already have that
+            //added to $primaryParticipant so that this change doesn't break or require changes to
+            //existing gateway implementations
+            $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];
+          }
+
+          //get event custom field information
+          $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
+          $primaryParticipant['eventCustomFields'] = $groupTree;
 
           // call postprocess hook before leaving
           $this->postProcessHook();
@@ -876,8 +884,9 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
             unset($copyParticipantCount[$participantNum]);
           }
         }
-        if ($participantNum === NULL)
-        break;
+        if ($participantNum === NULL) {
+          break;
+        }
 
         //carry the participant submitted values.
         $this->_values['params'][$participantID] = $params[$participantNum];
@@ -913,8 +922,8 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
             $this->assign('amounts', $amount);
           }
           if ($this->_lineItem) {
-            $lineItems  = $this->_lineItem;
-            $lineItem   = array();
+            $lineItems = $this->_lineItem;
+            $lineItem = array();
             if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
               $lineItem[] = $lineItemValue;
             }
@@ -947,14 +956,14 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * @param bool $isAdditionalAmount
    *
    * @return void
-   * @access public
    */
-  static function processContribution(&$form, $params, $result, $contactID,
+  public static function processContribution(
+    &$form, $params, $result, $contactID,
     $pending = FALSE, $isAdditionalAmount = FALSE
   ) {
     $transaction = new CRM_Core_Transaction();
 
-    $now         = date('YmdHis');
+    $now = date('YmdHis');
     $receiptDate = NULL;
 
     if (!empty($form->_values['event']['is_email_confirm'])) {
@@ -967,8 +976,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
 
     $contribParams = array(
       'contact_id' => $contactID,
-      'financial_type_id'     => !empty($form->_values['event']['financial_type_id']) ?
-      $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
+      'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
       'receive_date' => $now,
       'total_amount' => $params['amount'],
       'tax_amount' => $params['tax_amount'],
@@ -1065,7 +1073,6 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * @param CRM_Core_Form $form
    *
    * @return void
-   * @access public
    */
   public static function fixLocationFields(&$params, &$fields, &$form) {
     if (!empty($form->_fields)) {
@@ -1100,7 +1107,8 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
         !$form->_values['event']['is_monetary'] ||
         $form->_allowWaitlist ||
         $form->_requireApproval
-      ) && !empty($params["email-{$form->_bltID}"])) {
+      ) && !empty($params["email-{$form->_bltID}"])
+    ) {
       $params['email-Primary'] = $params["email-{$form->_bltID}"];
     }
   }
@@ -1114,7 +1122,6 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
    * @param CRM_Core_Form $form
    *
    * @return void
-   * @access public
    */
   public static function updateContactFields($contactID, $params, $fields, &$form) {
     //add the contact to group, if add to group is selected for a
@@ -1155,7 +1162,7 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
         'contact_type'
       );
 
-      if(array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
+      if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
         // we unset this here because the downstream function ignores the contactID we give it
         // if it is set & it is difficult to understand the implications of 'fixing' this downstream
         // but if we are passing a contact id into this function it's reasonable to assume we don't
@@ -1211,21 +1218,22 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
   public static function assignProfiles(&$form) {
     $participantParams = $form->_params;
     $formattedValues = $profileFields = array();
-    $count             = 1;
+    $count = 1;
     foreach ($participantParams as $participantNum => $participantValue) {
       if ($participantNum) {
-          $prefix1 = 'additional';
-          $prefix2 = 'additional_';
-      } else {
-          $prefix1 = '';
-          $prefix2 = '';
+        $prefix1 = 'additional';
+        $prefix2 = 'additional_';
+      }
+      else {
+        $prefix1 = '';
+        $prefix2 = '';
       }
       if ($participantValue != 'skip') {
         //get the customPre profile info
         if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
           $values = $groupName = array();
           CRM_Event_BAO_Event::displayProfile($participantValue,
-            $form->_values[ $prefix2 . 'custom_pre_id'],
+            $form->_values[$prefix2 . 'custom_pre_id'],
             $groupName,
             $values,
             $profileFields
@@ -1267,13 +1275,13 @@ class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
       }
       $form->_fields = $profileFields;
     }
-    if (!empty($formattedValues) ) {
+    if (!empty($formattedValues)) {
       $form->assign('primaryParticipantProfile', $formattedValues[1]);
-      $form->set('primaryParticipantProfile',    $formattedValues[1]);
+      $form->set('primaryParticipantProfile', $formattedValues[1]);
       if ($count > 2) {
         unset($formattedValues[1]);
         $form->assign('addParticipantProfile', $formattedValues);
-        $form->set('addParticipantProfile',    $formattedValues);
+        $form->set('addParticipantProfile', $formattedValues);
       }
     }
   }