function validate() { parent::validate(); if ($this->_errors) { return FALSE; } $this->cart->load_associations(); $fields = $this->_submitValues; foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) { $price_set_id = CRM_Event_BAO_Event::usesPriceSet($event_in_cart->event_id); if ($price_set_id) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $price_set_id; $priceField->find(); $check = array(); while ($priceField->fetch()) { if (!empty($fields["event_{$event_in_cart->event_id}_price_{$priceField->id}"])) { $check[] = $priceField->id; } } //XXX if (empty($check)) { $this->_errors['_qf_default'] = ts("Select at least one option from Price Levels."); } $lineItem = array(); if (is_array($this->_values['fee']['fields'])) { CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $fields, $lineItem); //XXX total... if ($fields['amount'] < 0) { $this->_errors['_qf_default'] = ts("Price Levels can not be less than zero. Please select the options accordingly"); } } } foreach ($event_in_cart->participants as $mer_participant) { $participant_fields = $fields['event'][$event_in_cart->event_id]['participant'][$mer_participant->id]; //TODO what to do when profile responses differ for the same contact? $contact_id = self::find_contact($participant_fields); if ($contact_id) { $participant = new CRM_Event_BAO_Participant(); $participant->event_id = $event_in_cart->event_id; $participant->contact_id = $contact_id; $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1'); $participant->find(); while ($participant->fetch()) { if (array_key_exists($participant->status_id, $statusTypes)) { $form = $mer_participant->get_form(); $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", array(1 => $participant_fields['email'], 2 => $event_in_cart->event->title, 3 => $event_in_cart->event->start_date)); } } } } } return empty($this->_errors); }
function addrecurLineItems($recurId, $contributionId) { $lineSets = $lineItems = array(); //Get the first contribution id with recur id if ($recurId) { $contriID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id'); $lineItems = CRM_Price_BAO_LineItem::getLineItems($contriID, 'contribution'); if (!empty($lineItems)) { foreach ($lineItems as $key => $value) { $pricesetID = new CRM_Price_DAO_Field(); $pricesetID->id = $value['price_field_id']; $pricesetID->find(TRUE); $lineSets[$pricesetID->price_set_id][] = $value; } } CRM_Contribute_Form_AdditionalInfo::processPriceSet($contributionId, $lineSets); } }
function upgrade_3_3_beta1($rev) { $upgrade = new CRM_Upgrade_Form(); $upgrade->processSQL($rev); // CRM-6902 // Add column price_field_value_id in civicrm_line_item. // Do not drop option_group_id column now since we need it to // update line items. $updateLineItem1 = "ALTER TABLE civicrm_line_item ADD COLUMN price_field_value_id int(10) unsigned default NULL;"; CRM_Core_DAO::executeQuery($updateLineItem1); $priceFieldDAO = new CRM_Price_DAO_Field(); $priceFieldDAO->find(); $ids = array(); while ($priceFieldDAO->fetch()) { $opGroupDAO = new CRM_Core_DAO_OptionGroup(); $opGroupDAO->name = 'civicrm_price_field.amount.' . $priceFieldDAO->id; if (!$opGroupDAO->find(TRUE)) { $opGroupDAO->free(); continue; } $opValueDAO = new CRM_Core_DAO_OptionValue(); $opValueDAO->option_group_id = $opGroupDAO->id; $opValueDAO->find(); while ($opValueDAO->fetch()) { // FIX ME: not migrating description(?), there will // be a field description for each option. $fieldValue = array('price_field_id' => $priceFieldDAO->id, 'label' => $opValueDAO->label, 'name' => CRM_Utils_String::munge($opValueDAO->label, '_', 64), 'amount' => $opValueDAO->name, 'weight' => $opValueDAO->weight, 'is_default' => $opValueDAO->is_default, 'is_active' => $opValueDAO->is_active); if ($priceFieldDAO->count) { // Migrate Participant Counts on option level. // count of each option will be the same // as earlier field count. $fieldValue['count'] = $priceFieldDAO->count; } $fieldValueDAO = CRM_Price_BAO_FieldValue::add($fieldValue, $ids); $lineItemDAO = new CRM_Price_DAO_LineItem(); $lineItemDAO->option_group_id = $opGroupDAO->id; $lineItemDAO->label = $opValueDAO->label; $lineItemDAO->unit_price = $opValueDAO->name; $labelFound = $priceFound = FALSE; // check with label and amount if (!$lineItemDAO->find(TRUE)) { $lineItemDAO->free(); $lineItemDAO = new CRM_Price_DAO_LineItem(); $lineItemDAO->option_group_id = $opGroupDAO->id; $lineItemDAO->label = $opValueDAO->label; // check with label only if ($lineItemDAO->find(TRUE)) { $labelFound = TRUE; } } else { $labelFound = TRUE; $priceFound = TRUE; } $lineItemDAO->free(); // update civicrm_line_item for price_field_value_id. // Used query to avoid line by line update. if ($labelFound || $priceFound) { $lineItemParams = array(1 => array($fieldValueDAO->id, 'Integer'), 2 => array($opValueDAO->label, 'String')); $updateLineItems = "UPDATE civicrm_line_item SET price_field_value_id = %1 WHERE label = %2"; if ($priceFound) { $lineItemParams[3] = array($opValueDAO->name, 'Float'); $updateLineItems .= " AND unit_price = %3"; } CRM_Core_DAO::executeQuery($updateLineItems, $lineItemParams); } } $opGroupDAO->delete(); $opValueDAO->free(); $opGroupDAO->free(); } $priceFieldDAO->free(); // Now drop option_group_id column from civicrm_line_item $updateLineItem2 = "ALTER TABLE civicrm_line_item DROP option_group_id,\n ADD CONSTRAINT `FK_civicrm_price_field_value_id` FOREIGN KEY (price_field_value_id) REFERENCES civicrm_price_field_value(id) ON DELETE SET NULL;"; CRM_Core_DAO::executeQuery($updateLineItem2, array(), TRUE, NULL, FALSE, FALSE); $updatePriceField = "ALTER TABLE civicrm_price_field DROP count"; CRM_Core_DAO::executeQuery($updatePriceField, array(), TRUE, NULL, FALSE, FALSE); // as the table 'civicrm_price_field' is localised and column 'count' is dropped // after the views are rebuild, we need to rebuild views to avoid invalid refrence of table. if ($upgrade->multilingual) { CRM_Core_I18n_Schema::rebuildMultilingualSchema($upgrade->locales, $rev); } }
/** * global validation rules for the form * * @param array $fields (referance) posted values of the form * * @return array if errors then list of errors to be posted back to the form, * true otherwise * @static * @access public */ static function formRule($fields, $files, $form) { // all option fields are of type "money" $errors = array(); /** Check the option values entered * Appropriate values are required for the selected datatype * Incomplete row checking is also required. */ if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) { $errors['price'] = ts('Price is a required field'); } //avoid the same price field label in Within PriceSet $priceFieldLabel = new CRM_Price_DAO_Field(); $priceFieldLabel->label = $fields['label']; $priceFieldLabel->price_set_id = $form->_sid; $dupeLabel = FALSE; if ($priceFieldLabel->find(TRUE) && $form->_fid != $priceFieldLabel->id) { $dupeLabel = TRUE; } if ($dupeLabel) { $errors['label'] = ts('Name already exists in Database.'); } if (is_numeric(CRM_Utils_Array::value('count', $fields)) && CRM_Utils_Array::value('count', $fields) == 0 && CRM_Utils_Array::value('html_type', $fields) == 'Text') { $errors['count'] = ts('Participant Count must be greater than zero.'); } if ($form->_action & CRM_Core_Action::ADD) { if ($fields['html_type'] != 'Text') { $countemptyrows = 0; $_flagOption = $_rowError = 0; $_showHide = new CRM_Core_ShowHideBlocks('', ''); for ($index = 1; $index <= self::NUM_OPTION; $index++) { $noLabel = $noAmount = $noWeight = 1; if (!empty($fields['option_label'][$index])) { $noLabel = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']); if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) { $errors["option_label[{$index}]"] = ts('Duplicate label value'); $_flagOption = 1; } } if ($form->_useForMember) { if (!empty($fields['membership_type_id'][$index])) { $memTypesIDS[] = $fields['membership_type_id'][$index]; } } // allow for 0 value. if (!empty($fields['option_amount'][$index]) || strlen($fields['option_amount'][$index]) > 0) { $noAmount = 0; } if (!empty($fields['option_weight'][$index])) { $noWeight = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']); if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) { $errors["option_weight[{$index}]"] = ts('Duplicate weight value'); $_flagOption = 1; } } if ($noLabel && !$noAmount) { $errors["option_label[{$index}]"] = ts('Label cannot be empty.'); $_flagOption = 1; } if (!$noLabel && $noAmount) { $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.'); $_flagOption = 1; } if ($noLabel && $noAmount) { $countemptyrows++; $_emptyRow = 1; } elseif (!empty($fields['option_max_value'][$index]) && !empty($fields['option_count'][$index]) && $fields['option_count'][$index] > $fields['option_max_value'][$index]) { $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.'); $_flagOption = 1; } $showBlocks = 'optionField_' . $index; if ($_flagOption) { $_showHide->addShow($showBlocks); $_rowError = 1; } if (!empty($_emptyRow)) { $_showHide->addHide($showBlocks); } else { $_showHide->addShow($showBlocks); } if ($index == self::NUM_OPTION) { $hideBlock = 'additionalOption'; $_showHide->addHide($hideBlock); } $_flagOption = $_emptyRow = 0; } if (!empty($memTypesIDS)) { // check for checkboxes allowing user to select multiple memberships from same membership organization if ($fields['html_type'] == 'CheckBox') { $foundDuplicate = FALSE; $orgIds = array(); foreach ($memTypesIDS as $key => $val) { $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val); if (in_array($org[$val], $orgIds)) { $foundDuplicate = TRUE; break; } $orgIds[$val] = $org[$val]; } if ($foundDuplicate) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity.'); } } // CRM-10390 - Only one price field in a set can include auto-renew membership options $foundAutorenew = FALSE; foreach ($memTypesIDS as $key => $val) { // see if any price field option values in this price field are for memberships with autorenew $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val); if (CRM_Utils_Array::value('auto_renew', $memTypeDetails)) { $foundAutorenew = TRUE; break; } } if ($foundAutorenew) { // if so, check for other fields in this price set which also have auto-renew membership options $otherFieldAutorenew = CRM_Price_BAO_Set::checkAutoRenewForPriceSet($form->_sid); if ($otherFieldAutorenew) { $errors['_qf_default'] = ts('You can include auto-renew membership choices for only one price field in a price set. Another field in this set already contains one or more auto-renew membership options.'); } } } $_showHide->addToTemplate(); if ($countemptyrows == 11) { $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.'); $_flagOption = 1; } } elseif (!empty($fields['max_value']) && !empty($fields['count']) && $fields['count'] > $fields['max_value']) { $errors['max_value'] = ts('Participant count can not be greater than max participants.'); } // do not process if no option rows were submitted if (empty($fields['option_amount']) && empty($fields['option_label'])) { return TRUE; } if (empty($fields['option_name'])) { $fields['option_amount'] = array(); } if (empty($fields['option_label'])) { $fields['option_label'] = array(); } } return empty($errors) ? TRUE : $errors; }
/** * global validation rules for the form * * @param array $fields (referance) posted values of the form * * @return array if errors then list of errors to be posted back to the form, * true otherwise * @static * @access public */ static function formRule($fields, $files, $form) { // all option fields are of type "money" $errors = array(); /** Check the option values entered * Appropriate values are required for the selected datatype * Incomplete row checking is also required. */ if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) { $errors['price'] = ts('Price is a required field'); } //avoid the same price field label in Within PriceSet $priceFieldLabel = new CRM_Price_DAO_Field(); $priceFieldLabel->label = $fields['label']; $priceFieldLabel->price_set_id = $form->_sid; $dupeLabel = false; if ($priceFieldLabel->find(true) && $form->_fid != $priceFieldLabel->id) { $dupeLabel = true; } if ($dupeLabel) { $errors['label'] = ts('Name already exists in Database.'); } if (is_numeric(CRM_Utils_Array::value('count', $fields)) && CRM_Utils_Array::value('count', $fields) == 0 && CRM_Utils_Array::value('html_type', $fields) == 'Text') { $errors['count'] = ts('Participant Count must be greater than zero.'); } if ($form->_action & CRM_Core_Action::ADD) { if ($fields['html_type'] != 'Text') { $countemptyrows = 0; $_flagOption = $_rowError = 0; $_showHide = new CRM_Core_ShowHideBlocks('', ''); for ($index = 1; $index <= self::NUM_OPTION; $index++) { $noLabel = $noAmount = $noWeight = 1; if (!empty($fields['option_label'][$index])) { $noLabel = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']); if (!($duplicateIndex === false) && !($duplicateIndex == $index)) { $errors["option_label[{$index}]"] = ts('Duplicate label value'); $_flagOption = 1; } } // allow for 0 value. if (!empty($fields['option_amount'][$index]) || strlen($fields['option_amount'][$index]) > 0) { $noAmount = 0; } if (!empty($fields['option_weight'][$index])) { $noWeight = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']); if (!($duplicateIndex === false) && !($duplicateIndex == $index)) { $errors["option_weight[{$index}]"] = ts('Duplicate weight value'); $_flagOption = 1; } } if ($noLabel && !$noAmount) { $errors["option_label[{$index}]"] = ts('Label cannot be empty.'); $_flagOption = 1; } if (!$noLabel && $noAmount) { $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.'); $_flagOption = 1; } if ($noLabel && $noAmount) { $countemptyrows++; $_emptyRow = 1; } else { if (!empty($fields['option_max_value'][$index]) && !empty($fields['option_count'][$index]) && $fields['option_count'][$index] > $fields['option_max_value'][$index]) { $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.'); $_flagOption = 1; } } $showBlocks = 'optionField_' . $index; if ($_flagOption) { $_showHide->addShow($showBlocks); $_rowError = 1; } if (!empty($_emptyRow)) { $_showHide->addHide($showBlocks); } else { $_showHide->addShow($showBlocks); } if ($index == self::NUM_OPTION) { $hideBlock = 'additionalOption'; $_showHide->addHide($hideBlock); } $_flagOption = $_emptyRow = 0; } $_showHide->addToTemplate(); if ($countemptyrows == 11) { $errors["option_label[1]"] = $errors["option_amount[1]"] = ts('Label and value cannot be empty.'); $_flagOption = 1; } } else { if (!empty($fields['max_value']) && !empty($fields['count']) && $fields['count'] > $fields['max_value']) { $errors["max_value"] = ts('Participant count can not be greater than max participants.'); } } // do not process if no option rows were submitted if (empty($fields['option_amount']) && empty($fields['option_label'])) { return true; } if (empty($fields['option_name'])) { $fields['option_amount'] = array(); } if (empty($fields['option_label'])) { $fields['option_label'] = array(); } } return empty($errors) ? true : $errors; }
/** * global validation rules for the form * * @param array $fields (referance) posted values of the form * * @return array if errors then list of errors to be posted back to the form, * true otherwise * @static * @access public */ static function formRule(&$fields, &$files, &$form) { // all option fields are of type "money" $errors = array(); /** Check the option values entered * Appropriate values are required for the selected datatype * Incomplete row checking is also required. */ if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) { $errors['price'] = ts('Price is a required field'); } //avoid the same price field label in Within PriceSet $priceFieldLabel = new CRM_Price_DAO_Field(); $priceFieldLabel->label = $fields['label']; $priceFieldLabel->price_set_id = $form->_sid; $dupeLabel = false; if ($priceFieldLabel->find(true) && $form->_fid != $priceFieldLabel->id) { $dupeLabel = true; } if ($dupeLabel) { $errors['label'] = ts('Name already exists in Database.'); } if ($form->_action & CRM_Core_Action::ADD) { if ($fields['html_type'] != 'Text') { $countemptyrows = 0; for ($index = self::NUM_OPTION; $index > 0; $index--) { $noLabel = $noAmount = $noWeight = 1; if (!empty($fields['option_label'][$index])) { $noLabel = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']); if (!($duplicateIndex === false) && !($duplicateIndex == $index)) { $errors["option_label[{$index}]"] = ts('Duplicate label value'); } } // allow for 0 value. if (!empty($fields['option_name'][$index]) || strlen($fields['option_name'][$index]) > 0) { $noAmount = 0; } if (!empty($fields['option_weight'][$index])) { $noWeight = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']); if (!($duplicateIndex === false) && !($duplicateIndex == $index)) { $errors["option_weight[{$index}]"] = ts('Duplicate weight value'); } } if ($noLabel && !$noAmount) { $errors["option_label[{$index}]"] = ts('Label cannot be empty.'); } if (!$noLabel && $noAmount) { $errors["option_name[{$index}]"] = ts('Amount cannot be empty.'); } if ($noLabel && $noAmount) { $countemptyrows++; } } if ($countemptyrows == 11) { $errors["option_label[1]"] = $errors["option_name[1]"] = ts('Label and value cannot be empty.'); } } $_showHide =& new CRM_Core_ShowHideBlocks('', ''); // do not process if no option rows were submitted if (empty($fields['option_name']) && empty($fields['option_label'])) { return true; } if (empty($fields['option_name'])) { $fields['option_name'] = array(); } if (empty($fields['option_label'])) { $fields['option_label'] = array(); } $dupeLabels = array(); $count = 0; for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) { $_flagOption = 0; $_rowError = 0; $showBlocks = 'optionField_' . $idx; // both value and label are empty if ($fields['option_name'][$idx] == '' && $fields['option_label'][$idx] == '') { $_showHide->addHide($showBlocks); $count++; if ($count == 11) { $showBlocks = 'optionField_' . '1'; $_showHide->addShow($showBlocks); } continue; } $_showHide->addShow($showBlocks); if ($fields['option_name'][$idx] != '') { // check for empty label if ($fields['option_label'][$idx] == '') { $errors['option_label][' . $idx . ']'] = ts('Option label cannot be empty'); } // all fields are money fields if (!CRM_Utils_Rule::moneySigned($fields['option_name'][$idx])) { $_flagOption = 1; $errors['option_name[' . $idx . ']'] = ts('Please enter a valid money value.'); } } if ($fields['option_label'][$idx] != '') { // check for empty value if ($fields['option_name'][$idx] == '') { $errors['option_name][' . $idx . ']'] = ts('Option value cannot be empty'); } // check for duplicate labels, if not already done if (isset($dupeLabels[$idx])) { continue; } $also_in = array_keys($fields['option_label'], $fields['option_label'][$idx]); // first match is always the current key unset($also_in[0]); if (!empty($also_in)) { $_flagOption = 1; $errors['option_label][' . $idx . ']'] = ts('Duplicate Option label'); foreach ($also_in as $also_in_key) { $errors['option_name][' . $also_in_key . ']'] = ts('Duplicate Option label'); $dupeValues[$also_in_key] = true; } } } if ($_flagOption) { $_showHide->addShow($showBlocks); $_rowError = 1; } // last row - hide "Additional Option" option if ($idx == self::NUM_OPTION) { $hideBlock = 'additionalOption'; $_showHide->addHide($hideBlock); } } $_showHide->addToTemplate(); } return empty($errors) ? true : $errors; }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule(&$fields, &$files, &$self) { $errors = array(); //get the button name. $button = substr($self->controller->getButtonName(), -4); if ($button != 'skip') { //Additional Participant can also register for an event only once require_once 'CRM/Event/Form/Registration/Register.php'; $isRegistered = CRM_Event_Form_Registration_Register::checkRegistration($fields, $self, true); if ($isRegistered) { $errors["email-{$self->_bltID}"] = ts('A person with this email address is already registered for this event.'); } //get the complete params. $params = $self->get('params'); //take the participant instance. $addParticipantNum = substr($self->_name, 12); if (is_array($params) && $self->_values['event']['allow_same_participant_emails'] != 1) { foreach ($params as $key => $value) { if ($value["email-{$self->_bltID}"] == $fields["email-{$self->_bltID}"] && $key != $addParticipantNum) { $errors["email-{$self->_bltID}"] = ts('The email address must be unique for each participant.'); break; } } } //check for atleast one pricefields should be selected if (CRM_Utils_Array::value('priceSetId', $fields)) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $fields['priceSetId']; $priceField->find(); $check = array(); while ($priceField->fetch()) { if (!empty($fields["price_{$priceField->id}"])) { $check[] = $priceField->id; } } if (empty($check)) { $errors['_qf_default'] = ts("Select at least one option from Event Fee(s)."); } } } return $errors; }
/** * Validate the priceset * * @param int $priceSetId, array $fields * * retrun the error string * * @access public * @static * */ public static function priceSetValidation($priceSetId, $fields, &$error) { // check for at least one positive // amount price field should be selected. $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $priceSetId; $priceField->find(); $priceFields = array(); while ($priceField->fetch()) { $key = "price_{$priceField->id}"; if (CRM_Utils_Array::value($key, $fields)) { $priceFields[$priceField->id] = $fields[$key]; } } if (!empty($priceFields)) { // we should has to have positive amount. $sql = "\nSELECT id, html_type \nFROM civicrm_price_field \nWHERE id IN (" . implode(',', array_keys($priceFields)) . ')'; $fieldDAO = CRM_Core_DAO::executeQuery($sql); $htmlTypes = array(); while ($fieldDAO->fetch()) { $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type; } $selectedAmounts = array(); require_once 'CRM/Price/BAO/FieldValue.php'; foreach ($htmlTypes as $fieldId => $type) { $options = array(); CRM_Price_BAO_FieldValue::getValues($fieldId, $options); if (empty($options)) { continue; } if ($type == 'Text') { foreach ($options as $opId => $option) { $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount']; break; } } else { if (is_array($fields["price_{$fieldId}"])) { foreach (array_keys($fields["price_{$fieldId}"]) as $opId) { $selectedAmounts[$opId] = $options[$opId]['amount']; } } else { if (in_array($fields["price_{$fieldId}"], array_keys($options))) { $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount']; } } } } list($componentName) = explode(':', $fields['_qf_default']); // now we have all selected amount in hand. $totalAmount = array_sum($selectedAmounts); if ($totalAmount < 0) { $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName)); } } else { $error['_qf_default'] = ts("Please select at least one option from price set."); } }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $config = CRM_Core_Config::singleton(); // we first reset the confirm page so it accepts new values $this->controller->resetPage('Confirm'); // get the submitted form values. $params = $this->controller->exportValues($this->_name); if (CRM_Utils_Array::value('priceSetId', $params)) { $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config'); $formValue = array(); if ($is_quick_config) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $params['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $otherAmount = FALSE; while ($priceField->fetch()) { CRM_Price_BAO_FieldValue::getValues($priceField->id, $values); if ($priceField->name == "membership_amount") { if ($priceFiledID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) { $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $values[$priceFiledID]); $this->set('selectMembership', CRM_Utils_Array::value('selectMembership', $params)); if (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) { $this->_values['amount'] = CRM_Utils_Array::value('amount', $values[$priceFiledID]); } } } if ($priceField->name == 'contribution_amount') { $priceFiledID = CRM_Utils_Array::value("price_{$priceField->id}", $params); if ($priceFiledID > 0 && !empty($priceFiledID)) { $params['amount'] = $priceFiledID; $this->_values['amount'] = CRM_Utils_Array::value('amount', $values[$priceFiledID]); $this->_values[$priceFiledID]['value'] = CRM_Utils_Array::value('amount', $values[$priceFiledID]); $this->_values[$priceFiledID]['label'] = CRM_Utils_Array::value('label', $values[$priceFiledID]); $this->_values[$priceFiledID]['amount_id'] = CRM_Utils_Array::value('id', $values[$priceFiledID]); $this->_values[$priceFiledID]['weight'] = CRM_Utils_Array::value('weight', $values[$priceFiledID]); } } if ($priceField->name == "other_amount" && ($priceFiledID = CRM_Utils_Array::value("price_{$priceField->id}", $params))) { $params['amount_other'] = $priceFiledID; } } } } if ($this->_values['is_pay_later'] && empty($this->_paymentProcessor) && !array_key_exists('hidden_processor', $params) || CRM_Utils_Array::value('payment_processor', $params) == 0) { $params['is_pay_later'] = 1; } else { $params['is_pay_later'] = 0; } $this->set('is_pay_later', $params['is_pay_later']); // assign pay later stuff $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE); $this->assign('is_pay_later', $params['is_pay_later']); if ($params['is_pay_later']) { $this->assign('pay_later_text', $this->_values['pay_later_text']); $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']); } //carry campaign from profile. if (array_key_exists('contribution_campaign_id', $params)) { $params['campaign_id'] = $params['contribution_campaign_id']; } if (CRM_Utils_Array::value('onbehalfof_id', $params)) { $params['organization_id'] = $params['onbehalfof_id']; } $params['currencyID'] = $config->defaultCurrency; $params['amount'] = self::computeAmount($params, $this); $params['separate_amount'] = $params['amount']; $memFee = NULL; if (CRM_Utils_Array::value('selectMembership', $params)) { if (!empty($this->_membershipTypeValues)) { $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']]; } else { $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $params['selectMembership']); } $memFee = $membershipTypeValues['minimum_fee']; if (!$params['amount'] && !$this->_separateMembershipPayment) { $params['amount'] = $memFee ? $memFee : 0; } } //If the membership & contribution is used in contribution page & not seperate payment $fieldId = $memPresent = $membershipLabel = $fieldOption = $proceFieldAmount = $is_quick_config = NULL; if ($this->_separateMembershipPayment == 0) { $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config'); if ($is_quick_config) { foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) { if ($fieldVal['name'] == 'membership_amount') { $fieldId = $fieldVal['id']; $fieldOption = $params['price_' . $fieldId]; $memPresent = TRUE; } else { if (CRM_Utils_Array::value('price_' . $fieldKey, $params) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) { $fieldId = $fieldVal['id']; if ($fieldVal['name'] == 'other_amount') { $proceFieldAmount = $this->_submitValues['price_' . $fieldId]; } else { $proceFieldAmount = $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount']; } unset($params['price_' . $fieldId]); break; } } } } } if (!isset($params['amount_other'])) { $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params)); } if ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) { $lineItem = array(); $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config'); if ($is_quick_config) { foreach ($this->_values['fee'] as $key => &$val) { if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && array_key_exists('price_' . $key, $params) && $params['price_' . $key] != 0) { foreach ($val['options'] as $optionKey => &$options) { $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params); break; } $params['price_' . $key] = 1; break; } } } CRM_Price_BAO_Set::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId]); if ($proceFieldAmount) { $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount; $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount; if (!$this->_membershipBlock['is_separate_payment']) { $params['amount'] = $proceFieldAmount; //require when separate membership not used } } $this->set('lineItem', $lineItem); } if ($this->_membershipBlock['is_separate_payment'] && CRM_Utils_Array::value('separate_amount', $params)) { $this->set('amount', $params['separate_amount']); } else { $this->set('amount', $params['amount']); } // generate and set an invoiceID for this transaction $invoiceID = md5(uniqid(rand(), TRUE)); $this->set('invoiceID', $invoiceID); // required only if is_monetary and valid postive amount if ($this->_values['is_monetary'] && is_array($this->_paymentProcessor) && ((double) $params['amount'] > 0.0 || $memFee > 0.0)) { // default mode is direct $this->set('contributeMode', 'direct'); if ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { //get the button name $buttonName = $this->controller->getButtonName(); if (in_array($buttonName, array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')) && !CRM_Utils_Array::value('is_pay_later', $params)) { $this->set('contributeMode', 'express'); $donateURL = CRM_Utils_System::url('civicrm/contribute', '_qf_Contribute_display=1'); $params['cancelURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE); $params['returnURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Confirm_display=1&rfp=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE); $params['invoiceID'] = $invoiceID; //default action is Sale $params['payment_action'] = 'Sale'; $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this); $token = $payment->setExpressCheckout($params); if (is_a($token, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($token); CRM_Utils_System::redirect($params['cancelURL']); } $this->set('token', $token); $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token={$token}"; CRM_Utils_System::redirect($paymentURL); } } elseif ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY) { $this->set('contributeMode', 'notify'); } } // should we skip the confirm page? if (!CRM_Utils_Array::value('is_confirm_enabled', $this->_values)) { // build the confirm page $confirmForm =& $this->controller->_pages['Confirm']; $confirmForm->preProcess(); $confirmForm->buildQuickForm(); // the confirmation page is valid $data =& $this->controller->container(); $data['valid']['Confirm'] = 1; // confirm the contribution $confirmForm->postProcess(); $qfKey = $this->controller->_key; // redirect to thank you page CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$qfKey}", TRUE, NULL, FALSE)); } }
/** * Get field ids of a price set * * @param int id Price Set id * * @return array of the field ids * * @access public * @static */ public static function getFieldIds($id) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $id; $priceField->find(); while ($priceField->fetch()) { $var[] = $priceField->id; } return $var; }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule(&$fields, &$files, &$self) { //To check if the user is already registered for the event(CRM-2426) self::checkRegistration($fields, $self); //check for availability of registrations. if (!$self->_allowConfirmation && !CRM_Utils_Array::value('bypass_payment', $fields) && is_numeric($self->_availableRegistrations) && CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations) { $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations)); } // during confirmation don't allow to increase additional participants, CRM-4320 if ($self->_allowConfirmation && CRM_Utils_Array::value('additional_participants', $fields) && is_array($self->_additionalParticipantIds) && $fields['additional_participants'] > count($self->_additionalParticipantIds)) { $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", array(1 => count($self->_additionalParticipantIds))); } //don't allow to register w/ waiting if enough spaces available. if (CRM_Utils_Array::value('bypass_payment', $fields)) { if (!is_numeric($self->_availableRegistrations) || CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations) { $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list."); } } $email = $fields["email-{$self->_bltID}"]; require_once 'CRM/Core/BAO/UFMatch.php'; if (CRM_Core_BAO_UFMatch::isDuplicateUser($email)) { $errors["email-{$self->_bltID}"] = ts('The email %1 already exists in the database.', array(1 => $email)); } if (CRM_Utils_Array::value('additional_participants', $fields) && !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])) { $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.'); } //check for atleast one pricefields should be selected if (CRM_Utils_Array::value('priceSetId', $fields)) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $fields['priceSetId']; $priceField->find(); $check = array(); while ($priceField->fetch()) { if (!empty($fields["price_{$priceField->id}"])) { $check[] = $priceField->id; } } if (empty($check)) { $errors['_qf_default'] = ts("Select at least one option from Event Fee(s)."); } $lineItem = array(); require_once "CRM/Price/BAO/Set.php"; CRM_Price_BAO_Set::processAmount($self->_values['fee']['fields'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts("Event Fee(s) can not be less than zero. Please select the options accordingly"); } } if ($self->_values['event']['is_monetary']) { if (is_array($self->_paymentProcessor)) { $payment =& CRM_Core_Payment::singleton($self->_mode, 'Event', $self->_paymentProcessor, $this); $error = $payment->checkConfig($self->_mode); if ($error) { $errors['_qf_default'] = $error; } } // return if this is express mode $config =& CRM_Core_Config::singleton(); if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return empty($errors) ? true : $errors; } } $zeroAmount = $fields['amount']; // also return if paylater mode or zero fees for valid members if (CRM_Utils_Array::value('is_pay_later', $fields) || CRM_Utils_Array::value('bypass_payment', $fields)) { if (CRM_Utils_Array::value('priceSetId', $fields)) { foreach ($fields as $key => $val) { if (substr($key, 0, 6) == 'price_' && $val != 0) { return empty($errors) ? true : $errors; } } } else { return empty($errors) ? true : $errors; } } else { if (CRM_Utils_Array::value('priceSetId', $fields)) { //here take all value(amount) of optoin value id $check = array(); foreach ($fields as $key => $val) { if (substr($key, 0, 6) == 'price_' && $val != 0) { $htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_Field', substr($key, 6), 'html_type'); if (is_array($val)) { //$keys is the id of the option value foreach ($val as $keys => $vals) { if (!$keys) { continue; } $check[] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $keys, 'name'); } } else { if ($htmlType == 'Text') { $check[] = $val; } else { //$val is the id of the option value $check[] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $val, 'name'); } } } } //validation for submitted each value is zero //if not zero give credit card validation error else //bypass it. $level = count($check); $j = 0; for ($i = 0; $i < $level; $i++) { if ($check[$i] >= 0) { $j += $check[$i]; } } if ($j == 0) { return empty($errors) ? true : $errors; } } else { if ($zeroAmount) { if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $zeroAmount, 'value', 'id') == 0) { return empty($errors) ? true : $errors; } } } } //is pay later and priceset is used avoid credit card and //billing address validation if ((CRM_Utils_Array::value('is_pay_later', $fields) || CRM_Utils_Array::value('bypass_payment', $fields)) && $fields['priceSetId'] || !$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist)) { return empty($errors) ? true : $errors; } foreach ($self->_fields as $name => $fld) { if ($fld['is_required'] && CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))) { $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title'])); } } } // make sure that credit card number and cvv are valid require_once 'CRM/Utils/Rule.php'; if (CRM_Utils_Array::value('credit_card_type', $fields)) { if (CRM_Utils_Array::value('credit_card_number', $fields) && !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])) { $errors['credit_card_number'] = ts("Please enter a valid Credit Card Number"); } if (CRM_Utils_Array::value('cvv2', $fields) && !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])) { $errors['cvv2'] = ts("Please enter a valid Credit Card Verification Number"); } } $elements = array('email_greeting' => 'email_greeting_custom', 'postal_greeting' => 'postal_greeting_custom', 'addressee' => 'addressee_custom'); foreach ($elements as $greeting => $customizedGreeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && !CRM_Utils_Array::value($customizedGreeting, $fields)) { $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? true : $errors; }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $config = CRM_Core_Config::singleton(); parent::preProcess(); // lineItem isn't set until Register postProcess $this->_lineItem = $this->get('lineItem'); $this->_paymentProcessor = $this->get('paymentProcessor'); if ($this->_contributeMode == 'express') { // rfp == redirect from paypal $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'); if ($rfp) { $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this); $expressParams = $payment->getExpressCheckoutDetails($this->get('token')); $this->_params['payer'] = $expressParams['payer']; $this->_params['payer_id'] = $expressParams['payer_id']; $this->_params['payer_status'] = $expressParams['payer_status']; CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE); // fix state and country id if present if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"]) && $this->_params["billing_state_province_id-{$this->_bltID}"]) { $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) { $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } // set a few other parameters for PayPal $this->_params['token'] = $this->get('token'); $this->_params['amount'] = $this->get('amount'); if (!empty($this->_membershipBlock)) { $this->_params['selectMembership'] = $this->get('selectMembership'); } // we use this here to incorporate any changes made by folks in hooks $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['payment_action'] = 'Sale'; // also merge all the other values from the profile fields $values = $this->controller->exportValues('Main'); $skipFields = array('amount', 'amount_other', "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country_id-{$this->_bltID}"); foreach ($values as $name => $value) { // skip amount field if (!in_array($name, $skipFields)) { $this->_params[$name] = $value; } } $this->set('getExpressCheckoutDetails', $this->_params); } else { $this->_params = $this->get('getExpressCheckoutDetails'); } } else { $this->_params = $this->controller->exportValues('Main'); if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) { $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) { $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } if (isset($this->_params['credit_card_exp_date'])) { $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); } $this->_params['ip_address'] = $_SERVER['REMOTE_ADDR']; // hack for safari if ($this->_params['ip_address'] == '::1') { $this->_params['ip_address'] = '127.0.0.1'; } $this->_params['amount'] = $this->get('amount'); $this->_useForMember = $this->get('useForMember'); if (isset($this->_params['amount'])) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $this->_params['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $contriPriceId = NULL; $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_params['priceSetId'], 'is_quick_config'); while ($priceField->fetch()) { if ($priceField->name == "contribution_amount") { $contriPriceId = $priceField->id; } if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) { if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') { $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_FieldValue', $this->_params["price_{$priceField->id}"], 'label'); } if ($priceField->name == "membership_amount") { $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_FieldValue', $this->_params["price_{$priceField->id}"], 'membership_type_id'); } } else { if (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) && $this->_values['fee'][$priceField->id]['name'] == "other_amount" && CRM_Utils_Array::value("price_{$contriPriceId}", $this->_params) < 1 && !CRM_Utils_Array::value("price_{$priceField->id}", $this->_params)) { $this->_params['amount'] = null; } } } } $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['payment_action'] = 'Sale'; } $this->_params['is_pay_later'] = $this->get('is_pay_later'); $this->assign('is_pay_later', $this->_params['is_pay_later']); if ($this->_params['is_pay_later']) { $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']); } // if onbehalf-of-organization if (CRM_Utils_Array::value('hidden_onbehalf_profile', $this->_params)) { if (CRM_Utils_Array::value('org_option', $this->_params) && CRM_Utils_Array::value('organization_id', $this->_params)) { if (CRM_Utils_Array::value('onbehalfof_id', $this->_params)) { $this->_params['organization_id'] = $this->_params['onbehalfof_id']; } } $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name']; $addressBlocks = array('street_address', 'city', 'state_province', 'postal_code', 'country', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name'); $blocks = array('email', 'phone', 'im', 'url', 'openid'); foreach ($this->_params['onbehalf'] as $loc => $value) { $field = $typeId = NULL; if (strstr($loc, '-')) { list($field, $locType) = explode('-', $loc); } if (in_array($field, $addressBlocks)) { if ($locType == 'Primary') { require_once 'CRM/Core/BAO/LocationType.php'; $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locType = $defaultLocationType->id; } if ($field == 'country') { $value = CRM_Core_PseudoConstant::countryIsoCode($value); } elseif ($field == 'state_province') { $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value); } $isPrimary = 1; if (isset($this->_params['onbehalf_location']['address']) && count($this->_params['onbehalf_location']['address']) > 0) { $isPrimary = 0; } $this->_params['onbehalf_location']['address'][$locType][$field] = $value; if (!CRM_Utils_Array::value('is_primary', $this->_params['onbehalf_location']['address'][$locType])) { $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary; } $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType; } elseif (in_array($field, $blocks)) { if (!$typeId || is_numeric($typeId)) { $blockName = $fieldName = $field; $locationType = 'location_type_id'; if ($locType == 'Primary') { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locationValue = $defaultLocationType->id; } else { $locationValue = $locType; } $locTypeId = ''; if ($field == 'url') { $blockName = 'website'; $locationType = 'website_type_id'; $locationValue = $this->_params['onbehalf']["{$loc}-website_type_id"]; } elseif ($field == 'im') { $fieldName = 'name'; $locTypeId = 'provider_id'; $typeId = $this->_params['onbehalf']["{$loc}-provider_id"]; } elseif ($field == 'phone') { list($field, $locType, $typeId) = explode('-', $loc); $locTypeId = 'phone_type_id'; } $isPrimary = 1; if (isset($this->_params['onbehalf_location'][$blockName]) && count($this->_params['onbehalf_location'][$blockName]) > 0) { $isPrimary = 0; } if (!$locTypeId) { $this->_params['onbehalf_location'][$blockName][] = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary); } else { $this->_params['onbehalf_location'][$blockName][] = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary, $locTypeId => $typeId); } } } elseif (strstr($loc, 'custom')) { if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) { $value = $this->_params['onbehalf']["{$loc}_id"]; } $this->_params['onbehalf_location']["{$loc}"] = $value; } else { if ($loc == 'contact_sub_type') { $this->_params['onbehalf_location'][$loc] = $value; } else { $this->_params['onbehalf_location'][$field] = $value; } } } } elseif (CRM_Utils_Array::value('is_for_organization', $this->_values)) { // no on behalf of an organization, CRM-5519 // so reset loc blocks from main params. foreach (array('phone', 'email', 'address') as $blk) { if (isset($this->_params[$blk])) { unset($this->_params[$blk]); } } } // if auto renew checkbox is set, initiate a open-ended recurring membership if ((CRM_Utils_Array::value('selectMembership', $this->_params) || CRM_Utils_Array::value('priceSetId', $this->_params)) && CRM_Utils_Array::value('is_recur', $this->_paymentProcessor) && CRM_Utils_Array::value('auto_renew', $this->_params) && !CRM_Utils_Array::value('is_recur', $this->_params) && !CRM_Utils_Array::value('frequency_interval', $this->_params)) { $this->_params['is_recur'] = $this->_values['is_recur'] = 1; // check if price set is not quick config if (CRM_Utils_Array::value('priceSetId', $this->_params) && !$isQuickConfig) { list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_Set::getRecurDetails($this->_params['priceSetId']); } else { // FIXME: set interval and unit based on selected membership type $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_interval'); $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_unit'); } } if ($this->_pcpId) { $params = $this->processPcp($this, $this->_params); $this->_params = $params; } $this->_params['invoiceID'] = $this->get('invoiceID'); //carry campaign from profile. if (array_key_exists('contribution_campaign_id', $this->_params)) { $this->_params['campaign_id'] = $this->_params['contribution_campaign_id']; } $this->set('params', $this->_params); }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule(&$fields, &$files, $self) { $errors = array(); //check if contact is selected in standalone mode if (isset($fields[contact_select_id]) && !$fields[contact_select_id]) { $errors['contact'] = ts('Please select a contact or create new contact'); } if (isset($fields["honor_type_id"])) { if (!(CRM_Utils_Array::value('honor_first_name', $fields) && CRM_Utils_Array::value('honor_last_name', $fields) || CRM_Utils_Array::value('honor_email', $fields))) { $errors['honor_first_name'] = ts('Honor First Name and Last Name OR an email should be set.'); } } //check for Credit Card Contribution. if ($self->_mode) { if (empty($fields['payment_processor_id'])) { $errors['payment_processor_id'] = ts('Payment Processor is a required field.'); } } // do the amount validations. if (!CRM_Utils_Array::value('total_amount', $fields) && empty($self->_lineItems)) { if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) { // check for at least one positive // amount price field should be selected. $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $priceSetId; $priceField->find(); $priceFields = array(); while ($priceField->fetch()) { $key = "price_{$priceField->id}"; if (CRM_Utils_Array::value($key, $fields)) { $priceFields[$priceField->id] = $fields[$key]; } } if (!empty($priceFields)) { // we should has to have positive amount. $sql = "\nSELECT id, html_type \n FROM civicrm_price_field \n WHERE id IN (" . implode(',', array_keys($priceFields)) . ')'; $fieldDAO = CRM_Core_DAO::executeQuery($sql); $htmlTypes = array(); while ($fieldDAO->fetch()) { $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type; } // all field val present in option value except text. $setectedAmounts = $amountIds = array(); foreach ($htmlTypes as $fieldId => $type) { if ($type == 'Text') { $sql = "\n SELECT val.id, val.name \n FROM civicrm_option_value val\nLEFT JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id )\n WHERE grp.name = 'civicrm_price_field.amount.{$fieldId}'"; $textValue = CRM_Core_DAO::executeQuery($sql); while ($textValue->fetch()) { // calculate text price field amount here itself. $setectedAmounts[$textValue->id] = $priceFields[$fieldId] * $textValue->name; } } else { if (is_array($priceFields[$fieldId])) { $amountIds = array_merge($amountIds, array_keys($priceFields[$fieldId])); } else { $amountIds[] = $priceFields[$fieldId]; } } } if (!empty($amountIds)) { $sql = "\nSELECT id, name\n FROM civicrm_option_value \n WHERE id IN (" . implode(',', $amountIds) . ')'; $optionsDAO = CRM_Core_DAO::executeQuery($sql); while ($optionsDAO->fetch()) { $setectedAmounts[$optionsDAO->id] = $optionsDAO->name; } } // now we have all selected amount in hand. $totalAmount = array_sum($setectedAmounts); if ($totalAmount < 0) { $errors['_qf_default'] = ts("Contribution can not be less than zero. Please select the options accordingly."); } } else { $errors['_qf_default'] = ts("Please select at least one option from contribution price set."); } } else { $errors['total_amount'] = ts('Please enter a valid amount.'); } } return $errors; }
/** * Validate the priceset * * @param int $priceSetId, array $fields * * retrun the error string * * @access public * @static * */ public static function priceSetValidation($priceSetId, $fields, &$error) { // check for at least one positive // amount price field should be selected. $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $priceSetId; $priceField->find(); $priceFields = array(); while ($priceField->fetch()) { $key = "price_{$priceField->id}"; if (CRM_Utils_Array::value($key, $fields)) { $priceFields[$priceField->id] = $fields[$key]; } } if (!empty($priceFields)) { // we should has to have positive amount. $sql = "\nSELECT id, html_type \nFROM civicrm_price_field \nWHERE id IN (" . implode(',', array_keys($priceFields)) . ')'; $fieldDAO = CRM_Core_DAO::executeQuery($sql); $htmlTypes = array(); while ($fieldDAO->fetch()) { $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type; } // all field val present in option value except text. $selectedAmounts = $amountIds = array(); foreach ($htmlTypes as $fieldId => $type) { if ($type == 'Text') { $sql = "\nSELECT val.id, val.name \nFROM civicrm_option_value val\nLEFT JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id )\nWHERE grp.name = 'civicrm_price_field.amount.{$fieldId}'"; $textValue = CRM_Core_DAO::executeQuery($sql); while ($textValue->fetch()) { // calculate text price field amount here itself. $selectedAmounts[$textValue->id] = $priceFields[$fieldId] * $textValue->name; } } else { if (is_array($priceFields[$fieldId])) { $amountIds = array_merge($amountIds, array_keys($priceFields[$fieldId])); } else { $amountIds[] = $priceFields[$fieldId]; } } } if (!empty($amountIds)) { $sql = "\nSELECT id, name\nFROM civicrm_option_value \nWHERE id IN (" . implode(',', $amountIds) . ')'; $optionsDAO = CRM_Core_DAO::executeQuery($sql); while ($optionsDAO->fetch()) { $selectedAmounts[$optionsDAO->id] = $optionsDAO->name; } } list($componentName) = explode(':', $fields['_qf_default']); // now we have all selected amount in hand. $totalAmount = array_sum($selectedAmounts); if ($totalAmount < 0) { $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName)); } } else { $error['_qf_default'] = ts("Please select at least one option from price set."); } }
/** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self); //check for atleast one pricefields should be selected if (CRM_Utils_Array::value('priceSetId', $fields)) { $priceField = new CRM_Price_DAO_Field(); $priceField->price_set_id = $fields['priceSetId']; $priceField->find(); $check = array(); while ($priceField->fetch()) { if (!empty($fields["price_{$priceField->id}"])) { $check[] = $priceField->id; } } if (empty($check)) { if ($self->_useForMember == 1) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } require_once 'CRM/Price/BAO/Set.php'; if ($self->_useForMember == 1 && !empty($check)) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId])) { if (is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } else { $priceFieldIDS[] = $fields['price_' . $priceId]; } if (CRM_Utils_Array::value('options', $value)) { foreach ($value['options'] as $val) { if (CRM_Utils_Array::value('membership_type_id', $val)) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_Set::getMembershipCount($ids); foreach ($count as $id => $occurance) { if ($occurance > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } if (empty($priceFieldMemTypes)) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_Set::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks' && $self->_values['amount_block_is_active']) { require_once 'CRM/Contribute/DAO/Product.php'; require_once 'CRM/Utils/Money.php'; $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(true); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); } } if ($self->_values['honor_block_is_active'] && CRM_Utils_Array::value('honor_type_id', $fields)) { // make sure there is a first name and last name if email is not there if (!CRM_Utils_Array::value('honor_email', $fields)) { if (!CRM_Utils_Array::value('honor_first_name', $fields) || !CRM_Utils_Array::value('honor_last_name', $fields)) { $errors['honor_last_name'] = ts('In Honor Of - First Name and Last Name, OR an Email Address is required.'); } } } if (isset($fields['is_recur']) && $fields['is_recur']) { if ($fields['frequency_interval'] <= 0) { $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).'); } if ($fields['frequency_unit'] == '0') { $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).'); } } if (CRM_Utils_Array::value('is_recur', $fields) && $fields['is_pay_later']) { $errors['is_pay_later'] = ' '; $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } if (CRM_Utils_Array::value('is_for_organization', $fields) && !property_exists($self, 'organizationName')) { if (!CRM_Utils_Array::value('organization_name', $fields['onbehalf'])) { if (CRM_Utils_Array::value('org_option', $fields) && !$fields['onbehalfof_id']) { $errors['organization_id'] = ts('Please select an organization or enter a new one.'); } else { if (!CRM_Utils_Array::value('org_option', $fields)) { $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.'); } } } foreach ($fields['onbehalf'] as $key => $value) { if (strstr($key, 'email')) { $emailLocType = explode('-', $key); } } if (!CRM_Utils_Array::value("email-{$emailLocType[1]}", $fields['onbehalf'])) { $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.'); } } if (CRM_Utils_Array::value('selectMembership', $fields) && $fields['selectMembership'] != 'no_thanks') { require_once 'CRM/Member/BAO/Membership.php'; require_once 'CRM/Member/BAO/MembershipType.php'; if (!empty($self->_membershipTypeValues)) { $memTypeDetails = $self->_membershipTypeValues[$fields['selectMembership']]; } else { $memTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($self, $fields['selectMembership']); } if ($self->_values['amount_block_is_active'] && !CRM_Utils_Array::value('is_separate_payment', $self->_membershipBlock)) { require_once 'CRM/Utils/Money.php'; if ($amount < CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) { $errors['selectMembership'] = ts('The Membership you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($memTypeDetails['minimum_fee']))); } } else { if (CRM_Utils_Array::value('minimum_fee', $memTypeDetails)) { // we dont have an amount, so lets get an amount for cc checks $amount = $memTypeDetails['minimum_fee']; } } } if ($self->_values['is_monetary']) { //validate other amount. $checkOtherAmount = false; if (CRM_Utils_Array::value('amount', $fields) == 'amount_other_radio' || CRM_Utils_Array::value('amount_other', $fields)) { $checkOtherAmount = true; } $otherAmountVal = CRM_Utils_Array::value('amount_other', $fields); if ($checkOtherAmount || $otherAmountVal) { if (!$otherAmountVal) { $errors['amount_other'] = ts('Amount is required field.'); } //validate for min and max. if ($otherAmountVal) { $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors['amount_other'] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors['amount_other'] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && CRM_Utils_Array::value('pcp_display_in_roll', $fields) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (CRM_Utils_Array::value('pledge_block_id', $self->_values)) { //validation for pledge payment. if (CRM_Utils_Array::value('pledge_id', $self->_values)) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } else { if (CRM_Utils_Array::value('is_pledge', $fields)) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == false) { $errors['pledge_installments'] = ts('Please enter a valid pledge installment.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == null) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } else { if (CRM_Utils_array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } else { if (CRM_Utils_array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == false) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == null) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } else { if (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } } } // also return if paylater mode if (CRM_Utils_Array::value('is_pay_later', $fields)) { return empty($errors) ? true : $errors; } // if the user has chosen a free membership or the amount is less than zero // i.e. we skip calling the payment processor and hence dont need credit card // info if ((double) $amount <= 0.0) { return $errors; } foreach ($self->_fields as $name => $fld) { if ($fld['is_required'] && CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))) { $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title'])); } } // make sure that credit card number and cvv are valid require_once 'CRM/Utils/Rule.php'; if (CRM_Utils_Array::value('credit_card_type', $fields)) { if (CRM_Utils_Array::value('credit_card_number', $fields) && !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])) { $errors['credit_card_number'] = ts('Please enter a valid Credit Card Number'); } if (CRM_Utils_Array::value('cvv2', $fields) && !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])) { $errors['cvv2'] = ts('Please enter a valid Credit Card Verification Number'); } } $elements = array('email_greeting' => 'email_greeting_custom', 'postal_greeting' => 'postal_greeting_custom', 'addressee' => 'addressee_custom'); foreach ($elements as $greeting => $customizedGreeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && !CRM_Utils_Array::value($customizedGreeting, $fields)) { $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? true : $errors; }