/** * Set variables up before form is built. */ public function preProcess() { $this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE); $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE); if ($this->_crid) { $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid); $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit); $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval); $this->assign('amount', $this->_subscriptionDetails->amount); $this->assign('installments', $this->_subscriptionDetails->installments); // Are we cancelling a recurring contribution that is linked to an auto-renew membership? if ($this->_subscriptionDetails->membership_id) { $this->_mid = $this->_subscriptionDetails->membership_id; } } if ($this->_mid) { $this->_mode = 'auto_renew'; // CRM-18468: crid is more accurate than mid for getting // subscriptionDetails, so don't get them again. if (!$this->_crid) { $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership'); } $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id'); $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes)); } $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE); if ($this->_coid) { if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) { CRM_Core_Error::fatal(ts('The recurring contribution looks to have been cancelled already.')); } $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution'); $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit); $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval); $this->assign('amount', $this->_subscriptionDetails->amount); $this->assign('installments', $this->_subscriptionDetails->installments); } if (!$this->_crid && !$this->_coid && !$this->_mid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) { CRM_Core_Error::fatal('Required information missing.'); } if (!CRM_Core_Permission::check('edit contributions')) { $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE); if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) { CRM_Core_Error::fatal(ts('You do not have permission to cancel this recurring contribution.')); } $this->_selfService = TRUE; } $this->assign('self_service', $this->_selfService); // handle context redirection CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext(); CRM_Utils_System::setTitle($this->_mid ? ts('Cancel Auto-renewal') : ts('Cancel Recurring Contribution')); $this->assign('mode', $this->_mode); if ($this->_subscriptionDetails->contact_id) { list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id); } }
/** * Set variables up before form is built. * * @return void */ public function preProcess() { $this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE); $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE); if ($this->_crid) { $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info'); $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid); // Are we cancelling a recurring contribution that is linked to an auto-renew membership? if ($this->_subscriptionDetails->membership_id) { $this->_mid = $this->_subscriptionDetails->membership_id; } } $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE); if ($this->_coid) { $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info'); $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution'); } if ($this->_mid) { $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info'); $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj'); $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership'); $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id'); $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes)); $this->_mode = 'auto_renew'; } $this->_paymentProcessorObj = CRM_Utils_Array::value('object', $this->_paymentProcessor); if (!$this->_crid && !$this->_coid && !$this->_mid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) { CRM_Core_Error::fatal('Required information missing.'); } if (!CRM_Core_Permission::check('edit contributions')) { $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE); if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) { CRM_Core_Error::fatal(ts('You do not have permission to cancel subscription.')); } $this->_selfService = TRUE; } if (!$this->_paymentProcessor['object']->isSupported('updateSubscriptionBillingInfo')) { CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.", array(1 => $this->_paymentProcessor['object']->_processorName))); } $this->assign('paymentProcessor', $this->_paymentProcessor); // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); $this->_bltID = array_search('Billing', $locationTypes); $this->assign('bltID', $this->_bltID); if (!$this->_bltID) { CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing'))); } $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit); $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval); $this->assign('amount', $this->_subscriptionDetails->amount); $this->assign('installments', $this->_subscriptionDetails->installments); $this->assign('mode', $this->_mode); // handle context redirection CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext(); }
function setUp() { parent::setUp(); $this->_contactID = $this->individualCreate(); $this->_membershipTypeID = $this->membershipTypeCreate(array('member_of_contact_id' => $this->_contactID)); $this->_membershipStatusID = $this->membershipStatusCreate('test status'); CRM_Member_PseudoConstant::membershipType($this->_membershipTypeID, TRUE); CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'name', TRUE); }
/** * API to Create or update a Membership Type * * @param array $params an associative array of name/value property values of civicrm_membership_type * * @return array $result newly created or updated membership type property values. * @access public * {getfields MembershipType_get} */ function civicrm_api3_membership_type_create($params) { $ids['membershipType'] = CRM_Utils_Array::value('id', $params); $ids['memberOfContact'] = CRM_Utils_Array::value('member_of_contact_id', $params); $ids['contributionType'] = CRM_Utils_Array::value('financial_type_id', $params); $membershipTypeBAO = CRM_Member_BAO_MembershipType::add($params, $ids); $membershipType = array(); _civicrm_api3_object_to_array($membershipTypeBAO, $membershipType[$membershipTypeBAO->id]); CRM_Member_PseudoConstant::membershipType(NULL, TRUE); civicrm_api3('membership', 'getfields', array('cache_clear' => 1, 'fieldname' => 'membership_type_id')); civicrm_api3('profile', 'getfields', array('action' => 'submit', 'cache_clear' => 1)); return civicrm_api3_create_success($membershipType, $params, 'membership_type', 'create', $membershipTypeBAO); }
/** * Set up for tests. */ public function setUp() { parent::setUp(); $this->_apiversion = 3; $this->_contactID = $this->individualCreate(); $this->_membershipTypeID = $this->membershipTypeCreate(array('member_of_contact_id' => $this->_contactID)); $this->_membershipTypeID2 = $this->membershipTypeCreate(array('period_type' => 'fixed', 'fixed_period_start_day' => '301', 'fixed_period_rollover_day' => '1111')); $this->_membershipStatusID = $this->membershipStatusCreate('test status'); CRM_Member_PseudoConstant::membershipType(NULL, TRUE); CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'name', TRUE); CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name'); $this->_entity = 'Membership'; $this->_params = array('contact_id' => $this->_contactID, 'membership_type_id' => $this->_membershipTypeID, 'join_date' => '2009-01-21', 'start_date' => '2009-01-21', 'end_date' => '2009-12-21', 'source' => 'Payment', 'is_override' => 1, 'status_id' => $this->_membershipStatusID); }
/** * API to Create or update a Membership Type * * @param array $params an associative array of name/value property values of civicrm_membership_type * * @return array $result newly created or updated membership type property values. * @access public * {getfields MembershipType_get} */ function civicrm_api3_membership_type_create($params) { $values = $params; civicrm_api3_verify_mandatory($values, 'CRM_Member_DAO_MembershipType'); $ids['membershipType'] = CRM_Utils_Array::value('id', $values); $ids['memberOfContact'] = CRM_Utils_Array::value('member_of_contact_id', $values); $ids['contributionType'] = CRM_Utils_Array::value('contribution_type_id', $values); require_once 'CRM/Member/BAO/MembershipType.php'; $membershipTypeBAO = CRM_Member_BAO_MembershipType::add($values, $ids); $membershipType = array(); _civicrm_api3_object_to_array($membershipTypeBAO, $membershipType[$membershipTypeBAO->id]); CRM_Member_PseudoConstant::membershipType(NULL, TRUE); return civicrm_api3_create_success($membershipType, $params, 'membership_type', 'create', $membershipTypeBAO); }
function buildQuickForm() { $mtypes = CRM_Member_PseudoConstant::membershipType(); $this->add('select', 'rood_mtype', ts('Rood lidmaatschapstype'), $mtypes, true); $this->add('select', 'sp_mtype', ts('SP lidmaatschapstype'), $mtypes, true); $this->add('select', 'rood_mstatus', ts('Beeindig Rood met lidmaatschapstatus'), CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), true); foreach (CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label') as $sId => $sName) { $this->_membershipStatus = $this->addElement('checkbox', "member_status_id[{$sId}]", NULL, $sName); } $this->addDate('birth_date_from', ts('Birth date from'), false, array('formatType' => 'activityDate')); $this->addDate('birth_date_to', ts('Birth Date to'), false, array('formatType' => 'activityDate')); $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')); $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money'); // add buttons $this->addButtons(array(array('type' => 'submit', 'name' => ts('Upgrade ROOD lidmaatschappen'), 'isDefault' => TRUE))); }
/** * @deprecated - this function formats params according to v2 standards but * need to be sure about the impact of not calling it so retaining on the import class * take the input parameter list as specified in the data model and * convert it into the same format that we use in QF and BAO object * * @param array $params Associative array of property name/value * pairs to insert in new contact. * @param array $values The reformatted properties that we can use internally * * @param array $create Is the formatted Values array going to * be used for CRM_Member_BAO_Membership:create() * * @return array|error * @access public */ function membership_format_params($params, &$values, $create = FALSE) { require_once 'api/v3/utils.php'; $fields = CRM_Member_DAO_Membership::fields(); _civicrm_api3_store_values($fields, $params, $values); $customFields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($params as $key => $value) { // ignore empty values or empty arrays etc if (CRM_Utils_System::isNull($value)) { continue; } //Handling Custom Data if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { $values[$key] = $value; $type = $customFields[$customFieldID]['html_type']; if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') { $mulValues = explode(',', $value); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); $values[$key] = array(); foreach ($mulValues as $v1) { foreach ($customOption as $customValueID => $customLabel) { $customValue = $customLabel['value']; if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) { if ($type == 'CheckBox') { $values[$key][$customValue] = 1; } else { $values[$key][] = $customValue; } } } } } } switch ($key) { case 'membership_contact_id': if (!CRM_Utils_Rule::integer($value)) { throw new Exception("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams); if (!$svq) { throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } $values['contact_id'] = $values['membership_contact_id']; unset($values['membership_contact_id']); break; case 'membership_type_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) { throw new Exception('Invalid Membership Type Id'); } $values[$key] = $value; break; case 'membership_type': $membershipTypeId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipType()); if ($membershipTypeId) { if (CRM_Utils_Array::value('membership_type_id', $values) && $membershipTypeId != $values['membership_type_id']) { throw new Exception('Mismatched membership Type and Membership Type Id'); } } else { throw new Exception('Invalid Membership Type'); } $values['membership_type_id'] = $membershipTypeId; break; case 'status_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) { throw new Exception('Invalid Membership Status Id'); } $values[$key] = $value; break; case 'membership_status': $membershipStatusId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipStatus()); if ($membershipStatusId) { if (CRM_Utils_Array::value('status_id', $values) && $membershipStatusId != $values['status_id']) { throw new Exception('Mismatched membership Status and Membership Status Id'); } } else { throw new Exception('Invalid Membership Status'); } $values['status_id'] = $membershipStatusId; break; default: break; } } _civicrm_api3_custom_format_params($params, $values, 'Membership'); if ($create) { // CRM_Member_BAO_Membership::create() handles membership_start_date, // membership_end_date and membership_source. So, if $values contains // membership_start_date, membership_end_date or membership_source, // convert it to start_date, end_date or source $changes = array('membership_start_date' => 'start_date', 'membership_end_date' => 'end_date', 'membership_source' => 'source'); foreach ($changes as $orgVal => $changeVal) { if (isset($values[$orgVal])) { $values[$changeVal] = $values[$orgVal]; unset($values[$orgVal]); } } } return NULL; }
/** * Build the form object. * * @return void */ public function buildQuickForm() { if ($this->_action == CRM_Core_Action::UPDATE) { $finTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_oid, 'financial_type_id'); CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::UPDATE); if (!array_key_exists($finTypeId, $financialTypes)) { CRM_Core_Error::fatal(ts("You do not have permission to access this page")); } } if ($this->_action == CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete')), array('type' => 'cancel', 'name' => ts('Cancel')))); return NULL; } else { $attributes = CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceFieldValue'); // lets trim all the whitespace $this->applyFilter('__ALL__', 'trim'); // hidden Option Id for validation use $this->add('hidden', 'optionId', $this->_oid); // Needed for i18n dialog $this->assign('optionId', $this->_oid); //hidden field ID for validation use $this->add('hidden', 'fieldId', $this->_fid); // label $this->add('text', 'label', ts('Option Label'), NULL, TRUE); $memberComponentId = CRM_Core_Component::getComponentID('CiviMember'); if ($this->_action == CRM_Core_Action::UPDATE) { $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this); } elseif ($this->_action == CRM_Core_Action::ADD || $this->_action == CRM_Core_Action::VIEW) { $this->_sid = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'price_set_id', 'id'); } $this->isEvent = FALSE; $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id'); $this->assign('showMember', FALSE); if ($memberComponentId == $extendComponentId) { $this->assign('showMember', TRUE); $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $this->add('select', 'membership_type_id', ts('Membership Type'), array('' => ' ') + $membershipTypes, FALSE, array('onClick' => "calculateRowValues( );")); $this->add('text', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']); } else { $allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId); $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent'); if (in_array($eventComponentId, $allComponents)) { $this->isEvent = TRUE; // count $this->add('text', 'count', ts('Participant Count')); $this->addRule('count', ts('Please enter a valid Max Participants.'), 'positiveInteger'); $this->add('text', 'max_value', ts('Max Participants')); $this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger'); } } //Financial Type $financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType(); if (count($financialType)) { $this->assign('financialType', $financialType); } $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + $financialType, TRUE); //CRM_Core_DAO::getFieldValue( 'CRM_Price_DAO_PriceField', $this->_fid, 'weight', 'id' ); // FIX ME: duplicate rule? /* $this->addRule( 'label', ts('Duplicate option label.'), 'optionExists', array( 'CRM_Core_DAO_OptionValue', $this->_oid, $this->_ogId, 'label' ) ); */ // value $this->add('text', 'amount', ts('Option Amount'), NULL, TRUE); // the above value is used directly by QF, so the value has to be have a rule // please check with Lobo before u comment this $this->registerRule('amount', 'callback', 'money', 'CRM_Utils_Rule'); $this->addRule('amount', ts('Please enter a monetary value for this field.'), 'money'); $this->add('textarea', 'description', ts('Description')); $this->add('textarea', 'help_pre', ts('Pre Option Help')); $this->add('textarea', 'help_post', ts('Post Option Help')); // weight $this->add('text', 'weight', ts('Order'), NULL, TRUE); $this->addRule('weight', ts('is a numeric field'), 'numeric'); // is active ? $this->add('checkbox', 'is_active', ts('Active?')); //is default $this->add('checkbox', 'is_default', ts('Default')); if ($this->_fid) { //hide the default checkbox option for text field $htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $this->_fid, 'html_type'); $this->assign('hideDefaultOption', FALSE); if ($htmlType == 'Text') { $this->assign('hideDefaultOption', TRUE); } } // add buttons $this->addButtons(array(array('type' => 'next', 'name' => ts('Save')), array('type' => 'cancel', 'name' => ts('Cancel')))); // if view mode pls freeze it with the done button. if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); $this->addButtons(array(array('type' => 'cancel', 'name' => ts('Done'), 'isDefault' => TRUE))); } } $this->addFormRule(array('CRM_Price_Form_Option', 'formRule'), $this); }
/** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param CRM_Core_Form $self * * @return bool|array * true if no errors, else array of errors */ public static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self->_values); if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.'); } if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) { $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE; $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE); $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(); $unallowedOrgs = array(); foreach (array_keys($lifeMember) as $memTypeId) { $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]; } } //check for atleast one pricefields should be selected if (!empty($fields['priceSetId']) && empty($self->_ccid)) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $fields['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $membershipIsActive = TRUE; $previousId = $otherAmount = FALSE; while ($priceField->fetch()) { if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) { $previousId = $priceField->id; if ($priceField->name == 'membership_amount' && !$priceField->is_active) { $membershipIsActive = FALSE; } } if ($priceField->name == 'other_amount') { if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) { $otherAmount = $priceField->id; } elseif (!empty($fields["price_{$priceField->id}"])) { $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]); $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) { $check[] = $priceField->id; } } $currentMemberships = NULL; if ($membershipIsActive) { $is_test = $self->_mode != 'live' ? 1 : 0; $memContactID = $self->_membershipContactID; // For anonymous user check using dedupe rule // if user has Cancelled Membership if (!$memContactID) { $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); // if we find more than one contact, use the first one $memContactID = CRM_Utils_Array::value(0, $ids); } $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test); $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.'; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) { if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) { if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id']))); } } else { if (is_array($fields['price_' . $fieldKey])) { foreach (array_keys($fields['price_' . $fieldKey]) as $key) { if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id']))); } } } } } } } // CRM-12233 if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) { $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { // if 'No thank you' membership is selected then set $membershipFieldId if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) { $membershipFieldId = $fieldKey; } elseif ($membershipFieldId) { if ($fieldValue['name'] == 'other_amount') { $otherFieldId = $fieldKey; } elseif ($fieldValue['name'] == 'contribution_amount') { $contributionFieldId = $fieldKey; } if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') { $errorKey = $fieldKey; } } } // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) { $errors["price_{$errorKey}"] = ts('Additional Contribution is required.'); } } if (empty($check) && empty($self->_ccid)) { if ($self->_useForMember == 1 && $membershipIsActive) { $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).'); } } if ($otherAmount && !empty($check)) { $errors["price_{$otherAmount}"] = ts('Amount is required field.'); } if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) { if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) { // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577 $priceFieldIDS[] = $fields['price_' . $priceId]; } if (!empty($value['options'])) { foreach ($value['options'] as $val) { if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } if (!empty($lifeMember)) { foreach ($priceFieldIDS as $priceFieldId) { if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) { $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.'); break; } } } if (!empty($priceFieldIDS)) { $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids); foreach ($count as $id => $occurrence) { if ($occurrence > 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) && $self->_membershipBlock['is_required'] == 1) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_PriceSet::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') { $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))); CRM_Core_Session::setStatus($errors['selectProduct']); } } //CRM-16285 - Function to handle validation errors on form, for recurring contribution field. CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors); if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && 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 && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (!empty($self->_values['pledge_block_id'])) { //validation for pledge payment. if (!empty($self->_values['pledge_id'])) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } elseif (!empty($fields['is_pledge'])) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) { $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } elseif (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.'); } elseif (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.'); } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } // if the user has chosen a free membership or the amount is less than zero // i.e. we don't need to validate payment related fields or profiles. if ((double) $amount <= 0.0) { return $errors; } if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) { $errors['payment_processor_id'] = ts('Payment Method is a required field.'); } else { CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing'); } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) { $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? TRUE : $errors; }
/** * Cancel Recurring contribution. * * @param int $recurId * Recur contribution id. * @param array $objects * An array of objects that is to be cancelled like. * contribution, membership, event. At least contribution object is a must. * * @param array $activityParams * * @return bool */ public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) { if (!$recurId) { return FALSE; } $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $canceledId = array_search('Cancelled', $contributionStatus); $recur = new CRM_Contribute_DAO_ContributionRecur(); $recur->id = $recurId; $recur->whereAdd("contribution_status_id != {$canceledId}"); if ($recur->find(TRUE)) { $transaction = new CRM_Core_Transaction(); $recur->contribution_status_id = $canceledId; $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date); $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date); $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date); $recur->cancel_date = date('YmdHis'); $recur->save(); $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId); if ($dao && $dao->recur_id) { $details = CRM_Utils_Array::value('details', $activityParams); if ($dao->auto_renew && $dao->membership_id) { // its auto-renewal membership mode $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id'); $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes); $details .= ' <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType)); } else { $details .= ' <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(1 => $dao->amount, 2 => $dao->frequency_interval, 3 => $dao->frequency_unit)); } $activityParams = array('source_contact_id' => $dao->contact_id, 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams), 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Cancel Recurring Contribution', 'name'), 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')), 'details' => $details, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); if ($cid) { $activityParams['target_contact_id'][] = $activityParams['source_contact_id']; $activityParams['source_contact_id'] = $cid; } CRM_Activity_BAO_Activity::create($activityParams); } // if there are associated objects, cancel them as well if ($objects == CRM_Core_DAO::$_nullObject) { $transaction->commit(); return TRUE; } else { $baseIPN = new CRM_Core_Payment_BaseIPN(); return $baseIPN->cancelled($objects, $transaction); } } else { // if already cancelled, return true $recur->whereAdd(); $recur->whereAdd("contribution_status_id = {$canceledId}"); if ($recur->find(TRUE)) { return TRUE; } } return FALSE; }
function alterMembershipTypeID($value, &$row) { return is_string(CRM_Member_PseudoConstant::membershipType($value, FALSE)) ? CRM_Member_PseudoConstant::membershipType($value, FALSE) : ''; }
/** * Retrieve list of Scheduled Reminders * * @param bool $namesOnly return simple list of names * * @param null $entityValue * @param null $id * * @return array (reference) reminder list * @static * @access public */ static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) { $activity_type = CRM_Core_PseudoConstant::activityType(TRUE, TRUE); $activity_status = CRM_Core_PseudoConstant::activityStatus(); $event_type = CRM_Event_PseudoConstant::eventType(); $civicrm_event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); $civicrm_participant_status_type = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'); $event_template = CRM_Event_PseudoConstant::eventTemplates(); $civicrm_contact = self::getDateFields(); $auto_renew_options = CRM_Core_OptionGroup::values('auto_renew_options'); $contact_date_reminder_options = CRM_Core_OptionGroup::values('contact_date_reminder_options'); $civicrm_membership_type = CRM_Member_PseudoConstant::membershipType(); $entity = array('civicrm_activity' => 'Activity', 'civicrm_participant' => 'Event', 'civicrm_membership' => 'Member', 'civicrm_contact' => 'Contact'); $query = "\nSELECT\n title,\n cam.entity,\n cas.id as id,\n cam.entity_value as entityValue,\n cas.entity_value as entityValueIds,\n cam.entity_status as entityStatus,\n cas.entity_status as entityStatusIds,\n cas.start_action_date as entityDate,\n cas.start_action_offset,\n cas.start_action_unit,\n cas.start_action_condition,\n cas.absolute_date,\n is_repeat,\n is_active\n\nFROM civicrm_action_schedule cas\nLEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)\n"; $params = CRM_Core_DAO::$_nullArray; if ($entityValue and $id) { $where = "\nWHERE cas.entity_value = {$id} AND\n cam.entity_value = '{$entityValue}'"; $query .= $where; $params = array(1 => array($id, 'Integer'), 2 => array($entityValue, 'String')); } $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $list[$dao->id]['id'] = $dao->id; $list[$dao->id]['title'] = $dao->title; $list[$dao->id]['start_action_offset'] = $dao->start_action_offset; $list[$dao->id]['start_action_unit'] = $dao->start_action_unit; $list[$dao->id]['start_action_condition'] = $dao->start_action_condition; $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate)); $list[$dao->id]['absolute_date'] = $dao->absolute_date; $status = $dao->entityStatus; $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds); foreach ($statusArray as &$s) { $s = CRM_Utils_Array::value($s, ${$status}); } $statusIds = implode(', ', $statusArray); $value = $dao->entityValue; $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds); foreach ($valueArray as &$v) { $v = CRM_Utils_Array::value($v, ${$value}); } $valueIds = implode(', ', $valueArray); $list[$dao->id]['entity'] = $entity[$dao->entity]; $list[$dao->id]['value'] = $valueIds; $list[$dao->id]['status'] = $statusIds; $list[$dao->id]['is_repeat'] = $dao->is_repeat; $list[$dao->id]['is_active'] = $dao->is_active; } return $list; }
/** * Function to build profile form * * @params object $form form object * @params array $field array field properties * @params int $mode profile mode * @params int $contactID contact id * * @return null * @static * @access public */ static function buildProfile(&$form, &$field, $mode, $contactId = null, $online = false) { require_once "CRM/Profile/Form.php"; require_once "CRM/Core/OptionGroup.php"; require_once 'CRM/Core/BAO/UFField.php'; require_once 'CRM/Contact/BAO/ContactType.php'; $defaultValues = array(); $fieldName = $field['name']; $title = $field['title']; $attributes = $field['attributes']; $rule = $field['rule']; $view = $field['is_view']; $required = $mode == CRM_Profile_Form::MODE_SEARCH ? false : $field['is_required']; $search = $mode == CRM_Profile_Form::MODE_SEARCH ? true : false; // do not display view fields in drupal registration form // CRM-4632 if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) { return; } if ($contactId && !$online) { $name = "field[{$contactId}][{$fieldName}]"; } else { $name = $fieldName; } require_once 'CRM/Core/BAO/Preferences.php'; $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true); if (substr($fieldName, 0, 14) === 'state_province') { $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(), $required); } else { if (substr($fieldName, 0, 7) === 'country') { $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required); $config =& CRM_Core_Config::singleton(); if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) { $defaultValues[$name] = $config->defaultContactCountry; $form->setDefaults($defaultValues); } } else { if (substr($fieldName, 0, 6) === 'county') { if ($addressOptions['county']) { $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::county(), $required); } } else { if (substr($fieldName, 0, 2) === 'im') { if (!$contactId) { $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::IMProvider(), $required); if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) { $form->freeze($name . "-provider_id"); } } $form->add('text', $name, $title, $attributes, $required); } else { if ($fieldName === 'birth_date' || $fieldName === 'deceased_date') { $form->addDate($name, $title, $required, array('formatType' => 'birth')); } else { if (in_array($fieldName, array("membership_start_date", "membership_end_date", "join_date"))) { $form->addDate($name, $title, $required, array('formatType' => 'custom')); } else { if ($field['name'] == 'membership_type_id') { require_once 'CRM/Member/PseudoConstant.php'; $form->add('select', 'membership_type_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipType(), $required); } else { if ($field['name'] == 'status_id') { require_once 'CRM/Member/PseudoConstant.php'; $form->add('select', 'status_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(), $required); } else { if ($fieldName === 'gender') { $genderOptions = array(); $gender = CRM_Core_PseudoConstant::gender(); foreach ($gender as $key => $var) { $genderOptions[$key] = HTML_QuickForm::createElement('radio', null, ts('Gender'), $var, $key); } $form->addGroup($genderOptions, $name, $title); if ($required) { $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required'); } } else { if ($fieldName === 'individual_prefix') { $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualPrefix(), $required); } else { if ($fieldName === 'individual_suffix') { $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualSuffix(), $required); } else { if ($fieldName === 'contact_sub_type') { $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $form->_fields[$fieldName]); $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : null; $setSubtype = false; if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) { $setSubtype = $profileType; $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType); } $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array(); if ($setSubtype) { $subtypeList = array(); $subtypeList[$setSubtype] = $subtypes[$setSubtype]; } else { $subtypeList = array('' => ts('- select -')) + $subtypes; } $form->add('select', $name, $title, $subtypeList, $required); } else { if (in_array($fieldName, array('email_greeting', 'postal_greeting', 'addressee'))) { //add email greeting, postal greeting, addressee, CRM-4575 $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field); $profileType = CRM_Core_BAO_UFField::getProfileType($gId, true, false, true); if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) { $profileType = 'Individual'; } if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) { $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType); } if ($fieldName == 'email_greeting') { $emailGreeting = array('contact_type' => $profileType, 'greeting_type' => 'email_greeting'); $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($emailGreeting), $required); // adding custom email greeting element alongwith email greeting $form->add('text', 'email_greeting_custom', ts('Custom Email Greeting'), null, false); } else { if ($fieldName === 'postal_greeting') { $postalGreeting = array('contact_type' => $profileType, 'greeting_type' => 'postal_greeting'); $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($postalGreeting), $required); // adding custom postal greeting element alongwith postal greeting $form->add('text', 'postal_greeting_custom', ts('Custom Postal Greeting'), null, false); } else { if ($fieldName === 'addressee') { $addressee = array('contact_type' => $profileType, 'greeting_type' => 'addressee'); $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($addressee), $required); // adding custom addressee element alongwith addressee type $form->add('text', 'addressee_custom', ts('Custom Addressee'), null, false); } } } } else { if ($fieldName === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::pcm(); foreach ($communicationFields as $key => $var) { if ($key == '') { continue; } $communicationOptions[] =& HTML_QuickForm::createElement('checkbox', $key, null, $var); } $form->addGroup($communicationOptions, $name, $title, '<br/>'); } else { if ($fieldName === 'preferred_mail_format') { $form->add('select', $name, $title, CRM_Core_SelectValues::pmf()); } else { if ($fieldName == 'external_identifier') { $form->add('text', $name, $title, $attributes, $required); $contID = $contactId; if (!$contID) { $contID = $form->get('id'); } $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier')); } else { if ($fieldName === 'group') { require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php'; CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, true, $required, $title, null, $name); } else { if ($fieldName === 'tag') { require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php'; CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, false, $required, null, $title, $name); } else { if ($fieldName === 'home_URL') { $form->addElement('text', $name, $title, array_merge(CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'home_URL'), array('onfocus' => "if (!this.value) this.value='http://'; else return false", 'onblur' => "if ( this.value == 'http://') this.value=''; else return false"))); $form->addRule($name, ts('Enter a valid Website.'), 'url'); } else { if (substr($fieldName, 0, 6) === 'custom') { $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName); if ($customFieldID) { CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, false, $required, $search, $title); } } else { if (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) { $form->addDate($name, $title, $required, array('formatType' => 'custom')); } else { if ($fieldName == 'payment_instrument') { require_once "CRM/Contribute/PseudoConstant.php"; $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required); } else { if ($fieldName == 'contribution_type') { require_once "CRM/Contribute/PseudoConstant.php"; $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), $required); } else { if ($fieldName == 'contribution_status_id') { require_once "CRM/Contribute/PseudoConstant.php"; $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionStatus(), $required); } else { if ($fieldName == 'participant_register_date') { $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime')); } else { if ($fieldName == 'participant_status_id') { require_once "CRM/Event/PseudoConstant.php"; $cond = null; if ($online == true) { $cond = "visibility_id = 1"; } $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(null, $cond), $required); } else { if ($fieldName == 'participant_role_id') { require_once "CRM/Event/PseudoConstant.php"; $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required); } else { if ($fieldName == 'scholarship_type_id') { $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('scholarship_type', true))); } else { if ($fieldName == 'applicant_status_id') { $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('applicant_status', true))); } else { if ($fieldName == 'highschool_gpa_id') { $form->add('select', $name, $title, array("" => "-- Select -- ") + CRM_Core_OptionGroup::values('highschool_gpa')); } else { if ($fieldName == 'world_region') { require_once "CRM/Core/PseudoConstant.php"; $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::worldRegion(), $required); } else { $processed = false; if (CRM_Core_Permission::access('Quest', false)) { require_once 'CRM/Quest/BAO/Student.php'; $processed = CRM_Quest_BAO_Student::buildStudentForm($form, $fieldName, $title, $contactId); } if (!$processed) { if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') { $form->add('checkbox', $name, $title, $attributes, $required); } else { $form->add('text', $name, $title, $attributes, $required); } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } static $hiddenSubtype = false; if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) { // In registration mode params are submitted via POST and we don't have any clue // about profile-id or the profile-type (which could be a subtype) // To generalize the behavior and simplify the process, // lets always add the hidden //subtype value if there is any, and we won't have to // compute it while processing. $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']); $hiddenSubtype = true; } if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) { $form->freeze($name); } //add the rules if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) { $form->addRule($name, ts('Please enter a valid amount.'), 'money'); } if ($rule) { if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) { $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule); } } }
function alterDisplay(&$rows) { // custom code to alter rows $entryFound = false; $checkList = array(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // not repeat contact display names if it matches with the one // in previous row $repeatFound = false; foreach ($row as $colName => $colVal) { if (CRM_Utils_Array::value($colName, $checkList) && is_array($checkList[$colName]) && in_array($colVal, $checkList[$colName])) { $rows[$rowNum][$colName] = ""; $repeatFound = true; } if (in_array($colName, $this->_noRepeats)) { $checkList[$colName][] = $colVal; } } } if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, false); } $entryFound = true; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, false); } $entryFound = true; } if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, false); } $entryFound = true; } if (array_key_exists('civicrm_contact_display_name', $row) && $rows[$rowNum]['civicrm_contact_display_name'] && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_display_name_link'] = $url; $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact Summary for this Contact."); $entryFound = true; } if (!$entryFound) { break; } } }
/** * handle the values in summary mode * * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function summary(&$values) { $erroneousField = null; $response = $this->setActiveFieldValues($values, $erroneousField); $errorRequired = false; if ($this->_membershipTypeIndex < 0) { $errorRequired = true; } else { $errorRequired = !CRM_Utils_Array::value($this->_membershipTypeIndex, $values); } if ($errorRequired) { array_unshift($values, ts('Missing required fields')); return CRM_Member_Import_Parser::ERROR; } $params =& $this->getActiveFieldParams(); require_once 'CRM/Import/Parser/Contact.php'; $errorMessage = null; //To check whether start date or join date is provided if (!$params['membership_start_date'] && !$params['join_date']) { $errorMessage = "Membership Start Date is required to create a memberships."; CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } //end //for date-Formats $session =& CRM_Core_Session::singleton(); $dateType = $session->get("dateTypes"); foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } break; case 'membership_start_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } break; case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage); } break; case 'membership_type_id': if (!CRM_Utils_Array::crmInArray($val, CRM_Member_PseudoConstant::membershipType())) { CRM_Import_Parser_Contact::addToErrorMsg('Membership Type', $errorMessage); } break; case 'status_id': if (!CRM_Utils_Array::crmInArray($val, CRM_Member_PseudoConstant::membershipStatus())) { CRM_Import_Parser_Contact::addToErrorMsg('Membership Status', $errorMessage); } break; case 'email': if (!CRM_Utils_Rule::email($val)) { CRM_Import_Parser_Contact::addToErrorMsg('Email Address', $errorMessage); } } } } //date-Format part ends $params['contact_type'] = 'Membership'; //checking error in custom data CRM_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage); if ($errorMessage) { $tempMsg = "Invalid value for field(s) : {$errorMessage}"; array_unshift($values, $tempMsg); $errorMessage = null; return CRM_Import_Parser::ERROR; } return CRM_Member_Import_Parser::VALID; }
/** * Build the form object. */ public function buildQuickForm() { // lets trim all the whitespace $this->applyFilter('__ALL__', 'trim'); // add a hidden field to remember the price set id // this get around the browser tab issue $this->add('hidden', 'sid', $this->_sid); $this->add('hidden', 'fid', $this->_fid); // label $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'label'), TRUE); // html_type $javascript = 'onchange="option_html_type(this.form)";'; $htmlTypes = CRM_Price_BAO_PriceField::htmlTypes(); // Text box for Participant Count for a field // Financial Type $financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType(); foreach ($financialType as $finTypeId => $type) { if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !CRM_Core_Permission::check('add contributions of type ' . $type)) { unset($financialType[$finTypeId]); } } if (count($financialType)) { $this->assign('financialType', $financialType); } $enabledComponents = CRM_Core_Component::getEnabledComponents(); $eventComponentId = $memberComponentId = NULL; if (array_key_exists('CiviEvent', $enabledComponents)) { $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent'); } if (array_key_exists('CiviMember', $enabledComponents)) { $memberComponentId = CRM_Core_Component::getComponentID('CiviMember'); } $attributes = CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceFieldValue'); $this->add('select', 'financial_type_id', ts('Financial Type'), array(' ' => ts('- select -')) + $financialType); $this->assign('useForMember', FALSE); if (in_array($eventComponentId, $this->_extendComponentId)) { $this->add('text', 'count', ts('Participant Count'), $attributes['count']); $this->addRule('count', ts('Participant Count should be a positive number'), 'positiveInteger'); $this->add('text', 'max_value', ts('Max Participants'), $attributes['max_value']); $this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger'); $this->assign('useForEvent', TRUE); } else { if (in_array($memberComponentId, $this->_extendComponentId)) { $this->_useForMember = 1; $this->assign('useForMember', $this->_useForMember); } $this->assign('useForEvent', FALSE); } $sel = $this->add('select', 'html_type', ts('Input Field Type'), $htmlTypes, TRUE, $javascript); // price (for text inputs) $this->add('text', 'price', ts('Price')); $this->registerRule('price', 'callback', 'money', 'CRM_Utils_Rule'); $this->addRule('price', ts('must be a monetary value'), 'money'); if ($this->_action == CRM_Core_Action::UPDATE) { $this->freeze('html_type'); } // form fields of Custom Option rows $_showHide = new CRM_Core_ShowHideBlocks('', ''); for ($i = 1; $i <= self::NUM_OPTION; $i++) { //the show hide blocks $showBlocks = 'optionField_' . $i; if ($i > 2) { $_showHide->addHide($showBlocks); if ($i == self::NUM_OPTION) { $_showHide->addHide('additionalOption'); } } else { $_showHide->addShow($showBlocks); } // label $attributes['label']['size'] = 25; $this->add('text', 'option_label[' . $i . ']', ts('Label'), $attributes['label']); // amount $this->add('text', 'option_amount[' . $i . ']', ts('Amount'), $attributes['amount']); $this->addRule('option_amount[' . $i . ']', ts('Please enter a valid amount for this field.'), 'money'); //Financial Type $this->add('select', 'option_financial_type_id[' . $i . ']', ts('Financial Type'), array('' => ts('- select -')) + $financialType); if (in_array($eventComponentId, $this->_extendComponentId)) { // count $this->add('text', 'option_count[' . $i . ']', ts('Participant Count'), $attributes['count']); $this->addRule('option_count[' . $i . ']', ts('Please enter a valid Participants Count.'), 'positiveInteger'); // max_value $this->add('text', 'option_max_value[' . $i . ']', ts('Max Participants'), $attributes['max_value']); $this->addRule('option_max_value[' . $i . ']', ts('Please enter a valid Max Participants.'), 'positiveInteger'); // description //$this->add('textArea', 'option_description['.$i.']', ts('Description'), array('rows' => 1, 'cols' => 40 )); } elseif (in_array($memberComponentId, $this->_extendComponentId)) { $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $js = array('onchange' => "calculateRowValues( {$i} );"); $this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'), array('' => ' ') + $membershipTypes, FALSE, $js); $this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array::value('membership_num_terms', $attributes)); } // weight $this->add('text', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']); // is active ? $this->add('checkbox', 'option_status[' . $i . ']', ts('Active?')); $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i); //for checkbox handling of default option $this->add('checkbox', "default_checkbox_option[{$i}]", NULL); } //default option selection $this->addGroup($defaultOption, 'default_option'); $_showHide->addToTemplate(); // is_display_amounts $this->add('checkbox', 'is_display_amounts', ts('Display Amount?')); // weight $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE); $this->addRule('weight', ts('is a numeric field'), 'numeric'); // checkbox / radio options per line $this->add('text', 'options_per_line', ts('Options Per Line')); $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric'); // help post, mask, attributes, javascript ? $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')); // active_on $date_options = array('format' => 'dmY His', 'minYear' => date('Y') - 1, 'maxYear' => date('Y') + 5, 'addEmptyOption' => TRUE); $this->addDateTime('active_on', ts('Active On'), FALSE, array('formatType' => 'activityDateTime')); // expire_on $this->addDateTime('expire_on', ts('Expire On'), FALSE, array('formatType' => 'activityDateTime')); // is required ? $this->add('checkbox', 'is_required', ts('Required?')); // is active ? $this->add('checkbox', 'is_active', ts('Active?')); // add buttons $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => TRUE), array('type' => 'next', 'name' => ts('Save and New'), 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel')))); // is public? $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility()); // add a form rule to check default value $this->addFormRule(array('CRM_Price_Form_Field', 'formRule'), $this); // if view mode pls freeze it with the done button. if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); $url = CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid); $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='{$url}'")); } }
/** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { $entryFound = FALSE; $checkList = array(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // not repeat contact display names if it matches with the one // in previous row $repeatFound = FALSE; foreach ($row as $colName => $colVal) { if (!empty($checkList[$colName]) && is_array($checkList[$colName]) && in_array($colVal, $checkList[$colName])) { $rows[$rowNum][$colName] = ""; $repeatFound = TRUE; } if (in_array($colName, $this->_noRepeats)) { $checkList[$colName][] = $colVal; } } } //handle the Membership Type Ids if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE); } $entryFound = TRUE; } // handle state province if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } // convert display name to links if (array_key_exists('civicrm_contact_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Report_Utils_Report::getNextUrl('member/detail', 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'], $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Membership Detail for this Contact."); } // If using campaigns, convert campaign_id to campaign title if (array_key_exists('civicrm_membership_campaign_id', $row)) { if ($value = $row['civicrm_membership_campaign_id']) { $rows[$rowNum]['civicrm_membership_campaign_id'] = $this->activeCampaigns[$value]; } $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } }
static function extractGroupTypes($groupType) { $returnGroupTypes = array(); if (!$groupType) { return $returnGroupTypes; } $groupTypeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $groupType); foreach (explode(',', $groupTypeParts[0]) as $type) { $returnGroupTypes[$type] = $type; } if (CRM_Utils_Array::value(1, $groupTypeParts)) { foreach (explode(',', $groupTypeParts[1]) as $typeValue) { $groupTypeValues = $valueLabels = array(); $valueParts = explode(':', $typeValue); $typeName = NULL; switch ($valueParts[0]) { case 'ContributionType': $typeName = 'Contribution'; $valueLabels = CRM_Contribute_PseudoConstant::financialType(); break; case 'ParticipantRole': $typeName = 'Participant'; $valueLabels = CRM_Event_PseudoConstant::participantRole(); break; case 'ParticipantEventName': $typeName = 'Participant'; $valueLabels = CRM_Event_PseudoConstant::event(); break; case 'ParticipantEventType': $typeName = 'Participant'; $valueLabels = CRM_Event_PseudoConstant::eventType(); break; case 'MembershipType': $typeName = 'Membership'; $valueLabels = CRM_Member_PseudoConstant::membershipType(); break; case 'ActivityType': $typeName = 'Activity'; $valueLabels = CRM_Core_PseudoConstant::ActivityType(TRUE, TRUE, FALSE, 'label', TRUE); break; } foreach ($valueParts as $val) { if (CRM_Utils_Rule::integer($val)) { $groupTypeValues[$val] = CRM_Utils_Array::value($val, $valueLabels); } } if (!is_array($returnGroupTypes[$typeName])) { $returnGroupTypes[$typeName] = array(); } $returnGroupTypes[$typeName][$valueParts[0]] = $groupTypeValues; } } return $returnGroupTypes; }
/** * @return bool */ public function validate() { if (CRM_Utils_System::isNull($this->_value)) { return TRUE; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': return CRM_Utils_Rule::date($this->_value); case 'non_deductible_amount': case 'total_amount': case 'fee_amount': case 'net_amount': return CRM_Utils_Rule::money($this->_value); case 'trxn_id': static $seenTrxnIds = array(); if (in_array($this->_value, $seenTrxnIds)) { return FALSE; } elseif ($this->_value) { $seenTrxnIds[] = $this->_value; return TRUE; } else { $this->_value = NULL; return TRUE; } break; case 'currency': return CRM_Utils_Rule::currencyCode($this->_value); case 'membership_type': static $membershipTypes = NULL; if (!$membershipTypes) { $membershipTypes = CRM_Member_PseudoConstant::membershipType(); } if (in_array($this->_value, $membershipTypes)) { return TRUE; } else { return FALSE; } break; case 'payment_instrument': static $paymentInstruments = NULL; if (!$paymentInstruments) { $paymentInstruments = CRM_Member_PseudoConstant::paymentInstrument(); } if (in_array($this->_value, $paymentInstruments)) { return TRUE; } else { return FALSE; } break; default: break; } // check whether that's a valid custom field id // and if so, check the contents' validity if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) { static $customFields = NULL; if (!$customFields) { $customFields = CRM_Core_BAO_CustomField::getFields('Membership'); } if (!array_key_exists($customFieldID, $customFields)) { return FALSE; } return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value); } return TRUE; }
/** * Create array of message information - ie. return html version, txt version, to field * * @param array $input * Incoming information. * - is_recur - should this be treated as recurring (not sure why you wouldn't * just check presence of recur object but maintaining legacy approach * to be careful) * @param array $ids * IDs of related objects. * @param array $values * Any values that may have already been compiled by calling process. * This is augmented by values 'gathered' by gatherMessageValues * @param bool $recur * @param bool $returnMessageText * Distinguishes between whether to send message or return. * message text. We are working towards this function ALWAYS returning message text & calling * function doing emails / pdfs with it * * @return array * messages * @throws Exception */ public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) { $this->loadRelatedObjects($input, $ids); if (empty($this->_component)) { $this->_component = CRM_Utils_Array::value('component', $input); } //not really sure what params might be passed in but lets merge em into values $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values); $template = CRM_Core_Smarty::singleton(); $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText); //what does recur 'mean here - to do with payment processor return functionality but // what is the importance if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) { $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']); $entityID = $entity = NULL; if (isset($ids['contribution'])) { $entity = 'contribution'; $entityID = $ids['contribution']; } if (!empty($ids['membership'])) { //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this // line having loaded an array $ids['membership'] = (array) $ids['membership']; $entity = 'membership'; $entityID = $ids['membership'][0]; } $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity)); $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing')); $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update')); if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { //direct mode showing billing block, so use directIPN for temporary $template->assign('contributeMode', 'directIPN'); } } // todo remove strtolower - check consistency if (strtolower($this->_component) == 'event') { $eventParams = array('id' => $this->_relatedObjects['participant']->event_id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case //and cases involving status updation through ipn // whatever that means! // total_amount appears to be the preferred input param & it is unclear why we support amount here // perhaps we should throw an e-notice if amount is set & force total_amount? if (!empty($input['amount'])) { $values['totalAmount'] = $input['amount']; } if ($values['event']['is_email_confirm']) { $values['is_email_receipt'] = 1; } return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText); } else { $values['contribution_id'] = $this->id; if (!empty($ids['related_contact'])) { $values['related_contact'] = $ids['related_contact']; if (isset($ids['onbehalf_dupe_alert'])) { $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; } $entityBlock = array('contact_id' => $ids['contact'], 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Home', 'id', 'name')); $address = CRM_Core_BAO_Address::getValues($entityBlock); $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); } $isTest = FALSE; if ($this->is_test) { $isTest = TRUE; } if (!empty($this->_relatedObjects['membership'])) { foreach ($this->_relatedObjects['membership'] as $membership) { if ($membership->id) { $values['isMembership'] = TRUE; // need to set the membership values here $template->assign('membership_assign', 1); $template->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); $template->assign('mem_start_date', $membership->start_date); $template->assign('mem_join_date', $membership->join_date); $template->assign('mem_end_date', $membership->end_date); $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label'); $template->assign('mem_status', $membership_status); if ($membership_status == 'Pending' && $membership->is_pay_later == 1) { $template->assign('is_pay_later', 1); } // if separate payment there are two contributions recorded and the // admin will need to send a receipt for each of them separately. // we dont link the two in the db (but can potentially infer it if needed) $template->assign('is_separate_payment', 0); if ($recur && $paymentObject) { $url = $paymentObject->subscriptionURL($membership->id, 'membership'); $template->assign('cancelSubscriptionUrl', $url); $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing'); $template->assign('updateSubscriptionBillingUrl', $url); $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); $template->assign('updateSubscriptionUrl', $url); } $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); return $result; // otherwise if its about sending emails, continue sending without return, as we // don't want to exit the loop. } } } else { return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); } } }
static function buildSearchForm(&$form) { require_once 'CRM/Member/PseudoConstant.php'; foreach (CRM_Member_PseudoConstant::membershipType() as $id => $Name) { $form->_membershipType =& $form->addElement('checkbox', "member_membership_type_id[{$id}]", null, $Name); } // Option to include / exclude inherited memberships from search results (e.g. rows where owner_membership_id is NOT NULL) $primaryValues = array(1 => ts('All Members'), 2 => ts('Primary Members Only'), 3 => ts('Related Members Only')); $form->addRadio('member_is_primary', '', $primaryValues); $form->setDefaults(array('member_is_primary' => 1)); foreach (CRM_Member_PseudoConstant::membershipStatus() as $sId => $sName) { $form->_membershipStatus =& $form->addElement('checkbox', "member_status_id[{$sId}]", null, $sName); } $form->addElement('text', 'member_source', ts('Source')); $form->addDate('member_join_date_low', ts('Join Date - From'), false, array('formatType' => 'relative')); $form->addDate('member_join_date_high', ts('To'), false, array('formatType' => 'relative')); $form->addDate('member_start_date_low', ts('Start Date - From'), false, array('formatType' => 'relative')); $form->addDate('member_start_date_high', ts('To'), false, array('formatType' => 'relative')); $form->addDate('member_end_date_low', ts('End Date - From'), false, array('formatType' => 'relative')); $form->addDate('member_end_date_high', ts('To'), false, array('formatType' => 'relative')); $form->addElement('checkbox', 'member_test', ts('Find Test Memberships?')); $form->addElement('checkbox', 'member_pay_later', ts('Find Pay Later Memberships?')); // add all the custom searchable fields require_once 'CRM/Custom/Form/CustomData.php'; $extends = array('Membership'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(null, true, $extends); if ($groupDetails) { require_once 'CRM/Core/BAO/CustomField.php'; $form->assign('membershipGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, false, false, true); } } } $form->assign('validCiviMember', true); }
/** * Add activity for Membership/Event/Contribution. * * @param object $activity * (reference) particular component object. * @param string $activityType * For Membership Signup or Renewal. * @param int $targetContactID * * @return bool|NULL */ public static function addActivity(&$activity, $activityType = 'Membership Signup', $targetContactID = NULL) { if ($activity->__table == 'civicrm_membership') { $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id); if (!$membershipType) { $membershipType = ts('Membership'); } $subject = "{$membershipType}"; if (!empty($activity->source) && $activity->source != 'null') { $subject .= " - {$activity->source}"; } if ($activity->owner_membership_id) { $query = "\nSELECT display_name\n FROM civicrm_contact, civicrm_membership\n WHERE civicrm_contact.id = civicrm_membership.contact_id\n AND civicrm_membership.id = {$activity->owner_membership_id}\n"; $displayName = CRM_Core_DAO::singleValueQuery($query); $subject .= " (by {$displayName})"; } $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id, 'label'); // CRM-72097 changed from start date to today $date = date('YmdHis'); $component = 'Membership'; } elseif ($activity->__table == 'civicrm_participant') { $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE); $roles = CRM_Event_PseudoConstant::participantRole(); $status = CRM_Event_PseudoConstant::participantStatus(); $subject = $event[$activity->event_id]; if (!empty($roles[$activity->role_id])) { $subject .= ' - ' . $roles[$activity->role_id]; } if (!empty($status[$activity->status_id])) { $subject .= ' - ' . $status[$activity->status_id]; } $date = date('YmdHis'); if ($activityType != 'Email') { $activityType = 'Event Registration'; } $component = 'Event'; } elseif ($activity->__table == 'civicrm_contribution') { // create activity record only for Completed Contributions if ($activity->contribution_status_id != 1) { return NULL; } $subject = NULL; $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency); if (!empty($activity->source) && $activity->source != 'null') { $subject .= " - {$activity->source}"; } $date = CRM_Utils_Date::isoToMysql($activity->receive_date); $activityType = $component = 'Contribution'; } $activityParams = array('source_contact_id' => $activity->contact_id, 'source_record_id' => $activity->id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'subject' => $subject, 'activity_date_time' => $date, 'is_test' => $activity->is_test, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'skipRecentView' => TRUE, 'campaign_id' => $activity->campaign_id); // create activity with target contacts $session = CRM_Core_Session::singleton(); $id = $session->get('userID'); if ($id) { $activityParams['source_contact_id'] = $id; $activityParams['target_contact_id'][] = $activity->contact_id; } // CRM-14945 if (property_exists($activity, 'details')) { $activityParams['details'] = $activity->details; } //CRM-4027 if ($targetContactID) { $activityParams['target_contact_id'][] = $targetContactID; } if (is_a(self::create($activityParams), 'CRM_Core_Error')) { CRM_Core_Error::fatal("Failed creating Activity for {$component} of id {$activity->id}"); return FALSE; } }
function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; $checkList = array(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats)) { // not repeat contact display names if it matches with the one // in previous row $repeatFound = FALSE; foreach ($row as $colName => $colVal) { if (is_array($checkList[$colName]) && in_array($colVal, $checkList[$colName])) { $rows[$rowNum][$colName] = ""; $repeatFound = TRUE; } if (in_array($colName, $this->_noRepeats)) { $checkList[$colName][] = $colVal; } } } //handle the Membership Type Ids if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE); } $entryFound = TRUE; } // handle state province if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value, FALSE); } $entryFound = TRUE; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } // convert display name to links if (array_key_exists('civicrm_contact_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url('civicrm/report/member/detail', 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name'] = "<a href='{$url}'>" . $row["civicrm_contact_sort_name"] . '</a>'; $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } }
/** * Flush anywhere that membership types might be cached. * * @throws \CiviCRM_API3_Exception */ public static function flush() { CRM_Member_PseudoConstant::membershipType(NULL, TRUE); civicrm_api3('membership', 'getfields', array('cache_clear' => 1, 'fieldname' => 'membership_type_id')); civicrm_api3('profile', 'getfields', array('action' => 'submit', 'cache_clear' => 1)); }
function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; $checkList = array(); $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // not repeat contact display names if it matches with the one // in previous row $repeatFound = FALSE; foreach ($row as $colName => $colVal) { if (CRM_Utils_Array::value($colName, $checkList) && is_array($checkList[$colName]) && in_array($colVal, $checkList[$colName])) { $rows[$rowNum][$colName] = ""; $repeatFound = TRUE; } if (in_array($colName, $this->_noRepeats)) { $checkList[$colName][] = $colVal; } } } if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_contact_sort_name', $row) && $rows[$rowNum]['civicrm_contact_sort_name'] && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact."); $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) { $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value]; $entryFound = TRUE; } // Convert campaign_id to campaign title if (array_key_exists('civicrm_membership_campaign_id', $row)) { if ($value = $row['civicrm_membership_campaign_id']) { $rows[$rowNum]['civicrm_membership_campaign_id'] = $this->activeCampaigns[$value]; $entryFound = TRUE; } } if (!$entryFound) { break; } } }
/** * Send email receipt. * * @param CRM_Core_Form $form * Form object. * @param array $formValues * @param object $membership * Object. * * @return bool * true if mail was sent successfully */ public static function emailReceipt(&$form, &$formValues, &$membership) { // retrieve 'from email id' for acknowledgement $receiptFrom = $formValues['from_email_address']; if (!empty($formValues['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']]; } // retrieve custom data $customFields = $customValues = array(); if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) { foreach ($form->_groupTree as $groupID => $group) { if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } } } $members = array(array('member_id', '=', $membership->id, 0, 0)); // check whether its a test drive if ($form->_mode == 'test') { $members[] = array('member_test', '=', 1, 0, 0); } CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members); if ($form->_mode) { if (!empty($form->_params['billing_first_name'])) { $name = $form->_params['billing_first_name']; } if (!empty($form->_params['billing_middle_name'])) { $name .= " {$form->_params['billing_middle_name']}"; } if (!empty($form->_params['billing_last_name'])) { $name .= " {$form->_params['billing_last_name']}"; } $form->assign('billingName', $name); // assign the address formatted up for display $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $part) { list($n, $id) = explode('-', $part); if (isset($form->_params['billing_' . $part])) { $addressFields[$n] = $form->_params['billing_' . $part]; } } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])); $form->assign('credit_card_type', $form->_params['credit_card_type']); $form->assign('contributeMode', 'direct'); $form->assign('isAmountzero', 0); $form->assign('is_pay_later', 0); $form->assign('isPrimary', 1); } $form->assign('module', 'Membership'); $form->assign('contactID', $formValues['contact_id']); $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues))); if (!empty($formValues['contribution_id'])) { $form->assign('contributionID', $formValues['contribution_id']); } elseif (isset($form->_onlinePendingContributionId)) { $form->assign('contributionID', $form->_onlinePendingContributionId); } if (!empty($formValues['contribution_status_id'])) { $form->assign('contributionStatusID', $formValues['contribution_status_id']); $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name')); } if (!empty($formValues['is_renew'])) { $form->assign('receiptType', 'membership renewal'); } else { $form->assign('receiptType', 'membership signup'); } $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues))); $form->assign('formValues', $formValues); if (empty($lineItem)) { $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y')); if (!CRM_Utils_System::isNull($membership->end_date)) { $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y')); } $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); } $form->assign('customValues', $customValues); $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry'); if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) { // in this case the form is being called statically from the batch editing screen // having one class in the form layer call another statically is not greate // & we should aim to move this function to the BAO layer in future. // however, we can assume that the contact_id passed in by the batch // function will be the recipient list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']); if (empty($form->_receiptContactId) || $isBatchProcess) { $form->_receiptContactId = $formValues['contact_id']; } } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW))); return TRUE; }
/** * takes an associative array and creates a membership object * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * @param boolean $callFromAPI Is this function called from API? * * @return object CRM_Member_BAO_Membership object * @access public * @static */ static function &create(&$params, &$ids, $skipRedirect = false, $activityType = 'Membership Signup') { // always cal status if is_override/skipStatusCal is not true. // giving respect to is_override during import. CRM-4012 // To skip status cal we should use 'skipStatusCal'. // eg pay later membership, membership update cron CRM-3984 if (!CRM_Utils_Array::value('is_override', $params) && !CRM_Utils_Array::value('skipStatusCal', $params)) { require_once 'CRM/Utils/Date.php'; $startDate = $endDate = $joinDate = null; if (isset($params['start_date'])) { $startDate = CRM_Utils_Date::customFormat($params['start_date'], '%Y%m%d'); } if (isset($params['end_date'])) { $endDate = CRM_Utils_Date::customFormat($params['end_date'], '%Y%m%d'); } if (isset($params['join_date'])) { $joinDate = CRM_Utils_Date::customFormat($params['join_date'], '%Y%m%d'); } require_once 'CRM/Member/BAO/MembershipStatus.php'; //fix for CRM-3570, during import exclude the statuses those having is_admin = 1 $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, false); //CRM-3724 always skip is_admin if is_override != true. if (!$excludeIsAdmin && !CRM_Utils_Array::value('is_override', $params)) { $excludeIsAdmin = true; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin); if (empty($calcStatus)) { if (!$skipRedirect) { // Redirect the form in case of error CRM_Core_Session::setStatus(ts('The membership cannot be saved.') . '<br/>' . ts('No valid membership status for given dates.')); return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member")); } // Return the error message to the api $error = array(); $error['is_error'] = ts('The membership cannot be saved. No valid membership status for given dates'); return $error; } $params['status_id'] = $calcStatus['id']; } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $membership =& self::add($params, $ids); if (is_a($membership, 'CRM_Core_Error')) { $transaction->rollback(); return $membership; } // add custom field values if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) { require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id); } $params['membership_id'] = $membership->id; if (isset($ids['membership'])) { $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $ids['membership'], 'contribution_id', 'membership_id'); } //record contribution for this membership if (CRM_Utils_Array::value('contribution_status_id', $params)) { $contributionParams = array(); $config = CRM_Core_Config::singleton(); $contributionParams['currency'] = $config->defaultCurrency; $contributionParams['receipt_date'] = CRM_Utils_Array::value('receipt_date', $params) ? $params['receipt_date'] : 'null'; $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params); $contributionParams['non_deductible_amount'] = 'null'; $recordContribution = array('contact_id', 'total_amount', 'receive_date', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test', 'contribution_status_id', 'check_number'); foreach ($recordContribution as $f) { $contributionParams[$f] = CRM_Utils_Array::value($f, $params); } require_once 'CRM/Contribute/BAO/Contribution.php'; $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); //insert payment record for this membership if (!CRM_Utils_Array::value('contribution', $ids) || CRM_Utils_Array::value('is_recur', $params)) { require_once 'CRM/Member/DAO/MembershipPayment.php'; $mpDAO = new CRM_Member_DAO_MembershipPayment(); $mpDAO->membership_id = $membership->id; $mpDAO->contribution_id = $contribution->id; if (CRM_Utils_Array::value('is_recur', $params)) { $mpDAO->find(); } CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $mpDAO); $mpDAO->save(); CRM_Utils_Hook::post('create', 'MembershipPayment', $mpDAO->id, $mpDAO); } } // add activity record only during create mode and renew mode // also add activity if status changed CRM-3984 and CRM-2521 if (!CRM_Utils_Array::value('membership', $ids) || $activityType == 'Membership Renewal' || CRM_Utils_Array::value('createActivity', $params)) { if (CRM_Utils_Array::value('membership', $ids)) { CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source')); $membership->contact_id = $data[$membership->id]['contact_id']; $membership->membership_type_id = $data[$membership->id]['membership_type_id']; $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]); } // since we are going to create activity record w/ // individual contact as a target in case of on behalf signup, // so get the copy of organization id, CRM-5551 $realMembershipContactId = $membership->contact_id; // create activity source = individual, target = org CRM-4027 $targetContactID = null; if (CRM_Utils_Array::value('is_for_organization', $params)) { $targetContactID = $membership->contact_id; $membership->contact_id = $ids['userId']; } require_once 'CRM/Activity/BAO/Activity.php'; CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID); // we might created activity record w/ individual // contact as target so update membership object w/ // original organization id, CRM-5551 $membership->contact_id = $realMembershipContactId; } $transaction->commit(); self::createRelatedMemberships($params, $membership); // do not add to recent items for import, CRM-4399 if (!CRM_Utils_Array::value('skipRecentView', $params)) { require_once 'CRM/Utils/Recent.php'; require_once 'CRM/Member/PseudoConstant.php'; require_once 'CRM/Contact/BAO/Contact.php'; $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"); $membershipTypes = CRM_Member_PseudoConstant::membershipType(); $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id]; require_once 'CRM/Core/Permission.php'; $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"); } // add the recently created Membership CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, null, $recentOther); } return $membership; }
/** * The function checks and updates the status of all membership records for a given domain using the * calc_membership_status and update_contact_membership APIs. * * IMPORTANT: * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3. * * @return array */ public static function updateAllMembershipStatus() { //get all active statuses of membership, CRM-3984 $allStatus = CRM_Member_PseudoConstant::membershipStatus(); $statusLabels = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'); $allTypes = CRM_Member_PseudoConstant::membershipType(); // get only memberships with active membership types $query = "\nSELECT civicrm_membership.id as membership_id,\n civicrm_membership.is_override as is_override,\n civicrm_membership.membership_type_id as membership_type_id,\n civicrm_membership.status_id as status_id,\n civicrm_membership.join_date as join_date,\n civicrm_membership.start_date as start_date,\n civicrm_membership.end_date as end_date,\n civicrm_membership.source as source,\n civicrm_contact.id as contact_id,\n civicrm_contact.is_deceased as is_deceased,\n civicrm_membership.owner_membership_id as owner_membership_id,\n civicrm_membership.contribution_recur_id as recur_id\nFROM civicrm_membership\nINNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )\nINNER JOIN civicrm_membership_type ON\n (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)\nWHERE civicrm_membership.is_test = 0"; $params = array(); $dao = CRM_Core_DAO::executeQuery($query, $params); $processCount = 0; $updateCount = 0; $smarty = CRM_Core_Smarty::singleton(); while ($dao->fetch()) { // echo "."; $processCount++; // Put common parameters into array for easy access $memberParams = array('id' => $dao->membership_id, 'status_id' => $dao->status_id, 'contact_id' => $dao->contact_id, 'membership_type_id' => $dao->membership_type_id, 'membership_type' => $allTypes[$dao->membership_type_id], 'join_date' => $dao->join_date, 'start_date' => $dao->start_date, 'end_date' => $dao->end_date, 'source' => $dao->source, 'skipStatusCal' => TRUE, 'skipRecentView' => TRUE); $smarty->assign_by_ref('memberParams', $memberParams); //update membership record to Deceased if contact is deceased if ($dao->is_deceased) { // check for 'Deceased' membership status, CRM-5636 $deceaseStatusId = array_search('Deceased', $allStatus); if (!$deceaseStatusId) { CRM_Core_Error::fatal(ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.", array(1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1')))); } //process only when status change. if ($dao->status_id != $deceaseStatusId) { //take all params that need to save. $deceasedMembership = $memberParams; $deceasedMembership['status_id'] = $deceaseStatusId; $deceasedMembership['createActivity'] = TRUE; $deceasedMembership['version'] = 3; //since there is change in status. $statusChange = array('status_id' => $deceaseStatusId); $smarty->append_by_ref('memberParams', $statusChange, TRUE); unset($deceasedMembership['contact_id'], $deceasedMembership['membership_type_id'], $deceasedMembership['membership_type'], $deceasedMembership['join_date'], $deceasedMembership['start_date'], $deceasedMembership['end_date'], $deceasedMembership['source']); //process membership record. civicrm_api('membership', 'create', $deceasedMembership); } continue; } //we fetch related, since we need to check for deceased //now further processing is handle w/ main membership record. if ($dao->owner_membership_id) { continue; } //update membership records where status is NOT - Pending OR Cancelled. //as well as membership is not override. //skipping Expired membership records -> reduced extra processing( kiran ) if (!$dao->is_override && !in_array($dao->status_id, array(array_search('Pending', $allStatus), array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', $allStatus)))) { // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses //get the membership status as per id. $newStatus = civicrm_api('membership_status', 'calc', array('membership_id' => $dao->membership_id, 'version' => 3, 'ignore_admin_only' => FALSE), TRUE); $statusId = CRM_Utils_Array::value('id', $newStatus); //process only when status change. if ($statusId && $statusId != $dao->status_id) { //take all params that need to save. $memParams = $memberParams; $memParams['status_id'] = $statusId; $memParams['createActivity'] = TRUE; $memParams['version'] = 3; // Unset columns which should remain unchanged from their current saved // values. This avoids race condition in which these values may have // been changed by other processes. unset($memParams['contact_id'], $memParams['membership_type_id'], $memParams['membership_type'], $memParams['join_date'], $memParams['start_date'], $memParams['end_date'], $memParams['source']); //since there is change in status. $statusChange = array('status_id' => $statusId); $smarty->append_by_ref('memberParams', $statusChange, TRUE); //process member record. civicrm_api('membership', 'create', $memParams); $updateCount++; } } } $result['is_error'] = 0; $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(1 => $processCount, 2 => $updateCount)); return $result; }
/** * @param $rows */ public function alterDisplay(&$rows) { // custom code to alter rows $checkList = array(); $entryFound = FALSE; $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); //altering the csv display adding additional fields if ($this->_outputMode == 'csv') { foreach ($this->_columns as $tableName => $table) { if (array_key_exists('fields', $table)) { foreach ($table['fields'] as $fieldName => $field) { if (!empty($field['csv_display']) && !empty($field['no_display'])) { $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field); $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field); } } } } } // allow repeat for first donation amount and date in csv $fAmt = ''; $fDate = ''; foreach ($rows as $rowNum => $row) { if ($this->_outputMode == 'csv') { if (array_key_exists('civicrm_contact_id', $row)) { if ($contactId = $row['civicrm_contact_id']) { if ($rowNum == 0) { $pcid = $contactId; $fAmt = $row['first_donation_first_donation_amount']; $fDate = $row['first_donation_first_donation_date']; } else { if ($pcid == $contactId) { $rows[$rowNum]['first_donation_first_donation_amount'] = $fAmt; $rows[$rowNum]['first_donation_first_donation_date'] = $fDate; $pcid = $contactId; } else { $fAmt = $row['first_donation_first_donation_amount']; $fDate = $row['first_donation_first_donation_date']; $pcid = $contactId; } } } } } if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { $repeatFound = FALSE; $display_flag = NULL; if (array_key_exists('civicrm_contact_id', $row)) { if ($cid = $row['civicrm_contact_id']) { if ($rowNum == 0) { $prev_cid = $cid; } else { if ($prev_cid == $cid) { $display_flag = 1; $prev_cid = $cid; } else { $display_flag = 0; $prev_cid = $cid; } } if ($display_flag) { foreach ($row as $colName => $colVal) { if (in_array($colName, $this->_noRepeats)) { unset($rows[$rowNum][$colName]); } } } $entryFound = TRUE; } } } if (array_key_exists('civicrm_membership_membership_type_id', $row)) { if ($value = $row['civicrm_membership_membership_type_id']) { $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_batch_batch_id', $row)) { if ($value = $row['civicrm_batch_batch_id']) { $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $value, 'title'); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } // convert donor sort name to link if (array_key_exists('civicrm_contact_sort_name', $row) && !empty($rows[$rowNum]['civicrm_contact_sort_name']) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts('View Contact Summary for this Contact.'); } if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) { $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value]; $entryFound = TRUE; } if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount_sum', $row)) && CRM_Core_Permission::check('access CiviContribute')) { $url = CRM_Utils_System::url('civicrm/contact/view/contribution', 'reset=1&id=' . $row['civicrm_contribution_contribution_id'] . '&cid=' . $row['civicrm_contact_id'] . '&action=view&context=contribution&selectedChild=contribute', $this->_absoluteUrl); $rows[$rowNum]['civicrm_contribution_total_amount_sum_link'] = $url; $rows[$rowNum]['civicrm_contribution_total_amount_sum_hover'] = ts('View Details of this Contribution.'); $entryFound = TRUE; } // convert campaign_id to campaign title if (array_key_exists('civicrm_contribution_campaign_id', $row)) { if ($value = $row['civicrm_contribution_campaign_id']) { $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value]; $entryFound = TRUE; } } $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'member/contributionDetail', 'List all contribution(s) for this ') ? TRUE : $entryFound; // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } $lastKey = $rowNum; } }