예제 #1
0
 /**
  * Fetch the object and store the values in the values array.
  *
  * @param array $params
  *   Input parameters to find object.
  * @param array $values
  *   Output values of the object.
  * @param bool $active
  *   Do you want only active memberships to.
  *                        be returned
  * @param bool $relatedMemberships
  *
  * @return CRM_Member_BAO_Membership|null
  *   The found object or null
  */
 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE)
 {
     if (empty($params)) {
         return NULL;
     }
     $membership = new CRM_Member_BAO_Membership();
     $membership->copyValues($params);
     $membership->find();
     $memberships = array();
     while ($membership->fetch()) {
         if ($active && !CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $membership->status_id, 'is_current_member')) {
             continue;
         }
         CRM_Core_DAO::storeValues($membership, $values[$membership->id]);
         $memberships[$membership->id] = $membership;
         if ($relatedMemberships && !empty($membership->owner_membership_id)) {
             $values['owner_membership_ids'][] = $membership->owner_membership_id;
         }
     }
     return $memberships;
 }
예제 #2
0
 /**
  * Load objects relations to contribution object.
  * Objects are stored in the $_relatedObjects property
  * In the first instance we are just moving functionality from BASEIpn -
  * @see http://issues.civicrm.org/jira/browse/CRM-9996
  *
  * Note that the unit test for the BaseIPN class tests this function
  *
  * @param array $input
  *   Input as delivered from Payment Processor.
  * @param array $ids
  *   Ids as Loaded by Payment Processor.
  * @param bool $loadAll
  *   Load all related objects - even where id not passed in? (allows API to call this).
  *
  * @return bool
  * @throws Exception
  */
 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
     // refactoring than anything else, and has unit test coverage.
     if (empty($this->financial_type_id)) {
         $this->find(TRUE);
     }
     $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value('paymentProcessor', $ids));
     if (!$paymentProcessorID && $this->contribution_page_id) {
         $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
         if ($paymentProcessorID) {
             $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
         }
     }
     $ids['contributionType'] = $this->financial_type_id;
     $ids['financialType'] = $this->financial_type_id;
     $entities = array('contact' => 'CRM_Contact_BAO_Contact', 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', 'contributionType' => 'CRM_Financial_BAO_FinancialType', 'financialType' => 'CRM_Financial_BAO_FinancialType');
     foreach ($entities as $entity => $bao) {
         if (!empty($ids[$entity])) {
             $this->_relatedObjects[$entity] = new $bao();
             $this->_relatedObjects[$entity]->id = $ids[$entity];
             if (!$this->_relatedObjects[$entity]->find(TRUE)) {
                 throw new CRM_Core_Exception($entity . ' could not be loaded');
             }
         }
     }
     if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
         $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
     }
     if (!empty($ids['pledge_payment'])) {
         foreach ($ids['pledge_payment'] as $key => $paymentID) {
             if (empty($paymentID)) {
                 continue;
             }
             $payment = new CRM_Pledge_BAO_PledgePayment();
             $payment->id = $paymentID;
             if (!$payment->find(TRUE)) {
                 throw new Exception("Could not find pledge payment record: " . $paymentID);
             }
             $this->_relatedObjects['pledge_payment'][] = $payment;
         }
     }
     if ($this->_component == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         //in any case get the memberships associated with the contribution
         //because we now support multiple memberships w/ price set
         // see if there are any other memberships to be considered for same contribution.
         $query = "\n            SELECT membership_id\n            FROM   civicrm_membership_payment\nWHERE  contribution_id = %1 ";
         $params = array(1 => array($this->id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             if ($dao->membership_id) {
                 if (!is_array($ids['membership'])) {
                     $ids['membership'] = array();
                 }
                 $ids['membership'][] = $dao->membership_id;
             }
         }
         if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
             foreach ($ids['membership'] as $id) {
                 if (!empty($id)) {
                     $membership = new CRM_Member_BAO_Membership();
                     $membership->id = $id;
                     if (!$membership->find(TRUE)) {
                         throw new Exception("Could not find membership record: {$id}");
                     }
                     $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                     $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                     $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                     $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                     $membership->free();
                 }
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         // get the payment processor id from event - this is inaccurate see CRM-16923
         // in future we should look at throwing an exception here rather than an dubious guess.
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
             if ($paymentProcessorID) {
                 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
             }
         }
     }
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
     }
     return TRUE;
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     try {
         // first make sure this is a valid line
         $response = $this->summary($values);
         if ($response != CRM_Import_Parser::VALID) {
             return $response;
         }
         $params =& $this->getActiveFieldParams();
         //assign join date equal to start date if join date is not provided
         if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) {
             $params['join_date'] = $params['membership_start_date'];
         }
         $session = CRM_Core_Session::singleton();
         $dateType = $session->get('dateTypes');
         $formatted = array();
         $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
         // don't add to recent items, CRM-4399
         $formatted['skipRecentView'] = TRUE;
         $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date'));
         foreach ($params as $key => $val) {
             if ($val) {
                 switch ($key) {
                     case 'join_date':
                     case 'membership_start_date':
                     case 'membership_end_date':
                         if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                             if (!CRM_Utils_Rule::date($params[$key])) {
                                 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                             }
                         } else {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                         }
                         break;
                     case 'membership_type_id':
                         if (!is_numeric($val)) {
                             unset($params['membership_type_id']);
                             $params['membership_type'] = $val;
                         }
                         break;
                     case 'status_id':
                         if (!is_numeric($val)) {
                             unset($params['status_id']);
                             $params['membership_status'] = $val;
                         }
                         break;
                     case 'is_override':
                         $params[$key] = CRM_Utils_String::strtobool($val);
                         break;
                 }
                 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                     if ($customFields[$customFieldID]['data_type'] == 'Date') {
                         CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                         unset($params[$key]);
                     } else {
                         if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                             $params[$key] = CRM_Utils_String::strtoboolstr($val);
                         }
                     }
                 }
             }
         }
         //date-Format part ends
         static $indieFields = NULL;
         if ($indieFields == NULL) {
             $tempIndieFields = CRM_Member_DAO_Membership::import();
             $indieFields = $tempIndieFields;
         }
         $formatValues = array();
         foreach ($params as $key => $field) {
             if ($field == NULL || $field === '') {
                 continue;
             }
             $formatValues[$key] = $field;
         }
         //format params to meet api v2 requirements.
         //@todo find a way to test removing this formatting
         $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
         if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership');
         } else {
             //fix for CRM-2219 Update Membership
             // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
             if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
                 array_unshift($values, 'Required parameter missing: Status');
                 return CRM_Import_Parser::ERROR;
             }
             if (!empty($formatValues['membership_id'])) {
                 $dao = new CRM_Member_BAO_Membership();
                 $dao->id = $formatValues['membership_id'];
                 $dates = array('join_date', 'start_date', 'end_date');
                 foreach ($dates as $v) {
                     if (!CRM_Utils_Array::value($v, $formatted)) {
                         $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                     }
                 }
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
                 if ($dao->find(TRUE)) {
                     $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                     $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
                     if (civicrm_error($newMembership)) {
                         array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                         return CRM_Import_Parser::ERROR;
                     } else {
                         $this->_newMemberships[] = $newMembership->id;
                         return CRM_Import_Parser::VALID;
                     }
                 } else {
                     array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
         }
         //Format dates
         $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d');
         $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
         $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
         if ($this->_contactIdIndex < 0) {
             //retrieve contact id using contact dedupe rule
             $formatValues['contact_type'] = $this->_contactType;
             $formatValues['version'] = 3;
             require_once 'CRM/Utils/DeprecatedUtils.php';
             $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
             if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                 $matchedIDs = explode(',', $error['error_message']['params'][0]);
                 if (count($matchedIDs) > 1) {
                     array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
                     return CRM_Import_Parser::ERROR;
                 } else {
                     $cid = $matchedIDs[0];
                     $formatted['contact_id'] = $cid;
                     //fix for CRM-1924
                     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                     self::formattedDates($calcDates, $formatted);
                     //fix for CRM-3570, exclude the statuses those having is_admin = 1
                     //now user can import is_admin if is override is true.
                     $excludeIsAdmin = FALSE;
                     if (!CRM_Utils_Array::value('is_override', $formatted)) {
                         $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
                     }
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
                     if (!CRM_Utils_Array::value('status_id', $formatted)) {
                         $formatted['status_id'] = $calcStatus['id'];
                     } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                         if (empty($calcStatus)) {
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         } elseif ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         }
                     }
                     $newMembership = civicrm_api3('membership', 'create', $formatted);
                     $this->_newMemberships[] = $newMembership['id'];
                     return CRM_Import_Parser::VALID;
                 }
             } else {
                 // Using new Dedupe rule.
                 $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
                 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
                 $disp = '';
                 foreach ($fieldsArray as $value) {
                     if (array_key_exists(trim($value), $params)) {
                         $paramValue = $params[trim($value)];
                         if (is_array($paramValue)) {
                             $disp .= $params[trim($value)][0][trim($value)] . " ";
                         } else {
                             $disp .= $params[trim($value)] . " ";
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('external_identifier', $params)) {
                     if ($disp) {
                         $disp .= "AND {$params['external_identifier']}";
                     } else {
                         $disp = $params['external_identifier'];
                     }
                 }
                 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
                 return CRM_Import_Parser::ERROR;
             }
         } else {
             if (CRM_Utils_Array::value('external_identifier', $formatValues)) {
                 $checkCid = new CRM_Contact_DAO_Contact();
                 $checkCid->external_identifier = $formatValues['external_identifier'];
                 $checkCid->find(TRUE);
                 if ($checkCid->id != $formatted['contact_id']) {
                     array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                     return CRM_Import_Parser::ERROR;
                 }
             }
             //to calculate dates
             $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
             self::formattedDates($calcDates, $formatted);
             //end of date calculation part
             //fix for CRM-3570, exclude the statuses those having is_admin = 1
             //now user can import is_admin if is override is true.
             $excludeIsAdmin = FALSE;
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
             }
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
             if (!CRM_Utils_Array::value('status_id', $formatted)) {
                 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
             } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 } elseif ($formatted['status_id'] != $calcStatus['id']) {
                     //Status Hold" is either NOT mapped or is FALSE
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
             $newMembership = civicrm_api3('membership', 'create', $formatted);
             $this->_newMemberships[] = $newMembership['id'];
             return CRM_Import_Parser::VALID;
         }
     } catch (Exception $e) {
         array_unshift($values, $e->getMessage());
         return CRM_Import_Parser::ERROR;
     }
 }
