function createContact(&$input, &$ids, &$objects)
 {
     $params = array();
     $billingID = $ids['billing'];
     $lookup = array('first_name', 'last_name', "street_address-{$billingID}", "city-{$billingID}", "state-{$billingID}", "postal_code-{$billingID}", "country-{$billingID}");
     foreach ($lookup as $name) {
         $params[$name] = $input[$name];
     }
     if (!empty($params)) {
         // update contact record
         $contact = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray, $ids['contact']);
     }
     return TRUE;
 }
Exemplo n.º 2
0
function civicrm_dwutils_get_deduped_contact($params) {
    
    require_once 'CRM/Dedupe/Finder.php';
    $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
    $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
    
    $fields = array();
    foreach($params as $key => $value) {
	if(strncmp($key, 'fields_', 7) == 0) {
	    $new_key = str_replace('fields_', '', $key);
	    $fields[$new_key] = 1;
	    unset($params[$key]);
	}
    }
    
    print_r($fields);
    
    $contact_id  = CRM_Utils_Array::value( 0, $ids );
    $contact_result =& CRM_Contact_BAO_Contact::createProfileContact( $params, $fields, $contact_id );
    return $contact_result;
}
Exemplo n.º 3
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->getName());
     if (!$this->_contactID && isset($params['cms_create_account'])) {
         foreach ($params as $key => $value) {
             if (substr($key, 0, 5) == 'email' && !empty($value)) {
                 list($fieldName, $locTypeId) = CRM_Utils_System::explode('-', $key, 2);
                 $isPrimary = 0;
                 if ($locTypeId == 'Primary') {
                     $locTypeDefault = CRM_Core_BAO_LocationType::getDefault();
                     $locTypeId = NULL;
                     if ($locTypeDefault) {
                         $locTypeId = $locTypeDefault->id;
                     }
                     $isPrimary = 1;
                 }
                 $params['email'] = array();
                 $params['email'][1]['email'] = $value;
                 $params['email'][1]['location_type_id'] = $locTypeId;
                 $params['email'][1]['is_primary'] = $isPrimary;
             }
         }
     }
     $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
     $dedupeParams['check_permission'] = FALSE;
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised');
     if ($ids) {
         $this->_contactID = $ids['0'];
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID);
     $this->set('contactID', $contactID);
     if (!empty($params['email'])) {
         $params['email'] = $params['email'][1]['email'];
     }
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email');
 }
Exemplo n.º 4
0
 /**
  * Function to create is honor of
  * 
  * @param array $params  associated array of fields (by reference)
  * @param int   $honorId honor Id
  *
  * @return contact id
  */
 function createHonorContact(&$params, $honorId = null)
 {
     $honorParams = array('first_name' => $params["honor_first_name"], 'last_name' => $params["honor_last_name"], 'prefix_id' => $params["honor_prefix_id"], 'email-Primary' => $params["honor_email"]);
     if (!$honorId) {
         require_once "CRM/Core/BAO/UFGroup.php";
         $honorParams['email'] = $params["honor_email"];
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($honorParams, 'Individual');
         $dedupeParams['check_permission'] = false;
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
         // if we find more than one contact, use the first one
         $honorId = CRM_Utils_Array::value(0, $ids);
     }
     $contact =& CRM_Contact_BAO_Contact::createProfileContact($honorParams, CRM_Core_DAO::$_nullArray, $honorId);
     return $contact;
 }
Exemplo n.º 5
0
 /**
  * method for creating contact
  * 
  * 
  */
 function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = null, $requiredCheck = true)
 {
     $dupeCheck = false;
     $newContact = null;
     if (is_null($contactId) && $onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
         $dupeCheck = (bool) $onDuplicate;
     }
     //get the prefix id etc if exists
     CRM_Contact_BAO_Contact::resolveDefaults($formatted, true);
     require_once 'api/v2/Contact.php';
     // setting required check to false, CRM-2839
     // plus we do our own required check in import
     $error = civicrm_contact_check_params($formatted, $dupeCheck, true, false);
     if (is_null($error) && civicrm_error(_civicrm_validate_formatted_contact($formatted))) {
         $error = _civicrm_validate_formatted_contact($formatted);
     }
     $newContact = $error;
     if (is_null($error)) {
         if ($contactId) {
             $this->formatParams($formatted, $onDuplicate, (int) $contactId);
         }
         // pass doNotResetCache flag since resetting and rebuilding cache could be expensive.
         $config =& CRM_Core_Config::singleton();
         $config->doNotResetCache = 1;
         $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, null, null, $formatted['contact_type']);
         $config->doNotResetCache = 0;
         $contact = array('contact_id' => $cid);
         $defaults = array();
         $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
     }
     //get the id of the contact whose street address is not parsable, CRM-5886
     if ($this->_parseStreetAddress && $newContact->address) {
         foreach ($newContact->address as $address) {
             if ($address['street_address'] && (!CRM_Utils_Array::value('street_number', $address) || !CRM_Utils_Array::value('street_name', $address))) {
                 $this->_unparsedStreetAddressContacts[] = array('id' => $newContact->id, 'streetAddress' => $address['street_address']);
             }
         }
     }
     return $newContact;
 }
Exemplo n.º 6
0
 /**
  * @param null $registeringContactID
  * @param array $fields
  *
  * @return int|mixed|null
  */
 static function find_or_create_contact($registeringContactID = NULL, $fields = array())
 {
     $contact_id = self::find_contact($fields);
     if ($contact_id) {
         return $contact_id;
     }
     $contact_params = array('email-Primary' => CRM_Utils_Array::value('email', $fields, NULL), 'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL), 'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL), 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, TRUE));
     $no_fields = array();
     $contact_id = CRM_Contact_BAO_Contact::createProfileContact($contact_params, $no_fields, NULL);
     if (!$contact_id) {
         CRM_Core_Error::displaySessionError("Could not create or match a contact with that email address.  Please contact the webmaster.");
     }
     return $contact_id;
 }
