public function updateMembershipReminderDate()
    {
        require_once 'CRM/Member/PseudoConstant.php';
        //get all active statuses of membership.
        $allStatuses = CRM_Member_PseudoConstant::membershipStatus();
        //set membership reminder date if membership
        //record has one of the following status.
        $validStatus = array('New', 'Current', 'Grace');
        $statusIds = array();
        foreach ($validStatus as $status) {
            $statusId = array_search($status, $allStatuses);
            if ($statusId) {
                $statusIds[$statusId] = $statusId;
            }
        }
        //we don't have valid status to check,
        //therefore no need to proceed further.
        if (empty($statusIds)) {
            return;
        }
        //set reminder date for all memberships,
        //in case reminder date is missing and
        //membership type has reminder day set.
        $query = '
    UPDATE  civicrm_membership membership
INNER JOIN  civicrm_contact contact ON ( contact.id = membership.contact_id )
INNER JOIN  civicrm_membership_type type ON ( type.id = membership.membership_type_id )
       SET  membership.reminder_date = DATE_SUB( membership.end_date, INTERVAL type.renewal_reminder_day + 1 DAY )
     WHERE  membership.reminder_date IS NULL
       AND  contact.is_deleted = 0
       AND  ( contact.is_deceased IS NULL OR contact.is_deceased = 0 )
       AND  type.renewal_reminder_day IS NOT NULL
       AND  membership.status_id IN ( ' . implode(' , ', $statusIds) . ' )';
        CRM_Core_DAO::executeQuery($query);
    }
 /**
  * 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);
     }
 }
Exemple #3
0
 /**
  * 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);
}
 public function testPseudoConstantflush()
 {
     $params = array('name' => 'testStatus', 'is_active' => 1);
     $membershipStatus = CRM_Member_BAO_MembershipStatus::add($params);
     $defaults = array();
     $result = CRM_Member_BAO_MembershipStatus::retrieve($params, $defaults);
     $this->assertEquals($result->name, 'testStatus', 'Verify membership status name.');
     $updateParams = array('id' => $membershipStatus->id, 'name' => 'testStatus', 'label' => 'Changed Status', 'is_active' => 1);
     $membershipStatus2 = CRM_Member_BAO_MembershipStatus::add($updateParams);
     $result = CRM_Member_PseudoConstant::membershipStatus($membershipStatus->id, NULL, 'label', FALSE, FALSE);
     $this->assertEquals($result, 'Changed Status', 'Verify updated membership status label From PseudoConstant.');
     CRM_Member_BAO_MembershipStatus::del($membershipStatus->id);
 }
 /**
  * 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)));
 }
Exemple #10
0
 /**
  * Get all the membership statuss
  *
  * @access public
  * @return array - array reference of all membership statuss if any
  * @static
  */
 public static function &membershipStatus($id = null, $cond = null)
 {
     if (self::$membershipStatus === null) {
         self::$membershipStatus = array();
     }
     $index = $cond ? $cond : 'No Condition';
     if (!CRM_Utils_Array::value($index, self::$membershipStatus)) {
         CRM_Core_PseudoConstant::populate(self::$membershipStatus[$index], 'CRM_Member_DAO_MembershipStatus', false, 'name', 'is_active', $cond, 'weight');
     }
     if ($id) {
         if (array_key_exists($id, self::$membershipStatus[$index])) {
             return self::$membershipStatus[$index][$id];
         } else {
             return null;
         }
     }
     return self::$membershipStatus[$index];
 }
 /**
  * Get all the membership statuss
  *
  * @access public
  * @return array - array reference of all membership statuss if any
  * @static
  */
 public static function &membershipStatus($id = null, $cond = null, $column = 'name')
 {
     if (self::$membershipStatus === null) {
         self::$membershipStatus = array();
     }
     $cacheKey = $column;
     if ($cond) {
         $cacheKey .= "_{$cond}";
     }
     if (!isset(self::$membershipStatus[$cacheKey])) {
         CRM_Core_PseudoConstant::populate(self::$membershipStatus[$cacheKey], 'CRM_Member_DAO_MembershipStatus', false, $column, 'is_active', $cond, 'weight');
     }
     $value = null;
     if ($id) {
         $value = CRM_Utils_Array::value($id, self::$membershipStatus[$cacheKey]);
     } else {
         $value = self::$membershipStatus[$cacheKey];
     }
     return $value;
 }
 /**
  * @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;
 }
Exemple #13
0
 /**
  * Build the search form.
  *
  * @param CRM_Core_Form $form
  */
 public static function buildSearchForm(&$form)
 {
     $membershipStatus = CRM_Member_PseudoConstant::membershipStatus();
     $form->add('select', 'membership_status_id', ts('Membership Status(s)'), $membershipStatus, FALSE, array('id' => 'membership_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2'));
     $form->addEntityRef('membership_type_id', ts('Membership Type(s)'), array('entity' => 'MembershipType', 'multiple' => TRUE, 'placeholder' => ts('- any -'), 'select' => array('minimumInputLength' => 0)));
     $form->addElement('text', 'member_source', ts('Source'));
     CRM_Core_Form_Date::buildDateRange($form, 'member_join_date', 1, '_low', '_high', ts('From'), FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'member_start_date', 1, '_low', '_high', ts('From'), FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'member_end_date', 1, '_low', '_high', ts('From'), FALSE);
     $form->addYesNo('member_is_primary', ts('Primary Member?'), TRUE);
     $form->addYesNo('member_pay_later', ts('Pay Later?'), TRUE);
     $form->addYesNo('member_auto_renew', ts('Auto-Renew?'), TRUE);
     $form->addYesNo('member_test', ts('Membership is a Test?'), TRUE);
     $form->addYesNo('member_is_override', ts('Membership Status Is Override?'), TRUE);
     // add all the custom  searchable fields
     $extends = array('Membership');
     $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
     if ($groupDetails) {
         $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);
             }
         }
     }
     CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'member_campaign_id');
     $form->assign('validCiviMember', TRUE);
     $form->setDefaults(array('member_test' => 0));
 }