예제 #4
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Member_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //assign join date equal to start date if join date is not provided
     if (!$params['join_date'] && $params['membership_start_date']) {
         $params['join_date'] = $params['membership_start_date'];
     }
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     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 'is_override':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID][2] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID][2] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Member/DAO/Membership.php';
         $tempIndieFields =& CRM_Member_DAO_Membership::import();
         $indieFields = $tempIndieFields;
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Member_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Member_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Membership');
     } else {
         //fix for CRM-2219 Update Membership
         // onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE
         if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
             array_unshift($values, "Required parameter missing: Status");
             return CRM_Member_Import_Parser::ERROR;
         }
         if ($formatValues['membership_id']) {
             require_once 'CRM/Member/BAO/Membership.php';
             $dao = new CRM_Member_BAO_Membership();
             $dao->id = $formatValues['membership_id'];
             $dates = array('join_date', 'start_date', 'end_date');
             foreach ($dates as $v) {
                 if (!$formatted[$v]) {
                     $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                 }
             }
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
             if ($dao->find(true)) {
                 $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                 $newMembership =& CRM_Member_BAO_Membership::create($formatted, $ids, true);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['is_error'] . " for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     $this->_newMemberships[] = $newMembership->id;
                     return CRM_Member_Import_Parser::VALID;
                 }
             } else {
                 array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
     }
     //Format dates
     $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d');
     $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d');
     $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The membership was not imported");
                 return CRM_Member_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 //fix for CRM-1924
                 require_once 'CRM/Member/BAO/MembershipStatus.php';
                 require_once 'CRM/Member/BAO/MembershipType.php';
                 require_once 'CRM/Member/PseudoConstant.php';
                 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                 self::formattedDates($calcDates, $formatted);
                 //fix for CRM-3570, exclude the statuses those having is_admin = 1
                 //now user can import is_admin if is override is true.
                 $excludeIsAdmin = false;
                 if (!CRM_Utils_Array::value('is_override', $formatted)) {
                     $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
                 }
                 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
                 if (!$formatted['status_id']) {
                     $formatted['status_id'] = $calcStatus['id'];
                 } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                     if (empty($calcStatus)) {
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     } else {
                         if ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                             return CRM_Member_Import_Parser::ERROR;
                         }
                     }
                 }
                 $newMembership = civicrm_contact_membership_create($formatted);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['error_message']);
                     return CRM_Member_Import_Parser::ERROR;
                 }
                 $this->_newMemberships[] = $newMembership['id'];
                 return CRM_Member_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Member_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
         //to calculate dates
         require_once 'CRM/Member/BAO/MembershipType.php';
         $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
         self::formattedDates($calcDates, $formatted);
         //end of date calculation part
         //fix for CRM-3570, exclude the statuses those having is_admin = 1
         //now user can import is_admin if is override is true.
         $excludeIsAdmin = false;
         if (!CRM_Utils_Array::value('is_override', $formatted)) {
             $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (!$formatted['status_id']) {
             $formatted['status_id'] = $calcStatus['id'];
         } else {
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     if ($formatted['status_id'] != $calcStatus['id']) {
                         //Status Hold" is either NOT mapped or is FALSE
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     }
                 }
             }
         }
         $newMembership = civicrm_contact_membership_create($formatted);
         if (civicrm_error($newMembership)) {
             array_unshift($values, $newMembership['error_message']);
             return CRM_Member_Import_Parser::ERROR;
         }
         $this->_newMemberships[] = $newMembership['id'];
         return CRM_Member_Import_Parser::VALID;
     }
 }
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $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');
     $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()'));
     //period type
     $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()'));
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120');
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(FALSE);
     $hasMsgTemplates = FALSE;
     if (!empty($msgTemplates)) {
         $hasMsgTemplates = TRUE;
     }
     //Auto-renew Option
     $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
     $isAuthorize = FALSE;
     $options = array();
     $allowAutoRenewMsg = FALSE;
     if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
         $isAuthorize = TRUE;
         $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required '));
         if ($hasMsgTemplates) {
             $allowAutoRenewMsg = TRUE;
             $autoRenewReminderMsg = $this->add('select', 'autorenewal_msg_id', ts('Auto-renew Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
         }
     }
     $this->addRadio('auto_renew', ts('Auto-renew Option'), $options, array('onclick' => "setReminder(this.value);"));
     $this->assign('authorize', $isAuthorize);
     $this->assign('allowAutoRenewMsg', $allowAutoRenewMsg);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     // required in form rule
     $this->add('hidden', 'action', $this->_action);
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType());
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd);
     $memberRel->setMultiple(TRUE);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     if ($hasMsgTemplates) {
         $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
     }
     $this->assign('hasMsgTemplates', $hasMsgTemplates);
     $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day'));
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     $searchDone = $this->get('searchDone');
     if ($searchRows) {
         $checkBoxes = array();
         $chekFlag = 0;
         foreach ($searchRows as $id => $row) {
             $checked = '';
             if (!$chekFlag) {
                 $checked = array('checked' => NULL);
                 $chekFlag++;
             }
             $checkBoxes[$id] = $this->createElement('radio', NULL, NULL, NULL, $id, $checked);
         }
         $this->addGroup($checkBoxes, 'contact_check');
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $searchDone);
     if ($searchDone) {
         $searchBtn = ts('Search Again');
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $searchBtn = ts('Change');
     } else {
         $searchBtn = ts('Search');
     }
     $membershipRecords = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(TRUE)) {
             $membershipRecords = TRUE;
             $memberRel->freeze();
         }
         $memberOrg->freeze();
         if ($searchDone) {
             $memberOrg->unfreeze();
         }
     }
     $this->assign('membershipRecordsExists', $membershipRecords);
     if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) {
         $renewMessage = array();
         $returnProperties = array('renewal_msg_id', 'renewal_reminder_day');
         CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties);
         if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) {
             $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
             $reminderDay->freeze();
         }
     }
     $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