Exemplo n.º 7
0
 /**
  * Post form submission handling.
  *
  * This is also called from the test suite.
  *
  * @param int $contactID
  *
  * @return array
  */
 protected function processFormSubmission($contactID)
 {
     $isPayLater = $this->_params['is_pay_later'];
     if (!isset($this->_params['payment_processor_id'])) {
         // If there is no processor we are using the pay-later manual pseudo-processor.
         // (note it might make sense to make this a row in the processor table in the db).
         $this->_params['payment_processor_id'] = 0;
     }
     if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] == 0) {
         $this->_params['is_pay_later'] = $isPayLater = TRUE;
     }
     // add a description field at the very beginning
     $this->_params['description'] = ts('Online Contribution') . ': ' . ($this->_pcpInfo['title'] ? $this->_pcpInfo['title'] : $this->_values['title']);
     $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values);
     // fix currency ID
     $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
     //carry payment processor id.
     if (CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
         $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
     }
     $premiumParams = $membershipParams = $params = $this->_params;
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     $fields = array('email-Primary' => 1);
     // get the add to groups
     $addToGroups = array();
     // now set the values for the billing location.
     foreach ($this->_fields as $name => $value) {
         $fields[$name] = 1;
         // get the add to groups for uf fields
         if (!empty($value['add_to_group_id'])) {
             $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
         }
     }
     $fields = $this->formatParamsForPaymentProcessor($fields);
     // billing email address
     $fields["email-{$this->_bltID}"] = 1;
     // if onbehalf-of-organization contribution, take out
     // organization params in a separate variable, to make sure
     // normal behavior is continued. And use that variable to
     // process on-behalf-of functionality.
     if (!empty($this->_values['onbehalf_profile_id'])) {
         $behalfOrganization = array();
         $orgFields = array('organization_name', 'organization_id', 'org_option');
         foreach ($orgFields as $fld) {
             if (array_key_exists($fld, $params)) {
                 $behalfOrganization[$fld] = $params[$fld];
                 unset($params[$fld]);
             }
         }
         if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
             foreach ($params['onbehalf'] as $fld => $values) {
                 if (strstr($fld, 'custom_')) {
                     $behalfOrganization[$fld] = $values;
                 } elseif (!strstr($fld, '-')) {
                     if (in_array($fld, array('contribution_campaign_id', 'member_campaign_id'))) {
                         $fld = 'campaign_id';
                     } else {
                         $behalfOrganization[$fld] = $values;
                     }
                     $this->_params[$fld] = $values;
                 }
             }
         }
         if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
             foreach ($params['onbehalf_location'] as $block => $vals) {
                 //fix for custom data (of type checkbox, multi-select)
                 if (substr($block, 0, 7) == 'custom_') {
                     continue;
                 }
                 // fix the index of block elements
                 if (is_array($vals)) {
                     foreach ($vals as $key => $val) {
                         //dont adjust the index of address block as
                         //it's index is WRT to location type
                         $newKey = $block == 'address' ? $key : ++$key;
                         $behalfOrganization[$block][$newKey] = $val;
                     }
                 }
             }
             unset($params['onbehalf_location']);
         }
         if (!empty($params['onbehalf[image_URL]'])) {
             $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
         }
     }
     // check for profile double opt-in and get groups to be subscribed
     $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
     // since we are directly adding contact to group lets unset it from mailing
     if (!empty($addToGroups)) {
         foreach ($addToGroups as $groupId) {
             if (isset($subscribeGroupIds[$groupId])) {
                 unset($subscribeGroupIds[$groupId]);
             }
         }
     }
     foreach ($addToGroups as $k) {
         if (array_key_exists($k, $subscribeGroupIds)) {
             unset($addToGroups[$k]);
         }
     }
     if (empty($contactID)) {
         $dupeParams = $params;
         if (!empty($dupeParams['onbehalf'])) {
             unset($dupeParams['onbehalf']);
         }
         if (!empty($dupeParams['honor'])) {
             unset($dupeParams['honor']);
         }
         $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
         $dedupeParams['check_permission'] = FALSE;
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
         // if we find more than one contact, use the first one
         $contactID = CRM_Utils_Array::value(0, $ids);
         // Fetch default greeting id's if creating a contact
         if (!$contactID) {
             foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
                 if (!isset($params[$greeting])) {
                     $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
                 }
             }
         }
         $contactType = NULL;
     } else {
         $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contactID, $addToGroups, NULL, $contactType, TRUE);
     // Make the contact ID associated with the contribution available at the Class level.
     // Also make available to the session.
     //@todo consider handling this in $this->getContactID();
     $this->set('contactID', $contactID);
     $this->_contactID = $contactID;
     //get email primary first if exist
     $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
     if (!$subscriptionEmail['email']) {
         $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
     }
     // subscribing contact to groups
     if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
         CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
     }
     // If onbehalf-of-organization contribution / signup, add organization
     // and it's location.
     if (isset($this->_values['onbehalf_profile_id']) && isset($behalfOrganization['organization_name'])) {
         $ufFields = array();
         foreach ($this->_fields['onbehalf'] as $name => $value) {
             $ufFields[$name] = 1;
         }
         self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values, $this->_params, $ufFields);
     } elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
         // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
         // store current user id as related contact for later use for mailing / activity..
         $this->_values['related_contact'] = $contactID;
         $this->_params['related_contact'] = $contactID;
         // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
         $contactID = $this->_membershipContactID;
     }
     // lets store the contactID in the session
     // for things like tell a friend
     $session = CRM_Core_Session::singleton();
     if (!$session->get('userID')) {
         $session->set('transaction.userID', $contactID);
     } else {
         $session->set('transaction.userID', NULL);
     }
     $this->_useForMember = $this->get('useForMember');
     // store the fact that this is a membership and membership type is selected
     if (!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks' || $this->_useForMember) {
         if (!$this->_useForMember) {
             $this->assign('membership_assign', TRUE);
             $this->set('membershipTypeID', $this->_params['selectMembership']);
         }
         if ($this->_action & CRM_Core_Action::PREVIEW) {
             $membershipParams['is_test'] = 1;
         }
         if ($this->_params['is_pay_later']) {
             $membershipParams['is_pay_later'] = 1;
         }
         //inherit campaign from contribution page.
         if (!array_key_exists('campaign_id', $membershipParams)) {
             $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
         $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $isPayLater);
     } else {
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($paymentParams['onbehalf']) && is_array($paymentParams['onbehalf'])) {
             foreach ($paymentParams['onbehalf'] as $key => $value) {
                 if (strstr($key, 'custom_')) {
                     $this->_params[$key] = $value;
                 }
             }
         }
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams, $contactID, $this->wrangleFinancialTypeID($this->_values['financial_type_id']), 'contribution', $this->_mode == 'test' ? 1 : 0, CRM_Utils_Array::value('is_recur', $paymentParams));
         if (empty($result['is_payment_failure'])) {
             // @todo move premium processing to complete transaction if it truly is an 'after' action.
             $this->postProcessPremium($premiumParams, $result['contribution']);
         }
         if (!empty($result['contribution'])) {
             // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
             $this->completeTransaction($result, $result['contribution']->id);
         }
         return $result;
     }
 }
Exemplo n.º 8
0
 /**
  * Retrieve a contact ID and if not present.
  *
  * Create one with this email
  *
  * @param string $email
  * @param string $name
  * @param bool $create
  * @param string $mail
  *
  * @return int|null
  */
 public static function getContactID($email, $name = NULL, $create = TRUE, &$mail)
 {
     $dao = CRM_Contact_BAO_Contact::matchContactOnEmail($email, 'Individual');
     $contactID = NULL;
     if ($dao) {
         $contactID = $dao->contact_id;
     }
     $result = NULL;
     CRM_Utils_Hook::emailProcessorContact($email, $contactID, $result);
     if (!empty($result)) {
         if ($result['action'] == self::EMAILPROCESSOR_IGNORE) {
             return NULL;
         }
         if ($result['action'] == self::EMAILPROCESSOR_OVERRIDE) {
             return $result['contactID'];
         }
         // else this is now create individual
         // so we just fall out and do what we normally do
     }
     if ($contactID) {
         return $contactID;
     }
     if (!$create) {
         return NULL;
     }
     // contact does not exist, lets create it
     $params = array('contact_type' => 'Individual', 'email-Primary' => $email);
     CRM_Utils_String::extractName($name, $params);
     return CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
 }
Exemplo n.º 9
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $ufGroupId = $this->get('ufGroupId');
     $notify = NULL;
     $inValidSubtypeCnt = 0;
     //send profile notification email if 'notify' field is set
     $notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $ufGroupId, 'notify');
     foreach ($params['field'] as $key => $value) {
         //CRM-5521
         //validate subtype before updating
         if (CRM_Utils_Array::value('contact_sub_type', $value) && !CRM_Contact_BAO_ContactType::isAllowEdit($key)) {
             unset($value['contact_sub_type']);
             $inValidSubtypeCnt++;
         }
         $value['preserveDBName'] = $this->_preserveDefault;
         //parse street address, CRM-7768
         self::parseStreetAddress($value, $this);
         CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields, $key, NULL, $ufGroupId);
         if ($notify) {
             $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($ufGroupId, $key, NULL);
             CRM_Core_BAO_UFGroup::commonSendMail($key, $values);
         }
     }
     $statusMsg = ts("Your updates have been saved.");
     if ($inValidSubtypeCnt) {
         $statusMsg .= ' ' . ts('Contact SubType field of %1 number of contact(s) has not been updated.', array(1 => $inValidSubtypeCnt));
     }
     CRM_Core_Session::setStatus("{$statusMsg}");
 }
Exemplo n.º 10
0
 /**
  * method for creating contact
  * 
  * 
  */
 function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = null, $requiredCheck = true)
 {
     $dupeCheck = false;
     $newContact = null;
     if (is_null($contactId) && $onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
         $dupeCheck = (bool) $onDuplicate;
     }
     //get the prefix id etc if exists
     CRM_Contact_BAO_Contact::resolveDefaults($formatted, true);
     require_once 'api/v2/Contact.php';
     // setting required check to false, CRM-2839
     // plus we do our own required check in import
     $error = civicrm_contact_check_params($formatted, $dupeCheck, true, false);
     if (is_null($error) && civicrm_error(_civicrm_validate_formatted_contact($formatted))) {
         $error = _civicrm_validate_formatted_contact($formatted);
     }
     $newContact = $error;
     if (is_null($error)) {
         if ($contactId) {
             $this->formatParams($formatted, $onDuplicate, (int) $contactId);
         }
         $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, null, null, $formatted['contact_type']);
         $contact = array('contact_id' => $cid);
         $defaults = array();
         $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
     }
     return $newContact;
 }
Exemplo n.º 11
0
/**
 * @todo What does this do? If it's still useful, figure out where it should live and what it should be named.
 *
 * @deprecated deprecated since version 2.2.3
 */