Exemple #14
0
 /**
  * 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;
 }
 /**
  * This function update contribution as well as related objects.
  */
 function transitionComponents($params, $processContributionObject = false)
 {
     // get minimum required values.
     $contactId = CRM_Utils_Array::value('contact_id', $params);
     $componentId = CRM_Utils_Array::value('component_id', $params);
     $componentName = CRM_Utils_Array::value('componentName', $params);
     $contributionId = CRM_Utils_Array::value('contribution_id', $params);
     $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
     // if we already processed contribution object pass previous status id.
     $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
     $updateResult = array();
     require_once 'CRM/Contribute/PseudoConstant.php';
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     // we process only ( Completed, Cancelled, or Failed ) contributions.
     if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) {
         return $updateResult;
     }
     if (!$componentName || !$componentId) {
         // get the related component details.
         $componentDetails = self::getComponentDetails($contributionId);
     } else {
         $componentDetails['contact_id'] = $contactId;
         $componentDetails['component'] = $componentName;
         if ($componentName = 'event') {
             $componentDetails['participant'] = $componentId;
         } else {
             $componentDetails['membership'] = $componentId;
         }
     }
     if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
         $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id');
     }
     // do check for required ids.
     if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) {
         return $updateResult;
     }
     //now we are ready w/ required ids, start processing.
     require_once 'CRM/Core/Payment/BaseIPN.php';
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $input = $ids = $objects = array();
     $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
     $ids['contribution'] = $contributionId;
     $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
     $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
     $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
     $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
     $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
     $ids['contributionRecur'] = null;
     $ids['contributionPage'] = null;
     if (!$baseIPN->validateData($input, $ids, $objects, false)) {
         CRM_Core_Error::fatal();
     }
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $pledgePayment =& $objects['pledge_payment'];
     $contribution =& $objects['contribution'];
     if ($pledgePayment) {
         require_once 'CRM/Pledge/BAO/Payment.php';
         $pledgePaymentIDs = array();
         foreach ($pledgePayment as $key => $object) {
             $pledgePaymentIDs[] = $object->id;
         }
         $pledgeID = $pledgePayment[0]->pledge_id;
     }
     require_once 'CRM/Event/PseudoConstant.php';
     require_once 'CRM/Event/BAO/Participant.php';
     require_once 'CRM/Pledge/BAO/Pledge.php';
     require_once 'CRM/Member/PseudoConstant.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
     if ($participant) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
         $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id');
     }
     // we might want to process contribution object.
     $processContribution = false;
     if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
         if ($membership) {
             $membership->status_id = array_search('Cancelled', $membershipStatuses);
             $membership->save();
             $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
     } else {
         if ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
             if ($membership) {
                 $membership->status_id = array_search('Expired', $membershipStatuses);
                 $membership->save();
                 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($participant) {
                 $updatedStatusId = array_search('Cancelled', $participantStatuses);
                 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($pledgePayment) {
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
         } else {
             if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
                 // only pending contribution related object processed.
                 if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) {
                     // this is case when we already processed contribution object.
                     return $updateResult;
                 } else {
                     if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
                         // this is case when we will going to process contribution object.
                         return $updateResult;
                     }
                 }
                 if ($membership) {
                     $format = '%Y%m%d';
                     require_once 'CRM/Member/BAO/MembershipType.php';
                     //CRM-4523
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     if ($currentMembership) {
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     require_once 'CRM/Member/BAO/MembershipStatus.php';
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     require_once 'CRM/Member/BAO/MembershipLog.php';
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y');
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($participant) {
                     $updatedStatusId = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                     $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($pledgePayment) {
                     CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                     $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
             }
         }
     }
     // process contribution object.
     if ($processContribution) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contributionParams = array();
         $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number');
         foreach ($fields as $field) {
             if (!CRM_Utils_Array::value($field, $params)) {
                 continue;
             }
             $contributionParams[$field] = $params[$field];
         }
         $ids = array('contribution' => $contributionId);
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
     }
     return $updateResult;
 }
Exemple #16
0
 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;
 }