예제 #6
0
 /**
  * Build the form object.
  *
  * @return void
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $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');
     $this->addSelect('duration_unit', array(), TRUE);
     //period type
     $this->addSelect('period_type', array(), TRUE);
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $props = array('api' => array('params' => array('contact_type' => 'Organization')));
     $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     //Auto-renew Option
     $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
     $isAuthorize = FALSE;
     $options = array();
     if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
         $isAuthorize = TRUE;
         $options = CRM_Core_SelectValues::memberAutoRenew();
     }
     $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
     $this->assign('authorize', $isAuthorize);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'd'), FALSE);
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, array('class' => 'crm-select2'));
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'), $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1));
     $this->addSelect('visibility', array('placeholder' => NULL, 'option_url' => NULL));
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     $membershipRecords = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(TRUE)) {
             $membershipRecords = TRUE;
             $memberRel->freeze();
         }
     }
     $this->assign('membershipRecordsExists', $membershipRecords);
     $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
예제 #7
0
 /**
  * Method to fix membership status of stale membership
  * 
  * This method first checks if the membership is stale. If it is,
  * then status will be updated based on existing start and end
  * dates and log will be added for the status change.
  * 
  * @param  array  $currentMembership   referance to the array
  *                                     containing all values of
  *                                     the current membership
  * @param  array  $changeToday         array of month, day, year
  *                                     values in case today needs
  *                                     to be customised, null otherwise
  * 
  * @return void
  * @static
  */
 static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday)
 {
     $today = null;
     if ($changeToday) {
         $today = CRM_Utils_Date::processDate($changeToday, null, false, 'Y-m-d');
     }
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($currentMembership['start_date'], $currentMembership['end_date'], $currentMembership['join_date'], $today);
     if (empty($status) || empty($status['id'])) {
         CRM_Core_Error::fatal(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
     }
     $currentMembership['today_date'] = $today;
     if ($status['id'] !== $currentMembership['status_id']) {
         $memberDAO = new CRM_Member_BAO_Membership();
         $memberDAO->id = $currentMembership['id'];
         $memberDAO->find(true);
         $memberDAO->status_id = $status['id'];
         $memberDAO->join_date = CRM_Utils_Date::isoToMysql($memberDAO->join_date);
         $memberDAO->start_date = CRM_Utils_Date::isoToMysql($memberDAO->start_date);
         $memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date);
         $memberDAO->save();
         CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
         $memberDAO->free();
         $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $currentMembership['status_id'], 'is_current_member');
         $format = '%Y%m%d';
         $logParams = array('membership_id' => $currentMembership['id'], 'status_id' => $status['id'], 'start_date' => CRM_Utils_Date::customFormat($currentMembership['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($currentMembership['end_date'], $format), 'modified_id' => $currentMembership['contact_id'], 'modified_date' => CRM_Utils_Date::customFormat($currentMembership['today_date'], $format), 'renewal_reminder_date' => CRM_Utils_Date::customFormat($currentMembership['reminder_date'], $format));
         $dontCare = null;
         require_once 'CRM/Member/BAO/MembershipLog.php';
         CRM_Member_BAO_MembershipLog::add($logParams, $dontCare);
     }
 }
예제 #8
0
 /**
  * Load related memberships.
  *
  * Note that in theory it should be possible to retrieve these from the line_item table
  * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
  * as it seems the api is not correctly linking the line items when the contribution is created in the flow
  * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
  * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
  *
  * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
  *
  * @param array $ids
  *
  * @throws Exception
  */
 public function loadRelatedMembershipObjects(&$ids)
 {
     $query = "\n      SELECT membership_id\n      FROM   civicrm_membership_payment\n      WHERE  contribution_id = %1 ";
     $params = array(1 => array($this->id, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     while ($dao->fetch()) {
         if ($dao->membership_id) {
             if (!is_array($ids['membership'])) {
                 $ids['membership'] = array();
             }
             $ids['membership'][] = $dao->membership_id;
         }
     }
     if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
         foreach ($ids['membership'] as $id) {
             if (!empty($id)) {
                 $membership = new CRM_Member_BAO_Membership();
                 $membership->id = $id;
                 if (!$membership->find(TRUE)) {
                     throw new Exception("Could not find membership record: {$id}");
                 }
                 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                 $membership->free();
             }
         }
     }
 }
예제 #9
0
 /**
  * Load objects relations to contribution object.
  * Objects are stored in the $_relatedObjects property
  * In the first instance we are just moving functionality from BASEIpn -
  * @see http://issues.civicrm.org/jira/browse/CRM-9996
  *
  * Note that the unit test for the BaseIPN class tests this function
  *
  * @param array $input
  *   Input as delivered from Payment Processor.
  * @param array $ids
  *   Ids as Loaded by Payment Processor.
  * @param bool $required
  *   Is Payment processor / contribution page required.
  * @param bool $loadAll
  *   Load all related objects - even where id not passed in? (allows API to call this).
  *
  * @return bool
  * @throws Exception
  */
 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
     $contributionType = new CRM_Financial_BAO_FinancialType();
     $contributionType->id = $this->financial_type_id;
     $contributionType->find(TRUE);
     if (!empty($ids['contact'])) {
         $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
         $this->_relatedObjects['contact']->id = $ids['contact'];
         $this->_relatedObjects['contact']->find(TRUE);
     }
     $this->_relatedObjects['contributionType'] = $contributionType;
     if ($this->_component == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         //in any case get the memberships associated with the contribution
         //because we now support multiple memberships w/ price set
         // see if there are any other memberships to be considered for same contribution.
         $query = "\n            SELECT membership_id\n            FROM   civicrm_membership_payment\nWHERE  contribution_id = %1 ";
         $params = array(1 => array($this->id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             if ($dao->membership_id) {
                 if (!is_array($ids['membership'])) {
                     $ids['membership'] = array();
                 }
                 $ids['membership'][] = $dao->membership_id;
             }
         }
         if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
             foreach ($ids['membership'] as $id) {
                 if (!empty($id)) {
                     $membership = new CRM_Member_BAO_Membership();
                     $membership->id = $id;
                     if (!$membership->find(TRUE)) {
                         throw new Exception("Could not find membership record: {$id}");
                     }
                     $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                     $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                     $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                     $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                     $membership->free();
                 }
             }
         }
         if (!empty($ids['pledge_payment'])) {
             foreach ($ids['pledge_payment'] as $key => $paymentID) {
                 if (empty($paymentID)) {
                     continue;
                 }
                 $payment = new CRM_Pledge_BAO_PledgePayment();
                 $payment->id = $paymentID;
                 if (!$payment->find(TRUE)) {
                     throw new Exception("Could not find pledge payment record: " . $paymentID);
                 }
                 $this->_relatedObjects['pledge_payment'][] = $payment;
             }
         }
         if (!empty($ids['contributionRecur'])) {
             $recur = new CRM_Contribute_BAO_ContributionRecur();
             $recur->id = $ids['contributionRecur'];
             if (!$recur->find(TRUE)) {
                 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
             }
             $this->_relatedObjects['contributionRecur'] =& $recur;
             //get payment processor id from recur object.
             $paymentProcessorID = $recur->payment_processor_id;
         }
         //for normal contribution get the payment processor id.
         if (!$paymentProcessorID) {
             if ($this->contribution_page_id) {
                 // get the payment processor id from contribution page
                 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
             } elseif (empty($ids['pledge_payment'])) {
                 $loadObjectSuccess = TRUE;
                 if ($required) {
                     throw new Exception("Could not find contribution page for contribution record: " . $this->id);
                 }
                 return $loadObjectSuccess;
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
         }
     }
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
     } elseif ($required) {
         throw new Exception("Could not find payment processor for contribution record: " . $this->id);
     }
     return TRUE;
 }
예제 #10
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), true);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $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');
     $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()'));
     //period type
     $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()'));
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120');
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false);
     $this->add('hidden', 'action', $this->_action);
     //required in form rule
     require_once 'CRM/Contribute/PseudoConstant.php';
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType());
     require_once 'CRM/Contact/BAO/Relationship.php';
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     require_once "CRM/Core/BAO/MessageTemplates.php";
     $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates();
     if (!empty($msgTemplates)) {
         $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
     } else {
         $this->assign('noMsgTemplates', true);
     }
     $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day'));
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     $searchDone = $this->get('searchDone');
     if ($searchRows) {
         $checkBoxes = array();
         $chekFlag = 0;
         foreach ($searchRows as $id => $row) {
             $checked = '';
             if (!$chekFlag) {
                 $checked = array('checked' => null);
                 $chekFlag++;
             }
             $checkBoxes[$id] = $this->createElement('radio', null, null, null, $id, $checked);
         }
         $this->addGroup($checkBoxes, 'contact_check');
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $searchDone);
     if ($searchDone) {
         $searchBtn = ts('Search Again');
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $searchBtn = ts('Change');
     } else {
         $searchBtn = ts('Search');
     }
     $membershipRecords = false;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         require_once 'CRM/Member/BAO/Membership.php';
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(true)) {
             $membershipRecords = true;
             $memberRel->freeze();
         }
         $memberOrg->freeze();
         if ($searchDone) {
             $memberOrg->unfreeze();
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) {
         $renewMessage = array();
         $returnProperties = array('renewal_msg_id', 'renewal_reminder_day');
         CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties);
         if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) {
             $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
             $reminderDay->freeze();
             $reminderMsg->freeze();
         }
     }
     $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