function civicrm_replace_contact_formatted($contactId, &$params, &$fields)
{
    //$contact = civcrm_get_contact(array('contact_id' => $contactId));
    $delContact = array('contact_id' => $contactId);
    civicrm_contact_delete($delContact);
    $cid = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, NULL, NULL, NULL, $params['contact_type']);
    return civicrm_create_success($cid);
}
Exemplo n.º 12
0
 /**
  * Submit function.
  *
  * This is also accessed by unit tests.
  *
  * @param array $formValues
  *
  * @return array
  */
 public function submit($formValues)
 {
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $joinDate = $startDate = $endDate = NULL;
     $membershipTypes = $membership = $calcDate = array();
     $membershipType = NULL;
     $mailSend = FALSE;
     $formValues = $this->setPriceSetParameters($formValues);
     $params = $softParams = $ids = array();
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $ids['userId'] = CRM_Core_Session::singleton()->get('userID');
     // Set variables that we normally get from context.
     // In form mode these are set in preProcess.
     //TODO: set memberships, fixme
     $this->setContextVariables($formValues);
     $this->_memTypeSelected = self::getSelectedMemberships($this->_priceSet, $formValues);
     if (empty($formValues['financial_type_id'])) {
         $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
     }
     $config = CRM_Core_Config::singleton();
     $this->convertDateFieldsToMySQL($formValues);
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($formValues['auto_renew'])) {
         $params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     $isQuickConfig = $this->_priceSet['is_quick_config'];
     $termsByType = array();
     $lineItem = array($this->_priceSetId => array());
     CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $formValues, $lineItem[$this->_priceSetId]);
     if (CRM_Utils_Array::value('tax_amount', $formValues)) {
         $params['tax_amount'] = $formValues['tax_amount'];
     }
     $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
     $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
     if (!empty($lineItem[$this->_priceSetId])) {
         foreach ($lineItem[$this->_priceSetId] as &$li) {
             if (!empty($li['membership_type_id'])) {
                 if (!empty($li['membership_num_terms'])) {
                     $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                 }
             }
             ///CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             if ($isQuickConfig && $submittedFinancialType) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Membership');
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($formValues['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         if (!$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'));
         }
         // add all the additional payment params we need
         $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
         $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
         $formValues['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues);
         $formValues['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues);
         $formValues['ip_address'] = CRM_Utils_System::ipAddress();
         $formValues['amount'] = $params['total_amount'];
         $formValues['currencyID'] = $config->defaultCurrency;
         $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
         $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
         $formValues['financial_type_id'] = $params['financial_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $formValues;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($formValues['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             }
         }
         if (!empty($formValues['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recurring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $financialType = new CRM_Financial_DAO_FinancialType();
             $financialType->id = $params['financial_type_id'];
             $financialType->find(TRUE);
             $this->_params = $formValues;
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this, $paymentParams, NULL, array('contact_id' => $this->_contributorContactID, 'line_item' => $lineItem, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams), 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues), 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)), 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams), 'payment_instrument_id' => $this->_paymentProcessor['payment_instrument_id']), $financialType, TRUE, FALSE, $this->_bltID);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = $this->_paymentProcessor['object'];
             try {
                 $result = $payment->doPayment($paymentParams);
                 $formValues = array_merge($formValues, $result);
                 // Assign amount to template if payment was successful.
                 $this->assign('amount', $params['total_amount']);
             } catch (PaymentProcessorException $e) {
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID, $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 CRM_Core_Error::displaySessionError($result);
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
             }
         }
         if ($formValues['payment_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($formValues['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $formValues['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $formValues);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             // This is required to trigger the recording of the membership contribution in the
             // CRM_Member_BAO_Membership::Create function.
             // @todo stop setting this & 'teach' the create function to respond to something
             // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
             // process -
             // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
             $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result);
             if (!empty($paymentParams['is_recur'])) {
                 // The earlier process created the line items (although we want to get rid of the earlier one in favour
                 // of a single path!
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$this->_priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$this->_priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$this->_priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
         // handled in the receipt. But by setting one we avoid breaking templates for now
         // although at some point we should switch in the templates.
         $formValues['receipt_text_signup'] = $formValues['receipt_text'];
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     $isRecur = CRM_Utils_Array::value('is_recur', $params);
     $this->setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
     return $createdMemberships;
 }
Exemplo n.º 13
0
 /**
  * Synchronize the object with the UF Match entry. Can be called stand-alone from
  * the drupalUsers script
  *
  * @param Object $user
  *   The drupal user object.
  * @param string $userKey
  *   The id of the user from the uf object.
  * @param string $uniqId
  *   The OpenID of the user.
  * @param string $uf
  *   The name of the user framework.
  * @param int $status
  *   Returns the status if user created or already exits (used for CMS sync).
  * @param string $ctype
  *   contact type
  * @param bool $isLogin
  *
  * @return CRM_Core_DAO_UFMatch|bool
  */
 public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = NULL, $ctype = NULL, $isLogin = FALSE)
 {
     $config = CRM_Core_Config::singleton();
     if (!CRM_Utils_Rule::email($uniqId)) {
         $retVal = $status ? NULL : FALSE;
         return $retVal;
     }
     $newContact = FALSE;
     // make sure that a contact id exists for this user id
     $ufmatch = new CRM_Core_DAO_UFMatch();
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     $ufmatch->uf_id = $userKey;
     if (!$ufmatch->find(TRUE)) {
         $transaction = new CRM_Core_Transaction();
         $dao = NULL;
         if (!empty($_POST) && !$isLogin) {
             $params = $_POST;
             $params['email'] = $uniqId;
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             $dedupeParams['check_permission'] = FALSE;
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
             if (!empty($ids) && Civi::settings()->get('uniq_email_per_site')) {
                 // restrict dupeIds to ones that belong to current domain/site.
                 $siteContacts = CRM_Core_BAO_Domain::getContactList();
                 foreach ($ids as $index => $dupeId) {
                     if (!in_array($dupeId, $siteContacts)) {
                         unset($ids[$index]);
                     }
                 }
                 // re-index the array
                 $ids = array_values($ids);
             }
             if (!empty($ids)) {
                 $dao = new CRM_Core_DAO();
                 $dao->contact_id = $ids[0];
             }
         } else {
             $dao = CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
         }
         $found = FALSE;
         if ($dao) {
             // ensure there does not exists a contact_id / uf_id pair
             // in the DB. This might be due to multiple emails per contact
             // CRM-9091
             $sql = "\nSELECT id\nFROM   civicrm_uf_match\nWHERE  contact_id = %1\nAND    domain_id = %2\n";
             $params = array(1 => array($dao->contact_id, 'Integer'), 2 => array(CRM_Core_Config::domainID(), 'Integer'));
             $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
             if (!$conflict) {
                 $found = TRUE;
                 $ufmatch->contact_id = $dao->contact_id;
                 $ufmatch->uf_name = $uniqId;
             }
         }
         if (!$found) {
             if ($config->userSystem->is_drupal) {
                 $mail = 'mail';
             } elseif ($uf == 'WordPress') {
                 $mail = 'user_email';
             } else {
                 $mail = 'email';
             }
             if (is_object($user)) {
                 $params = array('email-Primary' => $user->{$mail});
             }
             if ($ctype == 'Organization') {
                 $params['organization_name'] = $uniqId;
             } elseif ($ctype == 'Household') {
                 $params['household_name'] = $uniqId;
             }
             if (!$ctype) {
                 $ctype = "Individual";
             }
             $params['contact_type'] = $ctype;
             // extract first / middle / last name
             // for joomla
             if ($uf == 'Joomla' && $user->name) {
                 CRM_Utils_String::extractName($user->name, $params);
             }
             if ($uf == 'WordPress') {
                 if ($user->first_name) {
                     $params['first_name'] = $user->first_name;
                 }
                 if ($user->last_name) {
                     $params['last_name'] = $user->last_name;
                 }
             }
             $contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
             $ufmatch->contact_id = $contactId;
             $ufmatch->uf_name = $uniqId;
         }
         // check that there are not two CMS IDs matching the same CiviCRM contact - this happens when a civicrm
         // user has two e-mails and there is a cms match for each of them
         // the gets rid of the nasty fata error but still reports the error
         $sql = "\nSELECT uf_id\nFROM   civicrm_uf_match\nWHERE  ( contact_id = %1\nOR     uf_name      = %2\nOR     uf_id        = %3 )\nAND    domain_id    = %4\n";
         $params = array(1 => array($ufmatch->contact_id, 'Integer'), 2 => array($ufmatch->uf_name, 'String'), 3 => array($ufmatch->uf_id, 'Integer'), 4 => array($ufmatch->domain_id, 'Integer'));
         $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
         if (!$conflict) {
             $ufmatch = CRM_Core_BAO_UFMatch::create((array) $ufmatch);
             $ufmatch->free();
             $newContact = TRUE;
             $transaction->commit();
         } else {
             $msg = ts("Contact ID %1 is a match for %2 user %3 but has already been matched to %4", array(1 => $ufmatch->contact_id, 2 => $uf, 3 => $ufmatch->uf_id, 4 => $conflict));
             unset($conflict);
         }
     }
     if ($status) {
         return $newContact;
     } else {
         return $ufmatch;
     }
 }
Exemplo n.º 14
0
 /**
  * Update contact fields.
  *
  * @param int $contactID
  * @param array $params
  * @param array $fields
  * @param CRM_Core_Form $form
  *
  * @return int
  */
 public static function updateContactFields($contactID, $params, $fields, &$form)
 {
     //add the contact to group, if add to group is selected for a
     //particular uf group
     // get the add to groups
     $addToGroups = array();
     if (!empty($form->_fields)) {
         foreach ($form->_fields as $key => $value) {
             if (!empty($value['add_to_group_id'])) {
                 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
             }
         }
     }
     // check for profile double opt-in and get groups to be subscribed
     $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
     foreach ($addToGroups as $k) {
         if (array_key_exists($k, $subscribeGroupIds)) {
             unset($addToGroups[$k]);
         }
     }
     // since we are directly adding contact to group lets unset it from mailing
     if (!empty($addToGroups)) {
         foreach ($addToGroups as $groupId) {
             if (isset($subscribeGroupIds[$groupId])) {
                 unset($subscribeGroupIds[$groupId]);
             }
         }
     }
     if ($contactID) {
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
         if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
             // we unset this here because the downstream function ignores the contactID we give it
             // if it is set & it is difficult to understand the implications of 'fixing' this downstream
             // but if we are passing a contact id into this function it's reasonable to assume we don't
             // want it ignored
             unset($params['contact_id']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contactID, $addToGroups, NULL, $ctype, TRUE);
     } else {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             if (!isset($params[$greeting . '_id'])) {
                 $params[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, NULL, $addToGroups, NULL, NULL, TRUE);
         $form->set('contactID', $contactID);
     }
     //get email primary first if exist
     $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
     if (!$subscribtionEmail['email']) {
         $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
     }
     // subscribing contact to groups
     if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) {
         CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID);
     }
     return $contactID;
 }