Exemple #17
0
 /**
  * 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);
 }
 /**
  * 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;
     }
 }
 /**
  * Set contribution to failed
  * @param array $objects
  * @param object $transaction
  * @param array $input
  * @return boolean
  */
 function failed(&$objects, &$transaction, $input = array())
 {
     $contribution =& $objects['contribution'];
     $memberships = array();
     if (CRM_Utils_Array::value('membership', $objects)) {
         $memberships =& $objects['membership'];
         if (is_numeric($memberships)) {
             $memberships = array($objects['membership']);
         }
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $participant =& $objects['participant'];
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->contribution_status_id = array_search('Failed', $contributionStatus);
     $contribution->save();
     //add lineitems for recurring payments
     if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addRecurLineItems($objects['contributionRecur']->id, $contribution);
     }
     //copy initial contribution custom fields for recurring contributions
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         $this->copyCustomValues($objects['contributionRecur']->id, $contribution->id);
     }
     if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
         if (!empty($memberships)) {
             // if transaction is failed then set "Cancelled" as membership status
             $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus());
             foreach ($memberships as $membership) {
                 if ($membership) {
                     $membership->status_id = $cancelStatusId;
                     $membership->save();
                     //update related Memberships.
                     $params = array('status_id' => $cancelStatusId);
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
                 }
             }
         }
         if ($participant) {
             $participant->status_id = 4;
             $participant->save();
         }
     }
     $transaction->commit();
     CRM_Core_Error::debug_log_message("Setting contribution status to failed");
     //echo "Success: Setting contribution status to failed<p>";
     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);
         }
     }
 }
    /**
     * 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;
    }
 /**
  * Generate a query to locate recipients who match the given
  * schedule.
  *
  * @param \CRM_Core_DAO_ActionSchedule $schedule
  *   The schedule as configured by the administrator.
  * @param string $phase
  *   See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
  * @param array $defaultParams
  *
  * @return \CRM_Utils_SQL_Select
  * @see RecipientBuilder
  */
 public function createQuery($schedule, $phase, $defaultParams)
 {
     $selectedValues = (array) \CRM_Utils_Array::explodePadded($schedule->entity_value);
     $selectedStatuses = (array) \CRM_Utils_Array::explodePadded($schedule->entity_status);
     $query = \CRM_Utils_SQL_Select::from("{$this->entity} e")->param($defaultParams);
     $query['casAddlCheckFrom'] = 'civicrm_membership e';
     $query['casContactIdField'] = 'e.contact_id';
     $query['casEntityIdField'] = 'e.id';
     $query['casContactTableAlias'] = NULL;
     $query['casDateField'] = str_replace('membership_', 'e.', $schedule->start_action_date);
     // FIXME: Numbers should be constants.
     if (in_array(2, $selectedStatuses)) {
         //auto-renew memberships
         $query->where("e.contribution_recur_id IS NOT NULL");
     } elseif (in_array(1, $selectedStatuses)) {
         $query->where("e.contribution_recur_id IS NULL");
     }
     if (!empty($selectedValues)) {
         $query->where("e.membership_type_id IN (@memberTypeValues)")->param('memberTypeValues', $selectedValues);
     } else {
         $query->where("e.membership_type_id IS NULL");
     }
     $query->where("( e.is_override IS NULL OR e.is_override = 0 )");
     $query->merge($this->prepareMembershipPermissionsFilter());
     $query->where("e.status_id IN (#memberStatus)")->param('memberStatus', \CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id'));
     // Why is this only for civicrm_membership?
     if ($schedule->start_action_date && $schedule->is_repeat == FALSE) {
         $query['casUseReferenceDate'] = TRUE;
     }
     return $query;
 }
Exemple #23
0
 function alterMembershipStatusID($value, &$row)
 {
     return is_string(CRM_Member_PseudoConstant::membershipStatus($value, FALSE)) ? CRM_Member_PseudoConstant::membershipStatus($value, FALSE) : '';
 }
 /**
  * Create / update / delete membership for related contacts.
  *
  * This function will create/update/delete membership for related
  * contact based on 1) contact have active membership 2) that
  * membership is is extedned by the same relationship type to that
  * of the existing relationship.
  *
  * @param int $contactId
  *   contact id.
  * @param array $params
  *   array of values submitted by POST.
  * @param array $ids
  *   array of ids.
  * @param \const|int $action which action called this function
  *
  * @param bool $active
  *
  * @throws \CRM_Core_Exception
  */
 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE)
 {
     // Check the end date and set the status of the relationship
     // accordingly.
     $status = self::CURRENT;
     $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, array());
     $today = date('Ymd');
     // If a relationship hasn't yet started, just return for now
     // TODO: handle edge-case of updating start_date of an existing relationship
     if (!empty($params['start_date'])) {
         $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
         if ($today < $startDate) {
             return;
         }
     }
     if (!empty($params['end_date'])) {
         $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
         if ($today > $endDate) {
             $status = self::PAST;
         }
     }
     if ($action & CRM_Core_Action::ADD && $status & self::PAST) {
         // If relationship is PAST and action is ADD, do nothing.
         return;
     }
     $rel = explode('_', $params['relationship_type_id']);
     $relTypeId = $rel[0];
     if (!empty($rel[1])) {
         $relDirection = "_{$rel[1]}_{$rel[2]}";
     } else {
         // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
         // so we can assume _a_b
         $relDirection = "_a_b";
         $targetContact = array($params['contact_id_b'] => 1);
     }
     if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) {
         $contact = $contactId;
     } elseif ($action & CRM_Core_Action::UPDATE) {
         $contact = $ids['contact'];
         $targetContact = array($ids['contactTarget'] => 1);
     }
     // Build the 'values' array for
     // 1. ContactA
     // 2. ContactB
     // This will allow us to check if either of the contacts in
     // relationship have active memberships.
     $values = array();
     // 1. ContactA
     $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection);
     // 2. ContactB
     if (!empty($targetContact)) {
         foreach ($targetContact as $cid => $donCare) {
             $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId);
             $relTypeParams = array('id' => $relTypeId);
             $relTypeValues = array();
             CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
             if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
                 $values[$cid]['relationshipTypeDirection'] = '_a_b';
             } else {
                 $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b';
             }
         }
     }
     // CRM-15829 UPDATES
     // If we're looking for active memberships we must consider pending (id: 5) ones too.
     // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships.
     // As suggested by @davecivicrm, the pending status id is fetched using the CRM_Member_PseudoConstant::membershipStatus() class and method, since these ids differ from system to system.
     $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
     $query = 'SELECT * FROM `civicrm_membership_status`';
     if ($active) {
         $query .= ' WHERE `is_current_member` = 1 OR `id` = %1 ';
     }
     $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($pendingStatusId, 'Integer')));
     while ($dao->fetch()) {
         $membershipStatusRecordIds[$dao->id] = $dao->id;
     }
     // Now get the active memberships for all the contacts.
     // If contact have any valid membership(s), then add it to
     // 'values' array.
     foreach ($values as $cid => $subValues) {
         $memParams = array('contact_id' => $cid);
         $memberships = array();
         // CRM-15829 UPDATES
         // Since we want PENDING memberships as well, the $active flag needs to be set to false so that this will return all memberships and we can then filter the memberships based on the status IDs recieved above.
         CRM_Member_BAO_Membership::getValues($memParams, $memberships, FALSE, TRUE);
         // CRM-15829 UPDATES
         // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462
         foreach ($memberships as $key => $membership) {
             if (!isset($memberships[$key]['status_id'])) {
                 continue;
             }
             $membershipStatusId = $memberships[$key]['status_id'];
             if (!isset($membershipStatusRecordIds[$membershipStatusId])) {
                 unset($memberships[$key]);
             }
         }
         if (empty($memberships)) {
             continue;
         }
         //get ownerMembershipIds for related Membership
         //this is to handle memberships being deleted and recreated
         if (!empty($memberships['owner_membership_ids'])) {
             $ownerMemIds[$cid] = $memberships['owner_membership_ids'];
             unset($memberships['owner_membership_ids']);
         }
         $values[$cid]['memberships'] = $memberships;
     }
     $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
     foreach ($values as $cid => $details) {
         if (!array_key_exists('memberships', $details)) {
             continue;
         }
         $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, array()));
         $mainRelatedContactId = reset($relatedContacts);
         foreach ($details['memberships'] as $membershipId => $membershipValues) {
             $relTypeIds = array();
             if ($action & CRM_Core_Action::DELETE) {
                 // Delete memberships of the related contacts only if relationship type exists for membership type
                 $query = "\nSELECT relationship_type_id, relationship_direction\n  FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 $relTypeDirs = array();
                 while ($dao->fetch()) {
                     $relTypeId = $dao->relationship_type_id;
                     $relDirection = $dao->relationship_direction;
                 }
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
                 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 }
                 continue;
             }
             if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) {
                 // If relationship is PAST and action is UPDATE
                 // then delete the RELATED membership
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 continue;
             }
             // add / edit the memberships for related
             // contacts.
             // Get the Membership Type Details.
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
             // Check if contact's relationship type exists in membership type
             $relTypeDirs = array();
             if (!empty($membershipType['relationship_type_id'])) {
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
             }
             if (!empty($membershipType['relationship_direction'])) {
                 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
             }
             foreach ($relTypeIds as $key => $value) {
                 $relTypeDirs[] = $value . '_' . $relDirections[$key];
             }
             $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
             if (in_array($relTypeDir, $relTypeDirs)) {
                 // Check if relationship being created/updated is
                 // similar to that of membership type's
                 // relationship.
                 $membershipValues['owner_membership_id'] = $membershipId;
                 unset($membershipValues['id']);
                 unset($membershipValues['membership_contact_id']);
                 unset($membershipValues['contact_id']);
                 unset($membershipValues['membership_id']);
                 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
                     $membershipValues['contact_id'] = $relatedContactId;
                     if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) {
                         $membershipValues['status_id'] = $deceasedStatusId;
                         $membershipValues['skipStatusCal'] = TRUE;
                     }
                     foreach (array('join_date', 'start_date', 'end_date') as $dateField) {
                         if (!empty($membershipValues[$dateField])) {
                             $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
                         }
                     }
                     if ($action & CRM_Core_Action::UPDATE) {
                         //if updated relationship is already related to contact don't delete existing inherited membership
                         if (in_array($relTypeId, $relTypeIds) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) {
                             continue;
                         }
                         //delete the membership record for related
                         //contact before creating new membership record.
                         CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
                     }
                     // check whether we have some related memberships still available
                     $query = "\nSELECT count(*)\n  FROM civicrm_membership\n    LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n    AND is_current_member = 1";
                     $result = CRM_Core_DAO::singleValueQuery($query);
                     if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
                         CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
                     }
                 }
             } elseif ($action & CRM_Core_Action::UPDATE) {
                 // if action is update and updated relationship do
                 // not match with the existing
                 // membership=>relationship then we need to
                 // change the status of the membership record to expired for
                 // previous relationship -- CRM-12078.
                 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
                 if (empty($params['relationship_ids']) && !empty($params['id'])) {
                     $relIds = array($params['id']);
                 } else {
                     $relIds = CRM_Utils_Array::value('relationship_ids', $params);
                 }
                 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
                     $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
                     CRM_Member_BAO_Membership::add($membershipValues);
                     CRM_Core_Session::setStatus(ts("Inherited membership {$type} status was changed to Expired due to the change in relationship type."), ts('Record Updated'), 'alert');
                 }
             }
         }
     }
 }
 /**
  * @param $mappingID
  * @param $now
  * @param array $params
  *
  * @throws API_Exception
  */
 static function buildRecipientContacts($mappingID, $now, $params = array())
 {
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
     $actionSchedule->is_active = 1;
     if (!empty($params)) {
         _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
     }
     $actionSchedule->find();
     while ($actionSchedule->fetch()) {
         $mapping = new CRM_Core_DAO_ActionMapping();
         $mapping->id = $mappingID;
         $mapping->find(TRUE);
         // note: $where - this filtering applies for both
         // 'limit to' and 'addition to' options
         // $limitWhere - this filtering applies only for
         // 'limit to' option
         $select = $join = $where = $limitWhere = array();
         $limitTo = $actionSchedule->limit_to;
         $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR));
         $value = implode(',', $value);
         $status = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR));
         $status = implode(',', $status);
         $anniversary = false;
         if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
             $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name');
         }
         $from = "{$mapping->entity} e";
         if ($mapping->entity == 'civicrm_activity') {
             $contactField = 'r.contact_id';
             $table = 'civicrm_activity e';
             $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
             $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
             $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
             $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
             if ($limitTo == 0) {
                 // including the activity target contacts if 'in addition' is defined
                 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
             } else {
                 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
                     case 'Activity Assignees':
                         $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
                         break;
                     case 'Activity Source':
                         $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
                         break;
                     default:
                     case 'Activity Targets':
                         $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
                         break;
                 }
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = "e.activity_type_id IN ({$value})";
             } else {
                 $where[] = "e.activity_type_id IS NULL";
             }
             if (!empty($status)) {
                 $where[] = "e.status_id IN ({$status})";
             }
             $where[] = ' e.is_current_revision = 1 ';
             $where[] = ' e.is_deleted = 0 ';
             $dateField = 'e.activity_date_time';
         }
         if ($mapping->entity == 'civicrm_participant') {
             $table = 'civicrm_event r';
             $contactField = 'e.contact_id';
             $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
             if ($actionSchedule->recipient_listing && $limitTo) {
                 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR));
                 $rList = implode(',', $rList);
                 switch ($recipientOptions[$actionSchedule->recipient]) {
                     case 'participant_role':
                         $where[] = "e.role_id IN ({$rList})";
                         break;
                     default:
                         break;
                 }
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = $mapping->entity_value == 'event_type' ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
             } else {
                 $where[] = $mapping->entity_value == 'event_type' ? "r.event_type_id IS NULL" : "r.id IS NULL";
             }
             // participant status criteria not to be implemented
             // for additional recipients
             if (!empty($status)) {
                 $limitWhere[] = "e.status_id IN ({$status})";
             }
             $where[] = 'r.is_active = 1';
             $where[] = 'r.is_template = 0';
             $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
         }
         $notINClause = '';
         if ($mapping->entity == 'civicrm_membership') {
             $contactField = 'e.contact_id';
             $table = 'civicrm_membership e';
             // build where clause
             if ($status == 2) {
                 //auto-renew memberships
                 $where[] = "e.contribution_recur_id IS NOT NULL ";
             } elseif ($status == 1) {
                 $where[] = "e.contribution_recur_id IS NULL ";
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = "e.membership_type_id IN ({$value})";
             } else {
                 $where[] = "e.membership_type_id IS NULL";
             }
             $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
             $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
             $notINClause = self::permissionedRelationships($contactField);
             $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
             $mStatus = implode(',', $membershipStatus);
             $where[] = "e.status_id IN ({$mStatus})";
         }
         if ($mapping->entity == 'civicrm_contact') {
             if ($value == 'birth_date') {
                 $dateDBField = 'birth_date';
                 $table = 'civicrm_contact e';
                 $contactField = 'e.id';
                 $where[] = 'e.is_deleted = 0';
                 $where[] = 'e.is_deceased = 0';
             } else {
                 //custom field
                 $customFieldParams = array('id' => substr($value, 7));
                 $customGroup = $customField = array();
                 CRM_Core_BAO_CustomField::retrieve($customFieldParams, $customField);
                 $dateDBField = $customField['column_name'];
                 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
                 CRM_Core_BAO_CustomGroup::retrieve($customGroupParams, $customGroup);
                 $from = $table = "{$customGroup['table_name']} e";
                 $contactField = 'e.entity_id';
                 $where[] = '1';
                 // possible to have no "where" in this case
             }
             $status_ = explode(',', $status);
             if (in_array(2, $status_)) {
                 // anniversary mode:
                 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
                 $anniversary = true;
             } else {
                 // regular mode:
                 $dateField = 'e.' . $dateDBField;
             }
             // TODO get this working
             // TODO: Make sure everything's provided for repetition, etc.
         }
         // CRM-13577 Introduce Smart Groups Handling
         if ($actionSchedule->group_id) {
             // Need to check if its a smart group or not
             // Then decide which table to join onto the query
             $group = CRM_Contact_DAO_Group::getTableName();
             // Get the group information
             $sql = "\nSELECT     {$group}.id, {$group}.cache_date, {$group}.saved_search_id, {$group}.children\nFROM       {$group}\nWHERE      {$group}.id = {$actionSchedule->group_id}\n";
             $groupDAO = CRM_Core_DAO::executeQuery($sql);
             $isSmartGroup = FALSE;
             if ($groupDAO->fetch() && !empty($groupDAO->saved_search_id)) {
                 // Check that the group is in place in the cache and up to date
                 CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id);
                 // Set smart group flag
                 $isSmartGroup = TRUE;
             }
         }
         // CRM-13577 End Introduce Smart Groups Handling
         if ($limitTo) {
             if ($actionSchedule->group_id) {
                 // CRM-13577 If smart group then use Cache table
                 if ($isSmartGroup) {
                     $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
                     $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
                 } else {
                     $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
                     $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
                 }
             } elseif (!empty($actionSchedule->recipient_manual)) {
                 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
                 $where[] = "{$contactField} IN ({$rList})";
             }
         } else {
             $addGroup = $addWhere = '';
             if ($actionSchedule->group_id) {
                 // CRM-13577 If smart group then use Cache table
                 if ($isSmartGroup) {
                     $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
                     $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
                 } else {
                     $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
                     $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
                 }
             }
             if (!empty($actionSchedule->recipient_manual)) {
                 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
                 $addWhere = "c.id IN ({$rList})";
             }
         }
         $select[] = "{$contactField} as contact_id";
         $select[] = 'e.id as entity_id';
         $select[] = "'{$mapping->entity}' as entity_table";
         $select[] = "{$actionSchedule->id} as action_schedule_id";
         $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND\nreminder.entity_id          = e.id AND\nreminder.entity_table       = '{$mapping->entity}' AND\nreminder.action_schedule_id = %1";
         if ($anniversary) {
             // only consider reminders less than 11 months ago
             $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
         }
         if ($table != 'civicrm_contact e') {
             $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
         }
         if ($actionSchedule->start_action_date) {
             $startDateClause = array();
             $op = $actionSchedule->start_action_condition == 'before' ? '<=' : '>=';
             $operator = $actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD';
             $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
             $startDateClause[] = "'{$now}' >= {$date}";
             if ($mapping->entity == 'civicrm_participant') {
                 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
             } else {
                 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
             }
             $startDate = implode(' AND ', $startDateClause);
         } elseif ($actionSchedule->absolute_date) {
             $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
         }
         // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
         $dateClause = "reminder.id IS NULL AND {$startDate}";
         // start composing query
         $selectClause = 'SELECT ' . implode(', ', $select);
         $fromClause = "FROM {$from}";
         $joinClause = !empty($join) ? implode(' ', $join) : '';
         $whereClause = 'WHERE ' . implode(' AND ', $where);
         $limitWhereClause = '';
         if (!empty($limitWhere)) {
             $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
         }
         $query = "\nINSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)\n{$selectClause}\n{$fromClause}\n{$joinClause}\nLEFT JOIN {$reminderJoinClause}\n{$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}\n";
         CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
         if ($limitTo == 0) {
             $additionWhere = ' WHERE ';
             if ($actionSchedule->start_action_date) {
                 $additionWhere = $whereClause . ' AND ';
             }
             $contactTable = "civicrm_contact c";
             $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
             $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND\n          reminder.entity_id          = c.id AND\n          reminder.entity_table       = 'civicrm_contact' AND\n          reminder.action_schedule_id = {$actionSchedule->id}";
             $addWhereClause = '';
             if ($addWhere) {
                 $addWhereClause = "AND {$addWhere}";
             }
             $insertAdditionalSql = "\nINSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)\n{$addSelect}\nFROM ({$contactTable})\nLEFT JOIN {$additionReminderClause}\n{$addGroup}\nWHERE c.is_deleted = 0 AND c.is_deceased = 0\n{$addWhereClause}\n\nAND c.id NOT IN (\n     SELECT rem.contact_id\n     FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id\n     WHERE rem.action_schedule_id = {$actionSchedule->id}\n      AND rem.entity_table = '{$mapping->entity}'\n    )\nGROUP BY c.id\n";
             CRM_Core_DAO::executeQuery($insertAdditionalSql);
         }
         // if repeat is turned ON:
         if ($actionSchedule->is_repeat) {
             $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
             if ($actionSchedule->repetition_frequency_unit == 'day') {
                 $hrs = 24 * $actionSchedule->repetition_frequency_interval;
             } elseif ($actionSchedule->repetition_frequency_unit == 'week') {
                 $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7;
             } elseif ($actionSchedule->repetition_frequency_unit == 'month') {
                 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
             } elseif ($actionSchedule->repetition_frequency_unit == 'year') {
                 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
             } else {
                 $hrs = $actionSchedule->repetition_frequency_interval;
             }
             // (now <= repeat_end_time )
             $repeatEventClause = "'{$now}' <= {$repeatEvent}";
             // diff(now && logged_date_time) >= repeat_interval
             $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
             $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
             $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
             $sqlInsertValues = "{$selectClause}\n{$fromClause}\n{$joinClause}\nINNER JOIN {$reminderJoinClause}\n{$whereClause} {$limitWhereClause} AND {$repeatEventClause}\n{$groupByClause}\n{$havingClause}";
             $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer')));
             $arrValues = array();
             while ($valsqlInsertValues->fetch()) {
                 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
             }
             $valString = implode(',', $arrValues);
             if ($valString) {
                 $query = '
           INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
                 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
             }
             if ($limitTo == 0) {
                 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
                 $sqlEndEventCheck = "\nSELECT * FROM {$table}\n{$whereClause} AND {$repeatEventClause} LIMIT 1";
                 $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck);
                 if ($daoCheck->fetch()) {
                     $valSqlAdditionInsert = "\n{$addSelect}\nFROM  {$contactTable}\n{$addGroup}\nINNER JOIN {$additionReminderClause}\nWHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0\nGROUP BY reminder.contact_id\n{$havingClause}\n";
                     $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert);
                     $addValues = array();
                     while ($daoForVals->fetch()) {
                         $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
                     }
                     $valString = implode(',', $addValues);
                     if ($valString) {
                         $query = '
             INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
                         CRM_Core_DAO::executeQuery($query);
                     }
                 }
             }
         }
     }
 }