/**
 * This function ensures that we have the right input membership parameters
 *
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to insert in new membership.
 *
 * @return bool|CRM_Utils_Error
 * @access private
 */
function _civicrm_membership_check_params(&$params)
{
    // params should be an array
    if (!is_array($params)) {
        return civicrm_create_error('Params is not an array');
    }
    // cannot create a membership with empty params
    if (empty($params)) {
        return civicrm_create_error('Input Parameters empty');
    }
    $valid = true;
    $error = '';
    // contact id is required for both add and update
    if (!CRM_Utils_Array::value('contact_id', $params)) {
        $valid = false;
        $error .= ' contact_id';
    }
    // check params for membership id during update
    if (CRM_Utils_Array::value('id', $params)) {
        require_once 'CRM/Member/BAO/Membership.php';
        $membership = new CRM_Member_BAO_Membership();
        $membership->id = $params['id'];
        if (!$membership->find(true)) {
            return civicrm_create_error(ts('Membership id is not valid'));
        }
    } else {
        // membership type id Or membership type is required during add
        if (!CRM_Utils_Array::value('membership_type_id', $params) && !CRM_Utils_Array::value('membership_type', $params)) {
            $valid = false;
            $error .= ' membership_type_id Or membership_type';
        }
    }
    // also check for status id if override is set (during add/update)
    if (isset($params['is_override']) && !CRM_Utils_Array::value('status_id', $params)) {
        $valid = false;
        $error .= ' status_id';
    }
    if (!$valid) {
        return civicrm_create_error("Required fields not found for membership {$error}");
    }
    return array();
}
예제 #12
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $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');
     $this->addElement('select', 'duration_unit', ts('Duration'), CRM_Core_SelectValues::unitList('duration'));
     //period type
     $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType());
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $dataUrl = CRM_Utils_System::url("civicrm/ajax/rest", "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=membershipType&reset=1&org=1", FALSE, NULL, FALSE);
     $this->assign('dataUrl', $dataUrl);
     $memberOrg =& $this->add('text', 'member_of_contact', ts('Membership Organization'), NULL, TRUE);
     $this->add('hidden', 'member_of_contact_id', '', array('id' => 'member_of_contact_id'));
     if ($memberOrg->getValue()) {
         $this->assign('member_org', $memberOrg->getValue());
     }
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     //Auto-renew Option
     $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
     $isAuthorize = FALSE;
     $options = array();
     if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
         $isAuthorize = TRUE;
         $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required '));
     }
     $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
     $this->assign('authorize', $isAuthorize);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'd'), FALSE);
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType());
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd);
     $memberRel->setMultiple(TRUE);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     $membershipRecords = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(TRUE)) {
             $membershipRecords = TRUE;
             $memberRel->freeze();
         }
     }
     $this->assign('membershipRecordsExists', $membershipRecords);
     $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