Exemplo n.º 15
0
 /**
  * Add the billing address to the contact who paid.
  */
 protected function processBillingAddress()
 {
     $fields = array();
     // set email for primary location.
     $fields['email-Primary'] = 1;
     $this->_params['email-5'] = $this->_params['email-Primary'] = $this->_contributorEmail;
     // also add location name to the array
     $this->_params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $this->_params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $this->_params) . ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
     $this->_params["address_name-{$this->_bltID}"] = trim($this->_params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $fields["email-{$this->_bltID}"] = 1;
     list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($this->_params, $this->_bltID);
     $addressParams['preserveDBName'] = TRUE;
     if ($hasBillingField) {
         $addressParams = array_merge($this->_params, $addressParams);
         //here we are setting up the billing contact - if different from the member they are already created
         // but they will get billing details assigned
         CRM_Contact_BAO_Contact::createProfileContact($addressParams, $fields, $this->_contributorContactID, NULL, NULL, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'));
     }
 }
Exemplo n.º 16
0
 /**
  * Form submission of petition signature.
  */
 public function postProcess()
 {
     $tag_name = Civi::settings()->get('tag_unconfirmed');
     if ($tag_name) {
         // Check if contact 'email confirmed' tag exists, else create one
         // This should be in the petition module initialise code to create a default tag for this
         $tag_params['name'] = $tag_name;
         $tag_params['version'] = 3;
         $tag = civicrm_api('tag', 'get', $tag_params);
         if ($tag['count'] == 0) {
             //create tag
             $tag_params['description'] = $tag_name;
             $tag_params['is_reserved'] = 1;
             $tag_params['used_for'] = 'civicrm_contact';
             $tag = civicrm_api('tag', 'create', $tag_params);
         }
         $this->_tagId = $tag['id'];
     }
     // export the field values to be used for saving the profile form
     $params = $this->controller->exportValues($this->_name);
     $session = CRM_Core_Session::singleton();
     // format params
     $params['last_modified_id'] = $session->get('userID');
     $params['last_modified_date'] = date('YmdHis');
     if ($this->_action & CRM_Core_Action::ADD) {
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     if (isset($this->_surveyId)) {
         $params['sid'] = $this->_surveyId;
     }
     if (isset($this->_contactId)) {
         $params['contactId'] = $this->_contactId;
     }
     // if logged in user, skip dedupe
     if ($this->_loggedIn) {
         $ids[0] = $this->_contactId;
     } else {
         // dupeCheck - check if contact record already exists
         // code modified from api/v2/Contact.php-function civicrm_contact_check_params()
         $params['contact_type'] = $this->_ctype;
         //TODO - current dedupe finds soft deleted contacts - adding param is_deleted not working
         // ignore soft deleted contacts
         //$params['is_deleted'] = 0;
         $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
         $dedupeParams['check_permission'] = '';
         //dupesByParams($params, $ctype, $level = 'Unsupervised', $except = array())
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type']);
     }
     $petition_params['id'] = $this->_surveyId;
     $petition = array();
     CRM_Campaign_BAO_Survey::retrieve($petition_params, $petition);
     switch (count($ids)) {
         case 0:
             //no matching contacts - create a new contact
             // Add a source for this new contact
             $params['source'] = ts('Petition Signature') . ' ' . $this->petition['title'];
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
             } else {
                 $this->_sendEmailMode = self::EMAIL_CONFIRM;
                 // Set status for signature activity to scheduled until email is verified
                 $params['statusId'] = 1;
             }
             break;
         case 1:
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             // dedupe matched single contact, check for 'unconfirmed' tag
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email directly, the user is known and validated
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
         default:
             // more than 1 matching contact
             // for time being, take the first matching contact (not sure that's the best strategy, but better than creating another duplicate)
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
     }
     $transaction = new CRM_Core_Transaction();
     // CRM-17029 - get the add_to_group_id from the _contactProfileFields array.
     // There's a much more elegant solution with
     // array_values($this->_contactProfileFields)[0] but it's PHP 5.4+ only.
     $slice = array_slice($this->_contactProfileFields, 0, 1);
     $firstField = array_shift($slice);
     $addToGroupID = isset($firstField['add_to_group_id']) ? $firstField['add_to_group_id'] : NULL;
     $this->_contactId = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_contactProfileFields, $this->_contactId, $addToGroupID, $this->_contactProfileId, $this->_ctype, TRUE);
     // get additional custom activity profile field data
     // to save with new signature activity record
     $surveyInfo = $this->bao->getSurveyInfo($this->_surveyId);
     $customActivityFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyInfo['activity_type_id']);
     $customActivityFields = CRM_Utils_Array::crmArrayMerge($customActivityFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, NULL, 'Activity');
     // create the signature activity record
     $params['contactId'] = $this->_contactId;
     $params['activity_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->petition);
     $result = $this->bao->createSignature($params);
     // send thank you or email verification emails
     // if logged in using Facebook connect and email on form matches Fb email,
     // no need for email confirmation, send thank you email
     if ($this->forceEmailConfirmed['flag'] && $this->forceEmailConfirmed['email'] == $params['email-Primary']) {
         $this->_sendEmailMode = self::EMAIL_THANK;
     }
     switch ($this->_sendEmailMode) {
         case self::EMAIL_THANK:
             // mark the signature activity as completed and set confirmed cookie
             $this->bao->confirmSignature($result->id, $this->_contactId, $this->_surveyId);
             break;
         case self::EMAIL_CONFIRM:
             // set 'Unconfirmed' tag for this new contact
             if ($tag_name) {
                 unset($tag_params);
                 $tag_params['contact_id'] = $this->_contactId;
                 $tag_params['tag_id'] = $this->_tagId;
                 $tag_params['version'] = 3;
                 $tag_value = civicrm_api('entity_tag', 'create', $tag_params);
             }
             break;
     }
     //send email
     $params['activityId'] = $result->id;
     $params['tagId'] = $this->_tagId;
     $transaction->commit();
     $this->bao->sendEmail($params, $this->_sendEmailMode);
     if ($result) {
         // call the hook before we redirect
         $this->postProcessHook();
         // set the template to thank you
         $url = CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=' . $this->_sendEmailMode . '&reset=1');
         CRM_Utils_System::redirect($url);
     }
 }