Exemple #26
0
 /**
  * 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;
 }
Exemple #27
0
 /**
  * Update membership status to deceased.
  * function return the status message for updated membership.
  *
  * @param array $deceasedParams
  *   having contact id and deceased value.
  *
  * @return null|string
  *   $updateMembershipMsg string  status message for updated membership.
  */
 public function updateMembershipStatus($deceasedParams)
 {
     $updateMembershipMsg = NULL;
     $contactId = CRM_Utils_Array::value('contact_id', $deceasedParams);
     $deceasedDate = CRM_Utils_Array::value('deceased_date', $deceasedParams);
     // process to set membership status to deceased for both active/inactive membership
     if ($contactId && $this->_contactType == 'Individual' && !empty($deceasedParams['is_deceased'])) {
         $session = CRM_Core_Session::singleton();
         $userId = $session->get('userID');
         if (!$userId) {
             $userId = $contactId;
         }
         // get deceased status id
         $allStatus = CRM_Member_PseudoConstant::membershipStatus();
         $deceasedStatusId = array_search('Deceased', $allStatus);
         if (!$deceasedStatusId) {
             return $updateMembershipMsg;
         }
         $today = time();
         if ($deceasedDate && strtotime($deceasedDate) > $today) {
             return $updateMembershipMsg;
         }
         // get non deceased membership
         $dao = new CRM_Member_DAO_Membership();
         $dao->contact_id = $contactId;
         $dao->whereAdd("status_id != {$deceasedStatusId}");
         $dao->find();
         $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
         $allStatus = CRM_Member_PseudoConstant::membershipStatus();
         $memCount = 0;
         while ($dao->fetch()) {
             // update status to deceased (for both active/inactive membership )
             CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id, 'status_id', $deceasedStatusId);
             // add membership log
             $membershipLog = array('membership_id' => $dao->id, 'status_id' => $deceasedStatusId, 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), 'modified_id' => $userId, 'modified_date' => date('Ymd'), 'membership_type_id' => $dao->membership_type_id, 'max_related' => $dao->max_related);
             CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
             //create activity when membership status is changed
             $activityParam = array('subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}", 'source_contact_id' => $userId, 'target_contact_id' => $dao->contact_id, 'source_record_id' => $dao->id, 'activity_type_id' => array_search('Change Membership Status', $activityTypes), 'status_id' => 2, 'version' => 3, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'), 'is_auto' => 0, 'is_current_revision' => 1, 'is_deleted' => 0);
             $activityResult = civicrm_api('activity', 'create', $activityParam);
             $memCount++;
         }
         // set status msg
         if ($memCount) {
             $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.", array(1 => $memCount));
         }
     }
     return $updateMembershipMsg;
 }
 /**
  * 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));
 }
Exemple #29
0
 /**
  * Get all Cancelled Membership(s) for a contact
  *
  * @param int $contactID
  *   Contact id.
  * @param bool $isTest
  *   Mode of payment.
  *
  * @return array
  *   Array of membership type
  */
 public static function getContactsCancelledMembership($contactID, $isTest = FALSE)
 {
     if (!$contactID) {
         return array();
     }
     $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
     $queryParams = array(1 => array($contactID, 'Integer'), 2 => array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), 'Integer'), 3 => array($isTest, 'Boolean'));
     $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
     $cancelledMembershipIds = array();
     while ($dao->fetch()) {
         $cancelledMembershipIds[] = $dao->membership_type_id;
     }
     return $cancelledMembershipIds;
 }
 /**
  * This function process contribution related objects.
  *
  * @param int $contributionId
  * @param int $statusId
  * @param int|null $previousStatusId
  *
  * @return null|string
  */
 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL)
 {
     $statusMsg = NULL;
     if (!$contributionId || !$statusId) {
         return $statusMsg;
     }
     $params = array('contribution_id' => $contributionId, 'contribution_status_id' => $statusId, 'previous_contribution_status_id' => $previousStatusId, 'receive_date' => $receiveDate);
     $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
     if (!is_array($updateResult) || !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) || !is_array($updatedComponents) || empty($updatedComponents)) {
         return $statusMsg;
     }
     // get the user display name.
     $sql = "\n   SELECT  display_name as displayName\n     FROM  civicrm_contact\nLEFT JOIN  civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )\n    WHERE  civicrm_contribution.id = {$contributionId}";
     $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
     // get the status message for user.
     foreach ($updatedComponents as $componentName => $updatedStatusId) {
         if ($componentName == 'CiviMember') {
             $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, CRM_Member_PseudoConstant::membershipStatus());
             if ($updatedStatusName == 'Cancelled') {
                 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
             } elseif ($updatedStatusName == 'Expired') {
                 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
             } else {
                 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
                 if ($endDate) {
                     $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.", array(1 => $userDisplayName, 2 => $endDate));
                 }
             }
         }
         if ($componentName == 'CiviEvent') {
             $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, CRM_Event_PseudoConstant::participantStatus());
             if ($updatedStatusName == 'Cancelled') {
                 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
             } elseif ($updatedStatusName == 'Registered') {
                 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
             }
         }
         if ($componentName == 'CiviPledge') {
             $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
             if ($updatedStatusName == 'Cancelled') {
                 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
             } elseif ($updatedStatusName == 'Failed') {
                 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
             } elseif ($updatedStatusName == 'Completed') {
                 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
             }
         }
     }
     return $statusMsg;
 }