예제 #13
0
 /**
  * Function to calculate start date and end date for renewal membership 
  * 
  * @param int $membershipId 
  *
  * @return Array array fo the start date, end date and join date of the membership
  * @static
  */
 function getRenewalDatesForMembershipType($membershipId, $changeToday = null)
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     $params = array('id' => $membershipId);
     $membership = new CRM_Member_BAO_Membership();
     //$membership->copyValues( $params );
     $membership->id = $membershipId;
     $membership->find(true);
     $membershipDetails = CRM_Member_BAO_Membership::getValues($params, $values);
     $statusID = $membershipDetails[$membershipId]->status_id;
     $membershipTypeDetails = self::getMembershipTypeDetails($membershipDetails[$membershipId]->membership_type_id);
     $statusDetails = CRM_Member_BAO_MembershipStatus::getMembershipStatus($statusID);
     if ($statusDetails['is_current_member'] == 1) {
         $startDate = $membershipDetails[$membershipId]->start_date;
         $date = explode('-', $membershipDetails[$membershipId]->end_date);
         $logStartDate = date('Y-m-d', mktime(0, 0, 0, (double) $date[1], (double) ($date[2] + 1), (double) $date[0]));
         $date = explode('-', $logStartDate);
         $year = $date[0];
         $month = $date[1];
         $day = $date[2];
         switch ($membershipTypeDetails['duration_unit']) {
             case 'year':
                 $year = $year + $membershipTypeDetails['duration_interval'];
                 break;
             case 'month':
                 $month = $month + $membershipTypeDetails['duration_interval'];
                 break;
             case 'day':
                 $day = $day + $membershipTypeDetails['duration_interval'];
                 break;
         }
         if ($membershipTypeDetails['duration_unit'] == 'lifetime') {
             $endDate = null;
         } else {
             $endDate = date('Y-m-d', mktime(0, 0, 0, $month, $day - 1, $year));
         }
         $today = date('Y-m-d');
     } else {
         //get date in 'Ymd' format, CRM-5795
         $today = date('Ymd');
         if ($changeToday) {
             $today = CRM_Utils_Date::processDate($changeToday, null, false, 'Ymd');
         }
         $rollover = false;
         if (CRM_Utils_Array::value('period_type', $membershipTypeDetails) == 'rolling') {
             $startDate = $logStartDate = CRM_Utils_Date::mysqlToIso($today);
         } else {
             if (CRM_Utils_Array::value('period_type', $membershipTypeDetails) == 'fixed') {
                 // Renewing expired membership is two step process.
                 // 1. Renew the start date
                 // 2. Renew the end date
                 // 1.
                 $date = explode('-', $membershipDetails[$membershipId]->start_date);
                 $yearValue = date('Y');
                 $startDate = $logStartDate = date('Y-m-d', mktime(0, 0, 0, (double) $date[1], (double) $date[2], $yearValue));
                 // before moving to the step 2, check if TODAY is in
                 // rollover window.
                 $rolloverDay = substr($membershipTypeDetails['fixed_period_rollover_day'], -2);
                 $rolloverMonth = substr($membershipTypeDetails['fixed_period_rollover_day'], 0, -2);
                 $fixedStartMonth = substr($membershipTypeDetails['fixed_period_start_day'], 0, -2);
                 if ($rolloverMonth - $fixedStartMonth < 0) {
                     $rolloverDate = date('Ymd', mktime(0, 0, 0, (double) $rolloverMonth, (double) $rolloverDay, $yearValue + 1));
                 } else {
                     $rolloverDate = date('Ymd', mktime(0, 0, 0, (double) $rolloverMonth, (double) $rolloverDay, $yearValue));
                 }
                 if ($today > $rolloverDate) {
                     $rollover = true;
                 }
             }
         }
         // 2.
         $date = explode('-', $startDate);
         $year = (double) $date[0];
         $month = (double) $date[1];
         $day = (double) $date[2];
         switch ($membershipTypeDetails['duration_unit']) {
             case 'year':
                 $year = $year + $membershipTypeDetails['duration_interval'];
                 if ($rollover) {
                     $year = $year + $membershipTypeDetails['duration_interval'];
                 }
                 break;
             case 'month':
                 $month = $month + $membershipTypeDetails['duration_interval'];
                 if ($rollover) {
                     $month = $month + $membershipTypeDetails['duration_interval'];
                 }
                 break;
             case 'day':
                 $day = $day + $membershipTypeDetails['duration_interval'];
                 if ($rollover) {
                     $day = $day + $membershipTypeDetails['duration_interval'];
                 }
                 break;
         }
         if ($membershipTypeDetails['duration_unit'] == 'lifetime') {
             $endDate = null;
         } else {
             $endDate = date('Y-m-d', mktime(0, 0, 0, $month, $day - 1, $year));
         }
     }
     $membershipDates = array();
     $membershipDates['today'] = CRM_Utils_Date::customFormat($today, '%Y%m%d');
     $membershipDates['start_date'] = CRM_Utils_Date::customFormat($startDate, '%Y%m%d');
     $membershipDates['end_date'] = CRM_Utils_Date::customFormat($endDate, '%Y%m%d');
     if (CRM_Utils_Array::value("renewal_reminder_day", $membershipTypeDetails)) {
         $date = explode('-', $endDate);
         $year = $date[0];
         $month = $date[1];
         $day = $date[2];
         $day = $day - $membershipTypeDetails["renewal_reminder_day"];
         $reminderDate = date('Y-m-d', mktime(0, 0, 0, $month, $day - 1, $year));
         $membershipDates['reminder_date'] = CRM_Utils_Date::customFormat($reminderDate, '%Y%m%d');
     }
     $membershipDates['log_start_date'] = CRM_Utils_Date::customFormat($logStartDate, '%Y%m%d');
     return $membershipDates;
 }
예제 #14
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             $ids['membership'] = $key;
             if ($value['membership_source']) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             $membership = new CRM_Member_BAO_Membership();
             $membership->id = CRM_Utils_Array::value('membership', $ids);
             $membership->find(true);
             $membership->free();
             $value['status_id'] = $membership->status_id;
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', false, false, $membership->membership_type_id);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', false, false, null, null, true));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membership->membership_type_id);
             $membership = CRM_Member_BAO_Membership::add($value, $ids);
             // add custom field values
             if (CRM_Utils_Array::value('custom', $value) && is_array($value['custom'])) {
                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_membership', $membership->id);
             }
         }
         CRM_Core_Session::setStatus("Your updates have been saved.");
     } else {
         CRM_Core_Session::setStatus("No updates have been saved.");
     }
 }