Exemplo n.º 17
0
 /**
  * Function to add on behalf of organization and it's location
  *
  * @param $behalfOrganization array  array of organization info
  * @param $contactID          int    individual contact id. One
  * who is doing the process of signup / contribution.
  *
  * @param $values             array  form values array
  * @param $params
  * @param null $fields
  *
  * @return void
  * @access public
  */
 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL)
 {
     $isCurrentEmployer = FALSE;
     $orgID = NULL;
     if (!empty($behalfOrganization['organization_id']) && !empty($behalfOrganization['org_option'])) {
         $orgID = $behalfOrganization['organization_id'];
         unset($behalfOrganization['organization_id']);
         $isCurrentEmployer = TRUE;
     }
     // formalities for creating / editing organization.
     $behalfOrganization['contact_type'] = 'Organization';
     // get the relationship type id
     $relType = new CRM_Contact_DAO_RelationshipType();
     $relType->name_a_b = 'Employee of';
     $relType->find(TRUE);
     $relTypeId = $relType->id;
     // keep relationship params ready
     $relParams['relationship_type_id'] = $relTypeId . '_a_b';
     $relParams['is_permission_a_b'] = 1;
     $relParams['is_active'] = 1;
     if (!$orgID) {
         // check if matching organization contact exists
         $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
         $dedupeParams['check_permission'] = FALSE;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
         // CRM-6243 says to pick the first org even if more than one match
         if (count($dupeIDs) >= 1) {
             $behalfOrganization['contact_id'] = $dupeIDs[0];
             // don't allow name edit
             unset($behalfOrganization['organization_name']);
         }
     } else {
         // if found permissioned related organization, allow location edit
         $behalfOrganization['contact_id'] = $orgID;
         // don't allow name edit
         unset($behalfOrganization['organization_name']);
     }
     // handling for image url
     if (!empty($behalfOrganization['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
     }
     // create organization, add location
     $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID, NULL, NULL, 'Organization');
     // create relationship
     $relParams['contact_check'][$orgID] = 1;
     $cid = array('contact' => $contactID);
     CRM_Contact_BAO_Relationship::create($relParams, $cid);
     // if multiple match - send a duplicate alert
     if ($dupeIDs && count($dupeIDs) > 1) {
         $values['onbehalf_dupe_alert'] = 1;
         // required for IPN
         $params['onbehalf_dupe_alert'] = 1;
     }
     // make sure organization-contact-id is considered for recording
     // contribution/membership etc..
     if ($contactID != $orgID) {
         // take a note of contact-id, so we can send the
         // receipt to individual contact as well.
         // required for mailing/template display ..etc
         $values['related_contact'] = $contactID;
         // required for IPN
         $params['related_contact'] = $contactID;
         //make this employee of relationship as current
         //employer / employee relationship,  CRM-3532
         if ($isCurrentEmployer && $orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id')) {
             $isCurrentEmployer = FALSE;
         }
         if (!$isCurrentEmployer && $orgID) {
             //build current employer params
             $currentEmpParams[$contactID] = $orgID;
             CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
         }
         // contribution / signup will be done using this
         // organization id.
         $contactID = $orgID;
     }
 }
Exemplo n.º 18
0
 function postProcess()
 {
     if (!array_key_exists('event', $this->_submitValues)) {
         return;
     }
     // XXX de facto primary key
     $email_to_contact_id = array();
     foreach ($this->_submitValues['event'] as $event_id => $participants) {
         foreach ($participants['participant'] as $participant_id => $fields) {
             if (array_key_exists($fields['email'], $email_to_contact_id)) {
                 $contact_id = $email_to_contact_id[$fields['email']];
             } else {
                 $contact_id = self::find_or_create_contact($this->getContactID(), $fields);
                 $email_to_contact_id[$fields['email']] = $contact_id;
             }
             $participant = $this->cart->get_event_in_cart_by_event_id($event_id)->get_participant_by_id($participant_id);
             if ($participant->contact_id && $contact_id != $participant->contact_id) {
                 $defaults = array();
                 $params = array('id' => $participant->contact_id);
                 $temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
                 foreach ($this->cart->get_subparticipants($participant) as $subparticipant) {
                     $subparticipant->contact_id = $contact_id;
                     $subparticipant->save();
                 }
                 $participant->contact_id = $contact_id;
                 $participant->save();
                 if ($temporary_contact->is_deleted) {
                     #ARGH a permissions check prevents us from using skipUndelete,
                     #so we potentially leave records pointing to this contact for now
                     #CRM_Contact_BAO_Contact::deleteContact($temporary_contact->id);
                     $temporary_contact->delete();
                 }
             }
             //TODO security check that participant ids are already in this cart
             $participant_params = array('id' => $participant_id, 'cart_id' => $this->cart->id, 'event_id' => $event_id, 'contact_id' => $contact_id, 'email' => $fields['email']);
             $participant = new CRM_Event_Cart_BAO_MerParticipant($participant_params);
             $participant->save();
             $this->cart->add_participant_to_cart($participant);
             if (array_key_exists('field', $this->_submitValues) && array_key_exists($participant_id, $this->_submitValues['field'])) {
                 $custom_fields = array_merge($participant->get_form()->get_participant_custom_data_fields());
                 CRM_Contact_BAO_Contact::createProfileContact($this->_submitValues['field'][$participant_id], $custom_fields, $contact_id);
             }
         }
     }
     $this->cart->save();
 }
Exemplo n.º 19
0
 /**
  * Process the form after the input has been submitted and validated.
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $ufGroupId = $this->get('ufGroupId');
     $notify = NULL;
     $inValidSubtypeCnt = 0;
     //send profile notification email if 'notify' field is set
     $notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $ufGroupId, 'notify');
     foreach ($params['field'] as $key => $value) {
         //CRM-5521
         //validate subtype before updating
         if (!empty($value['contact_sub_type']) && !CRM_Contact_BAO_ContactType::isAllowEdit($key)) {
             unset($value['contact_sub_type']);
             $inValidSubtypeCnt++;
         }
         $value['preserveDBName'] = $this->_preserveDefault;
         //parse street address, CRM-7768
         self::parseStreetAddress($value, $this);
         CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields, $key, NULL, $ufGroupId, NULL, TRUE);
         if ($notify) {
             $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($ufGroupId, $key, NULL);
             CRM_Core_BAO_UFGroup::commonSendMail($key, $values);
         }
     }
     CRM_Core_Session::setStatus('', ts("Updates Saved"), 'success');
     if ($inValidSubtypeCnt) {
         CRM_Core_Session::setStatus(ts('Contact Subtype field of 1 contact has not been updated.', array('plural' => 'Contact Subtype field of %count contacts has not been updated.', 'count' => $inValidSubtypeCnt)), ts('Invalid Subtype'));
     }
 }
Exemplo n.º 20
0
 /**
  * @param $submittedValues
  */
 public function processCreditCard($submittedValues)
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     // Get the required fields value only.
     $params = $this->_params = $submittedValues;
     //get the payment processor id as per mode.
     //@todo unclear relevance of mode - seems like a lot of duplicated params here!
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
         $this->assign('displayName', $this->userDisplayName);
     }
     //set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->_contributorEmail;
     // now set the values for the billing location.
     foreach ($this->_fields as $name => $dontCare) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     // Add all the additional payment params we need.
     $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
     // function to get correct amount level consistently. Remove setting of the amount level in
     // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
     // to cover all variants.
     $this->_params['amount_level'] = 0;
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency);
     if (!empty($this->_params['trxn_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['trxn_date'], $this->_params['trxn_date_time']);
     }
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     $this->assignBillingName($params);
     $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
     $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
     $date = CRM_Utils_Date::mysqlToIso($date);
     $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
     $this->assign('credit_card_exp_date', $date);
     $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     // at this point we've created a contact and stored its address etc
     // all the payment processors expect the name and address to be in the
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactId;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     // add some financial type details to the params list
     // if folks need to use it
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->_contributorEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     $result = NULL;
     if ($paymentParams['amount'] > 0.0) {
         try {
             // force a reget of the payment processor in case the form changed it, CRM-7179
             $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
             $result = $payment->doPayment($paymentParams);
         } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/payment/add', $urlParams));
         }
     }
     if ($result) {
         $this->_params = array_merge($this->_params, $result);
     }
     if (empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = $now;
     }
     $this->set('params', $this->_params);
     // set source if not set
     if (empty($this->_params['source'])) {
         $userID = $session->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // process the additional payment
     $participantId = NULL;
     if ($this->_component == 'event') {
         $participantId = $this->_id;
     }
     $trxnRecord = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
     if ($trxnRecord->id && !empty($this->_params['is_email_receipt'])) {
         $sendReceipt = $this->emailReceipt($this->_params);
     }
     if ($trxnRecord->id) {
         $statusMsg = ts('The payment record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
     }
 }
Exemplo n.º 21
0
 /**
  * Takes an associative array and creates a friend object.
  *
  * the function extract all the params it needs to initialize the create a
  * friend object. the params array could contain additional unused name/value
  * pairs
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Friend_BAO_Friend
  */
 public static function add(&$params)
 {
     $friend = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
     return $friend;
 }
Exemplo n.º 22
0
 /**
  * Based on the provided two contact_ids and a set of tables, move the belongings of the
  * other contact to the main one - be it Location / CustomFields or Contact .. related info.
  * A superset of moveContactBelongings() function.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @param $migrationInfo
  *
  * @return bool
  */
 public static function moveAllBelongings($mainId, $otherId, $migrationInfo)
 {
     if (empty($migrationInfo)) {
         return FALSE;
     }
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $relTables = CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = $tableOperations = array();
     foreach ($migrationInfo as $key => $value) {
         if ($value == $qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) || substr($key, 0, 12) == 'move_custom_') && $value != NULL) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
             if (array_key_exists('operation', $migrationInfo)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $migrationInfo['operation'])) {
                         $tableOperations[$table] = $migrationInfo['operation'][$key];
                     }
                 }
             }
         }
     }
     // **** Do location related migration:
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : NULL;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : NULL;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if (array_key_exists($name, $locComponent)) {
                     $idKey = $locTypeId;
                 }
                 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
                     $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
                 }
                 if (!$otherBlockId) {
                     continue;
                 }
                 // for the block which belongs to other-contact, link the contact to main-contact
                 $otherBlockDAO = new $daoName();
                 $otherBlockDAO->id = $otherBlockId;
                 $otherBlockDAO->contact_id = $mainId;
                 $otherBlockDAO->location_type_id = $locTypeId;
                 // if main contact already has primary & billing, set the flags to 0.
                 if ($primaryDAOId) {
                     $otherBlockDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $otherBlockDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block which belongs to main-contact.
                 if (isset($mainBlockId) && $mainBlockId && $operation == 2) {
                     $deleteDAO = new $daoName();
                     $deleteDAO->id = $mainBlockId;
                     $deleteDAO->find(TRUE);
                     // if we about to delete a primary / billing block, set the flags for new block
                     // that we going to assign to main-contact
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $otherBlockDAO->update();
                 $otherBlockDAO->free();
             }
         }
     }
     // **** Do tables related migrations
     if (!empty($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
         unset($moveTables, $tableOperations);
     }
     // **** Do contact related migrations
     CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
     // fix custom fields so they're edible by createProfileContact()
     static $treeCache = array();
     if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
         $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], CRM_Core_DAO::$_nullObject, NULL, -1);
     }
     $cgTree =& $treeCache[$migrationInfo['main_details']['contact_type']];
     $cFields = array();
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             if (empty($cFields[$fid])) {
                 continue;
             }
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     $customParams = array('entityID' => $mainId, $key => TRUE);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (!empty($customfieldValues[$key])) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPARATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $mergeValue) . CRM_Core_DAO::VALUE_SEPARATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } elseif (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                         //we require submitted values should be in array format
                         if ($value) {
                             $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             //hack to remove null values from array.
                             $mergeValue = array();
                             foreach ($mergeValueArray as $k => $v) {
                                 if ($v != '') {
                                     $mergeValue[] = $v;
                                 }
                             }
                             $submitted[$key] = $mergeValue;
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // **** Do file custom fields related migrations
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
     // like, delete a file...
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
         $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         if (!empty($fileIds[$mainId])) {
             CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
         }
         // move the other contact's file to main contact
         //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
         if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
             $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
         } else {
             $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         if (CRM_Core_DAO::singleValueQuery("\n        SELECT id\n        FROM civicrm_entity_file\n        WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")) {
             $sql = "\n          UPDATE civicrm_entity_file\n          SET entity_id = {$mainId}\n          WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
         } else {
             $sql = "\n          INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )\n          VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     // special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         $viewOnlyCustomFields['entityID'] = $mainId;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     // **** Delete other contact & update prev-next caching
     $otherParams = array('contact_id' => $otherId, 'id' => $otherId, 'version' => 3);
     if (CRM_Core_Permission::check('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (!empty($submitted['external_identifier'])) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
             CRM_Core_DAO::executeQuery($query);
         }
         civicrm_api('contact', 'delete', $otherParams);
         CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
     }
     // FIXME: else part
     /*         else { */
     /*             CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
     /*         } */
     // CRM-15681 merge sub_types
     if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
         if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
             $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
         } else {
             $submitted['contact_sub_type'] = $other_sub_types;
         }
     }
     // **** Update contact related info for the main contact
     if (!empty($submitted)) {
         $submitted['contact_id'] = $mainId;
         //update current employer field
         if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
             if (!CRM_Utils_System::isNull($currentEmloyerId)) {
                 $submitted['current_employer'] = $submitted['current_employer_id'];
             } else {
                 $submitted['current_employer'] = '';
             }
             unset($submitted['current_employer_id']);
         }
         //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
         if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
             $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
         }
         if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
             $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
         }
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
         unset($submitted);
     }
     CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
     return TRUE;
 }
Exemplo n.º 23
0
 /**
  * Test case for createProfileContact.
  */
 public function testCreateProfileContact()
 {
     $fields = CRM_Contact_BAO_Contact::exportableFields('Individual');
     //current employer field for individual
     $fields['organization_name'] = array('name' => 'organization_name', 'where' => 'civicrm_organization.organization_name', 'title' => 'Current Employer');
     //get the common params
     $contactParams = $this->contactParams();
     $unsetParams = array('location', 'privacy');
     foreach ($unsetParams as $param) {
         unset($contactParams[$param]);
     }
     $profileParams = array('organization_name' => 'Yahoo', 'gender_id' => '2', 'prefix_id' => '3', 'suffix_id' => '2', 'city-Primary' => 'Newark', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '18.219023', 'geo_code_2-Primary' => '-105.00973', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.smith', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '303443689', 'phone-Primary-2' => '9833910234', 'postal_code-Primary' => '01903', 'postal_code_suffix-Primary' => '12345', 'state_province-Primary' => '1029', 'street_address-Primary' => 'Saint Helier St', 'supplemental_address_1-Primary' => 'Hallmark Ct', 'supplemental_address_2-Primary' => 'Jersey Village', 'user_unique_id' => '123456789', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('3' => '1', '4' => '1', '1' => '1'));
     $createParams = array_merge($contactParams, $profileParams);
     //create the contact using create profile contact.
     $contactId = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, NULL, NULL, NULL, NULL, TRUE);
     //get the parameters to compare.
     $params = $this->contactParams();
     //check the values in DB.
     foreach ($params as $key => $val) {
         if (!is_array($params[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $params[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($params['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $profileParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $profileParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $params['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $params['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $params['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $profileParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $profileParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $profileParams), 'city' => CRM_Utils_Array::value('city-Primary', $profileParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $profileParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $profileParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $profileParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $profileParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $profileParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($profileParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($profileParams['tag'], $tagIds);
     //update Contact mode
     $updateCParams = array('first_name' => 'john', 'last_name' => 'doe', 'contact_type' => 'Individual', 'middle_name' => 'abc', 'prefix_id' => 2, 'suffix_id' => 3, 'nick_name' => 'Nick Name Updated', 'job_title' => 'software Developer', 'gender_id' => 1, 'is_deceased' => 1, 'website' => array(1 => array('website_type_id' => 1, 'url' => 'http://civicrmUpdate.org')), 'contact_source' => 'test contact', 'external_identifier' => 111222333, 'preferred_mail_format' => 'Both', 'is_opt_out' => 0, 'legal_identifier' => '123123123123', 'image_URL' => 'http://imageupdate.com', 'deceased_date' => '1981-10-10', 'birth_date' => '1951-11-11', 'privacy' => array('do_not_phone' => 1, 'do_not_email' => 1), 'preferred_communication_method' => array('1' => 0, '2' => 1, '3' => 0, '4' => 1, '5' => 0));
     $updatePfParams = array('organization_name' => 'Google', 'city-Primary' => 'Mumbai', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '31.694842', 'geo_code_2-Primary' => '-106.29998', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.doe', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '02115245336', 'phone-Primary-2' => '9766323895', 'postal_code-Primary' => '12345', 'postal_code_suffix-Primary' => '123', 'state_province-Primary' => '1004', 'street_address-Primary' => 'Oberoi Garden', 'supplemental_address_1-Primary' => 'A-wing:3037', 'supplemental_address_2-Primary' => 'Andhery', 'user_unique_id' => '1122334455', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('2' => '1', '5' => '1'));
     $createParams = array_merge($updateCParams, $updatePfParams);
     //create the contact using create profile contact.
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, $contactId, NULL, NULL, NULL, TRUE);
     //check the contact ids
     $this->assertEquals($contactId, $contactID, 'check for Contact ids');
     //check the values in DB.
     foreach ($updateCParams as $key => $val) {
         if (!is_array($updateCParams[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $updateCParams[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($updateCParams['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $updatePfParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $updatePfParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $updateCParams['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $updateCParams['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $updateCParams['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $updatePfParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $updatePfParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $updatePfParams), 'city' => CRM_Utils_Array::value('city-Primary', $updatePfParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $updatePfParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $updatePfParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $updatePfParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $updatePfParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $updatePfParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($updatePfParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($updatePfParams['tag'], $tagIds);
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
 }
Exemplo n.º 24
0
 /**
  * Process credit card payment.
  *
  * @param array $submittedValues
  * @param array $lineItem
  *
  * @throws CRM_Core_Exception
  */
 protected function processCreditCard($submittedValues, $lineItem)
 {
     $sendReceipt = $contribution = FALSE;
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     $isTest = $this->_mode == 'test' ? 1 : 0;
     // CRM-12680 set $_lineItem if its not set
     if (empty($this->_lineItem) && !empty($lineItem)) {
         $this->_lineItem = $lineItem;
     }
     //Get the require fields value only.
     $params = $this->_params = $submittedValues;
     $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
     // Get the payment processor id as per mode.
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // Set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->userEmail;
     // now set the values for the billing location.
     foreach (array_keys($this->_fields) as $name) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
     // add all the additional payment params we need
     if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     }
     $legacyCreditCardExpiryCheck = FALSE;
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
         $legacyCreditCardExpiryCheck = TRUE;
     }
     if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     $this->_params['amount_level'] = 0;
     $this->_params['description'] = ts('Office Credit Card contribution');
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency);
     $this->_params['payment_action'] = 'Sale';
     if (!empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
     }
     if (!empty($params['soft_credit_to'])) {
         $this->_params['soft_credit_to'] = $params['soft_credit_to'];
         $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
     }
     $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
     $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
     $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     // At this point we've created a contact and stored its address etc
     // all the payment processors expect the name and address to be in the
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactID;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     $contributionType = new CRM_Financial_DAO_FinancialType();
     $contributionType->id = $params['financial_type_id'];
     // Add some financial type details to the params list
     // if folks need to use it.
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->userEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     // For recurring contribution, create Contribution Record first.
     // Contribution ID, Recurring ID and Contact ID needed
     // When we get a callback from the payment processor, CRM-7115
     if (!empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem);
         $paymentParams['contributionID'] = $contribution->id;
         $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
     }
     $result = array();
     if ($paymentParams['amount'] > 0.0) {
         // force a re-get of the payment processor in case the form changed it, CRM-7179
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
         try {
             $result = $payment->doPayment($paymentParams, 'contribute');
         } catch (CRM_Core_Exception $e) {
             $message = ts("Payment Processor Error message") . $e->getMessage();
             $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
             // Set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
         }
     }
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     if (!empty($this->_params['is_email_receipt'])) {
         $this->_params['receipt_date'] = $now;
     } else {
         $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
     }
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', $this->_params['receive_date']);
     // Result has all the stuff we need
     // lets archive it to a financial transaction
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', TRUE);
         $this->set('is_deductible', TRUE);
     }
     // Set source if not set
     if (empty($this->_params['source'])) {
         $userID = CRM_Core_Session::singleton()->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // Build custom data getFields array
     $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
     if (empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem);
     }
     // Send receipt mail.
     if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
         $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $this->_params['contact_id'] = $this->_contactID;
         $this->_params['contribution_id'] = $contribution->id;
         $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
     }
     //process the note
     if ($contribution->id && isset($params['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
     }
     //process premium
     if ($contribution->id && isset($params['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
     }
     //update pledge payment status.
     if ($this->_ppID && $contribution->id) {
         // Store contribution id in payment record.
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
     }
     if ($contribution->id) {
         $statusMsg = ts('The contribution record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     }
 }
Exemplo n.º 25
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Exemplo n.º 26
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
Exemplo n.º 27
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::del($this->_id);
         return;
     }
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $lineItems = NULL;
     if (!empty($this->_lineItem)) {
         $lineItems = $this->_lineItem;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->convertDateFieldsToMySQL($formValues);
     $params = $softParams = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($this->_params['auto_renew'])) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $termsByType = array();
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
             $params['tax_amount'] = $this->_params['tax_amount'];
         }
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
         if (!empty($lineItem[$priceSetId])) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 if (!empty($li['membership_type_id'])) {
                     if (!empty($li['membership_num_terms'])) {
                         $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                     }
                 }
                 ///CRM-11529 for quick config backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if ($isQuickConfig && $submittedFinancialType) {
                     $li['financial_type_id'] = $submittedFinancialType;
                 }
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId && !$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         }
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution');
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['financial_type_id'] = $params['financial_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             }
         }
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, TRUE, FALSE, $isTest, $lineItems);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (!empty($paymentParams['contributionID'])) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (!empty($paymentParams['contributionRecurID'])) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         // if the payment processor returns a contribution_status_id -> use it!
         if (isset($result['contribution_status_id'])) {
             $result['payment_status_id'] = $result['contribution_status_id'];
         }
         if (isset($result['payment_status_id'])) {
             // CRM-16737 $result['contribution_status_id'] is deprecated in favour
             // of payment_status_id as the payment processor only knows whether the payment is complete
             // not whether payment completes the contribution
             $params['contribution_status_id'] = $result['payment_status_id'];
         } else {
             $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
         }
         if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($this->_params['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($this->_params['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) {
                 // CRM-16993 we have a situation where line items have already been created.
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && empty($params['is_recur'])) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && !empty($mailSend)) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
Exemplo n.º 28
0
 /**
  * Process the user submitted custom data values.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     //if the delete record button is clicked
     if ($this->_deleteButtonName) {
         if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
             $filterParams['id'] = $this->_customGroupId;
             $returnProperties = array('is_multiple', 'table_name');
             CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
             if (!empty($returnValues['is_multiple'])) {
                 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
                     $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
                     $sqlParams = array(1 => array($this->_recordId, 'Integer'), 2 => array($this->_id, 'Integer'));
                     CRM_Core_DAO::executeQuery($sql, $sqlParams);
                     CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
                 }
             }
             return;
         }
     }
     CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     $greetingTypes = array('addressee' => 'addressee_id', 'email_greeting' => 'email_greeting_id', 'postal_greeting' => 'postal_greeting_id');
     $details = array();
     if ($this->_id) {
         $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id, $greetingTypes);
         $details = $contactDetails[0][$this->_id];
     }
     if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) || CRM_Utils_Array::value('postal_greeting_id', $details))) {
         $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
         //Though Profile type is contact we need
         //Individual/Household/Organization for setting Greetings.
         if ($profileType == 'Contact') {
             $profileType = 'Individual';
             //if we editing Household/Organization.
             if ($this->_id) {
                 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
             }
         }
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         foreach ($greetingTypes as $key => $value) {
             if (!array_key_exists($key, $params)) {
                 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     //used to send subscribe mail to the group which user want.
     //if the profile double option in is enabled
     $mailingType = array();
     $result = NULL;
     foreach ($params as $name => $values) {
         if (substr($name, 0, 6) == 'email-') {
             $result['email'] = $values;
         }
     }
     //array of group id, subscribed by contact
     $contactGroup = array();
     if (!empty($params['group']) && CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
         $groupSubscribed = array();
         if (!empty($result['email'])) {
             if ($this->_id) {
                 $contactGroups = new CRM_Contact_DAO_GroupContact();
                 $contactGroups->contact_id = $this->_id;
                 $contactGroups->status = 'Added';
                 $contactGroups->find();
                 $contactGroup = array();
                 while ($contactGroups->fetch()) {
                     $contactGroup[] = $contactGroups->group_id;
                     $groupSubscribed[$contactGroups->group_id] = 1;
                 }
             }
             foreach ($params['group'] as $key => $val) {
                 if (!$val) {
                     unset($params['group'][$key]);
                     continue;
                 }
                 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $key, 'group_type', 'id');
                 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($groupTypes, 1, -1));
                 //filter group of mailing type and unset it from params
                 if (in_array(2, $groupType)) {
                     //if group is already subscribed , ignore it
                     $groupExist = CRM_Utils_Array::key($key, $contactGroup);
                     if (!isset($groupExist)) {
                         $mailingType[] = $key;
                         unset($params['group'][$key]);
                     }
                 }
             }
         }
     }
     $addToGroupId = CRM_Utils_Array::value('add_to_group_id', $this->_ufGroup);
     if (!empty($addToGroupId)) {
         //run same check whether group is a mailing list
         $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $addToGroupId, 'group_type', 'id');
         $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($groupTypes, 1, -1));
         //filter group of mailing type and unset it from params
         if (in_array(2, $groupType) && !empty($result['email']) && CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()) {
             if (!count($contactGroup)) {
                 //array of group id, subscribed by contact
                 $contactGroup = array();
                 if ($this->_id) {
                     $contactGroups = new CRM_Contact_DAO_GroupContact();
                     $contactGroups->contact_id = $this->_id;
                     $contactGroups->status = 'Added';
                     $contactGroups->find();
                     $contactGroup = array();
                     while ($contactGroups->fetch()) {
                         $contactGroup[] = $contactGroups->group_id;
                         $groupSubscribed[$contactGroups->group_id] = 1;
                     }
                 }
             }
             //if group is already subscribed , ignore it
             $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
             if (!isset($groupExist)) {
                 $mailingType[] = $addToGroupId;
                 $addToGroupId = NULL;
             }
         } else {
             // since we are directly adding contact to group lets unset it from mailing
             if ($key = array_search($addToGroupId, $mailingType)) {
                 unset($mailingType[$key]);
             }
         }
     }
     if ($this->_grid) {
         $params['group'] = $groupSubscribed;
     }
     // commenting below code, since we potentially
     // triggered maximum name field formatting cases during CRM-4430.
     // CRM-4343
     // $params['preserveDBName'] = true;
     $profileFields = $this->_fields;
     if ($this->_mode & self::MODE_EDIT && $this->_activityId && $this->_isContactActivityProfile) {
         $profileFields = $activityParams = array();
         foreach ($this->_fields as $fieldName => $field) {
             if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
                 if (isset($params[$fieldName])) {
                     $activityParams[$fieldName] = $params[$fieldName];
                 }
                 if (isset($params['activity_date_time'])) {
                     $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
                 }
                 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
                     $activityParams[$fieldName] = $params["{$fieldName}_id"];
                 }
             } else {
                 $profileFields[$fieldName] = $field;
             }
         }
         if (!empty($activityParams)) {
             $activityParams['version'] = 3;
             $activityParams['id'] = $this->_activityId;
             $activityParams['skipRecentView'] = TRUE;
             civicrm_api('Activity', 'create', $activityParams);
         }
     }
     if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
         $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
     }
     $this->_id = CRM_Contact_BAO_Contact::createProfileContact($params, $profileFields, $this->_id, $addToGroupId, $this->_gid, $this->_ctype, TRUE);
     //mailing type group
     if (!empty($mailingType)) {
         // we send in the contactID so we match the same groups and are exact, rather than relying on email
         // CRM-8710
         CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
     }
     $ufGroups = array();
     if ($this->_gid) {
         $ufGroups[$this->_gid] = 1;
     } elseif ($this->_mode == self::MODE_REGISTER) {
         $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
     }
     foreach ($ufGroups as $gId => $val) {
         if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
             $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
             CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
         }
     }
     //create CMS user (if CMS user option is selected in profile)
     if (!empty($params['cms_create_account']) && $this->_mode == self::MODE_CREATE) {
         $params['contactID'] = $this->_id;
         if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
             CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
             CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
             $transaction->rollback();
             return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create', 'reset=1&gid=' . $this->_gid));
         }
     }
     $transaction->commit();
 }
Exemplo n.º 29
0
 /**
  * update contact information
  *
  * @param array $value associated array of submitted values
  *
  * @access public
  *
  * @return void
  */
 private function updateContactInfo(&$value)
 {
     $value['preserveDBName'] = $this->_preserveDefault;
     //parse street address, CRM-7768
     CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
     CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields, $value['contact_id']);
 }
Exemplo n.º 30
0
 /**
  * Create honor-contact method
  */
 public function testcreateAndGetHonorContact()
 {
     $firstName = 'John_' . substr(sha1(rand()), 0, 7);
     $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
     $email = "{$firstName}.{$lastName}@example.com";
     //Get profile id of name honoree_individual used to create profileContact
     $honoreeProfileId = NULL;
     $ufGroupDAO = new CRM_Core_DAO_UFGroup();
     $ufGroupDAO->name = 'honoree_individual';
     if ($ufGroupDAO->find(TRUE)) {
         $honoreeProfileId = $ufGroupDAO->id;
     }
     $params = array('prefix_id' => 3, 'first_name' => $firstName, 'last_name' => $lastName, 'email-1' => $email);
     $softParam = array('soft_credit_type_id' => 1);
     $honoreeContactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray, NULL, NULL, $honoreeProfileId);
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName, 'Database check for created honor contact record.');
     //create contribution on behalf of honary.
     $contactId = Contact::createIndividual();
     $softParam['contact_id'] = $honoreeContactId;
     $ids = array('contribution' => NULL);
     $param = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 4, 'contribution_status_id' => 1, 'receive_date' => date('Ymd'), 'total_amount' => 66);
     $contribution = CRM_Contribute_BAO_Contribution::create($param, $ids);
     $id = $contribution->id;
     $softParam['contribution_id'] = $id;
     $softParam['currency'] = $contribution->currency;
     $softParam['amount'] = $contribution->total_amount;
     //Create Soft Contribution for honoree contact
     CRM_Contribute_BAO_ContributionSoft::add($softParam);
     $this->assertDBCompareValue('CRM_Contribute_DAO_ContributionSoft', $id, 'contact_id', 'contribution_id', $honoreeContactId, 'Check DB for honor contact of the contribution');
     //get honorary information
     $getHonorContact = CRM_Contribute_BAO_Contribution::getHonorContacts($honoreeContactId);
     $this->assertEquals(array($id => array('honor_type' => 'In Honor of', 'honorId' => $id, 'display_name' => 'John Doe', 'type' => 'Event Fee', 'type_id' => '4', 'amount' => '$ 66.00', 'source' => NULL, 'receive_date' => date('Y-m-d 00:00:00'), 'contribution_status' => 'Completed')), $getHonorContact);
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName, 'Database check for created honor contact record.');
     //get annual contribution information
     $annual = CRM_Contribute_BAO_Contribution::annual($contactId);
     $config = CRM_Core_Config::singleton();
     $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency, 'symbol', 'name');
     $this->assertDBCompareValue('CRM_Contribute_DAO_Contribution', $id, 'total_amount', 'id', ltrim($annual[2], $currencySymbol), 'Check DB for total amount of the contribution');
     //Delete honor contact
     Contact::delete($honoreeContactId);
     //Delete Contribution record
     $this->contributionDelete($contribution->id);
     //Delete contributor contact
     Contact::delete($contactId);
 }