Example #1
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;
}
 public function testDupesByParams()
 {
     // make dupe checks based on based on following contact sets:
     // FIRST - LAST - EMAIL
     // ---------------------------------
     // robin  - hood - robin@example.com
     // robin  - hood - hood@example.com
     // robin  - dale - robin@example.com
     // little - dale - dale@example.com
     // will   - dale - dale@example.com
     // will   - dale - will@example.com
     // will   - dale - will@example.com
     // contact data set
     // FIXME: move create params to separate function
     $params = array(array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'robin', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'little', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'));
     $count = 1;
     // TODO: This is not an API test!!
     foreach ($params as $param) {
         $param['version'] = 3;
         $contact = civicrm_api('contact', 'create', $param);
         $params = array('contact_id' => $contact['id'], 'street_address' => 'Ambachtstraat 23', 'location_type_id' => 1, 'version' => 3);
         $result = civicrm_api('address', 'create', $params);
         $contactIds[$count++] = $contact['id'];
     }
     // verify that all contacts have been created separately
     $this->assertEquals(count($contactIds), 7, 'Check for number of contacts.');
     $dao = new CRM_Dedupe_DAO_RuleGroup();
     $dao->contact_type = 'Individual';
     $dao->used = 'General';
     $dao->is_default = 1;
     $dao->find(TRUE);
     $fields = array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'street_address' => 'Ambachtstraat 23');
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'General');
     // Check with default Individual-General rule
     $this->assertEquals(count($ids), 2, 'Check Individual-General rule for dupesByParams().');
     // delete all created contacts
     foreach ($contactIds as $contactId) {
         Contact::delete($contactId);
     }
 }
Example #3
0
 /**
  * Function to that checks for duplicate contacts
  *  
  *  @param array  $fields      fields array which are submitted
  *  @param array  $error       error message array
  *  @param int    $contactID   contact id
  *  @param string $contactType contact type  
  */
 static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType)
 {
     // if this is a forced save, ignore find duplicate rule
     if (!CRM_Utils_Array::value('_qf_Contact_upload_duplicate', $fields)) {
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $contactType);
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Fuzzy', array($contactID));
         if ($ids) {
             $viewUrls = array();
             $editUrls = array();
             require_once 'CRM/Contact/BAO/Contact/Utils.php';
             list($viewUrls, $editUrls, $mergeUrl) = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, true, true, $contactID);
             $viewUrl = implode(', ', $viewUrls);
             $editUrl = implode(', ', $editUrls);
             $errors['_qf_default'] = ts('One matching contact was found.', array('count' => count($editUrls), 'plural' => '%count matching contacts were found.'));
             $errors['_qf_default'] .= '<br />';
             $errors['_qf_default'] .= ts('If you need to verify if this is the same contact, click here - %1 - to VIEW the existing contact in a new tab.', array(1 => $viewUrl, 'count' => count($viewUrls), 'plural' => 'If you need to verify whether one of these is the same contact, click here - %1 - to VIEW the existing contact in a new tab.'));
             $errors['_qf_default'] .= '<br />';
             $errors['_qf_default'] .= ts('If you know the record you are creating is a duplicate, click here - %1 - to EDIT the original record instead.', array(1 => $editUrl));
             $errors['_qf_default'] .= '<br />';
             //allow to merge with matching contact, CRM-3160
             if (!empty($mergeUrl)) {
                 $errors['_qf_default'] .= ts('If you know the record you are editing is a duplicate, click here - %1 - to MERGE with the existing record instead.', array(1 => $mergeUrl));
                 $errors['_qf_default'] .= '<br />';
             }
             $errors['_qf_default'] .= ts('If you are sure this is NOT a duplicate, click the &quot;Save Matching Contact&quot; button (this button is located at the bottom of the Contact Details section below).');
             // let smarty know that there are duplicates
             $template =& CRM_Core_Smarty::singleton();
             $template->assign('isDuplicate', 1);
         } else {
             if (CRM_Utils_Array::value('_qf_Contact_refresh_dedupe', $fields)) {
                 // add a session message for no matching contacts
                 CRM_Core_Session::setStatus('No matching contact found.');
             }
         }
     }
 }
Example #4
0
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  *   The uploaded files if any.
  * @param CRM_Core_Form $self
  *
  * @return bool|array
  *   true if no errors, else array of errors
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self->_values);
     if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) {
         $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
     }
     if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) {
         $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE;
         $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE);
         $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
         $unallowedOrgs = array();
         foreach (array_keys($lifeMember) as $memTypeId) {
             $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
         }
     }
     //check for atleast one pricefields should be selected
     if (!empty($fields['priceSetId']) && empty($self->_ccid)) {
         $priceField = new CRM_Price_DAO_PriceField();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->orderBy('weight');
         $priceField->find();
         $check = array();
         $membershipIsActive = TRUE;
         $previousId = $otherAmount = FALSE;
         while ($priceField->fetch()) {
             if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
                 $previousId = $priceField->id;
                 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
                     $membershipIsActive = FALSE;
                 }
             }
             if ($priceField->name == 'other_amount') {
                 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) {
                     $otherAmount = $priceField->id;
                 } elseif (!empty($fields["price_{$priceField->id}"])) {
                     $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
                     $min = CRM_Utils_Array::value('min_amount', $self->_values);
                     $max = CRM_Utils_Array::value('max_amount', $self->_values);
                     if ($min && $otherAmountVal < $min) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min));
                     }
                     if ($max && $otherAmountVal > $max) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                     }
                 }
             }
             if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) {
                 $check[] = $priceField->id;
             }
         }
         $currentMemberships = NULL;
         if ($membershipIsActive) {
             $is_test = $self->_mode != 'live' ? 1 : 0;
             $memContactID = $self->_membershipContactID;
             // For anonymous user check using dedupe rule
             // if user has Cancelled Membership
             if (!$memContactID) {
                 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
                 $dedupeParams['check_permission'] = FALSE;
                 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
                 // if we find more than one contact, use the first one
                 $memContactID = CRM_Utils_Array::value(0, $ids);
             }
             $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test);
             $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
             foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
                 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
                     if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) {
                         if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) {
                             $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
                         }
                     } else {
                         if (is_array($fields['price_' . $fieldKey])) {
                             foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
                                 if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) {
                                     $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // CRM-12233
         if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) {
             $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
             foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
                 // if 'No thank you' membership is selected then set $membershipFieldId
                 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
                     $membershipFieldId = $fieldKey;
                 } elseif ($membershipFieldId) {
                     if ($fieldValue['name'] == 'other_amount') {
                         $otherFieldId = $fieldKey;
                     } elseif ($fieldValue['name'] == 'contribution_amount') {
                         $contributionFieldId = $fieldKey;
                     }
                     if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
                         $errorKey = $fieldKey;
                     }
                 }
             }
             // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
             if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
                 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
             }
         }
         if (empty($check) && empty($self->_ccid)) {
             if ($self->_useForMember == 1 && $membershipIsActive) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         if ($otherAmount && !empty($check)) {
             $errors["price_{$otherAmount}"] = ts('Amount is required field.');
         }
         if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) {
                     if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
                         // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
                         // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (!empty($value['options'])) {
                         foreach ($value['options'] as $val) {
                             if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             if (!empty($lifeMember)) {
                 foreach ($priceFieldIDS as $priceFieldId) {
                     if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) {
                         $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
                         break;
                     }
                 }
             }
             if (!empty($priceFieldIDS)) {
                 $ids = implode(',', $priceFieldIDS);
                 $priceFieldIDS['id'] = $fields['priceSetId'];
                 $self->set('memberPriceFieldIDS', $priceFieldIDS);
                 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
                 foreach ($count as $id => $occurrence) {
                     if ($occurrence > 1) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                     }
                 }
             }
             if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(TRUE);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
             CRM_Core_Session::setStatus($errors['selectProduct']);
         }
     }
     //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
     CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
     if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) {
         $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (!empty($self->_values['pledge_block_id'])) {
         //validation for pledge payment.
         if (!empty($self->_values['pledge_id'])) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } elseif (!empty($fields['is_pledge'])) {
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
                 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
             } else {
                 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
                     $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                 } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) {
                     $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                 } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 0) {
                     $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                 }
             }
             //validation for Pledge Frequency Interval.
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
                 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
             } else {
                 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
                     $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                 } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) {
                     $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                 }
             }
         }
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we don't need to validate payment related fields or profiles.
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) {
         $errors['payment_processor_id'] = ts('Payment Method is a required field.');
     } else {
         CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing');
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
                 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #5
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;
     }
 }
Example #6
0
 /**
  * Create Current employer relationship for a individual.
  *
  * @param int $contactID
  *   Contact id of the individual.
  * @param $organization
  *   (id or name).
  * @param int $previousEmployerID
  * @param bool $newContact
  *
  */
 public static function createCurrentEmployerRelationship($contactID, $organization, $previousEmployerID = NULL, $newContact = FALSE)
 {
     //if organization name is passed. CRM-15368,CRM-15547
     if ($organization && !is_numeric($organization)) {
         $organizationParams['organization_name'] = $organization;
         $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
         $dedupeParams['check_permission'] = FALSE;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
         if (is_array($dupeIDs) && !empty($dupeIDs)) {
             // we should create relationship only w/ first org CRM-4193
             foreach ($dupeIDs as $orgId) {
                 $organization = $orgId;
                 break;
             }
         } else {
             //create new organization
             $newOrg = array('contact_type' => 'Organization', 'organization_name' => $organization);
             $org = CRM_Contact_BAO_Contact::create($newOrg);
             $organization = $org->id;
         }
     }
     if ($organization && is_numeric($organization)) {
         $cid = array('contact' => $contactID);
         // get the relationship type id of "Employee of"
         $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
         if (!$relTypeId) {
             CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
         }
         // create employee of relationship
         $relationshipParams = array('is_active' => TRUE, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($organization => TRUE));
         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::legacyCreateMultiple($relationshipParams, $cid);
         // In case we change employer, clean previous employer related records.
         if (!$previousEmployerID && !$newContact) {
             $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
         }
         if ($previousEmployerID && $previousEmployerID != $organization) {
             self::clearCurrentEmployer($contactID, $previousEmployerID);
         }
         // set current employer
         self::setCurrentEmployer(array($contactID => $organization));
         $relationshipParams['relationship_ids'] = $relationshipIds;
         // Handle related memberships. CRM-3792
         self::currentEmployerRelatedMembership($contactID, $organization, $relationshipParams, $duplicate, $previousEmployerID);
     }
 }
function _woocommerce_civicrm_add_update_contact($cid, $order)
{
    if (!civicrm_wp_initialize()) {
        return;
    }
    $action = 'create';
    //try {
    $contact = array();
    if ($cid != 0) {
        try {
            $params = array('contact_id' => $cid, 'return' => array('id', 'source', 'first_name', 'last_name'));
            $contact = civicrm_api3('contact', 'getsingle', $params);
        } catch (CiviCRM_Exception $e) {
            CRM_Core_Error::debug_log_message('Not able to find contact');
            return FALSE;
        }
    }
    // Create contact
    // Prepare array to update contact via civi API.
    $email = '';
    $fname = '';
    $lname = '';
    $cid = '';
    if (!empty($order->shipping_email)) {
        $email = $order->shipping_email;
        $fname = $order->shipping_first_name;
        $lname = $order->shipping_last_name;
    } else {
        $email = $order->billing_email;
        $fname = $order->billing_first_name;
        $lname = $order->billing_last_name;
    }
    // Try to get contact Id using dedupe
    $contact['first_name'] = $fname;
    $contact['last_name'] = $lname;
    $contact['email'] = $email;
    $dedupeParams = CRM_Dedupe_Finder::formatParams($contact, 'Individual');
    $dedupeParams['check_permission'] = FALSE;
    $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised');
    if ($ids) {
        $cid = $ids['0'];
        $action = 'update';
    }
    $contact['sort_name'] = "{$lname}, {$fname}";
    $contact['display_name'] = "{$fname} {$lname}";
    if (!$cid) {
        $contact['contact_type'] = 'Individual';
    }
    if (isset($contact['contact_subtype'])) {
        unset($contact['contact_subtype']);
    }
    if (empty($contact['source'])) {
        $contact['source'] = 'Woocommerce purchase';
    }
    //CRM_Core_Error::debug_var('Contact', $contact);
    // Create contact or update existing contact.
    //if ($contact_status == 'new' && !$contact_info['values'][$cid]['first_name'] && !$contact_info['values'][$cid]['last_name']) {
    try {
        $result = civicrm_api3('contact', 'create', $contact);
        $cid = $result['id'];
        $name = trim($contact['display_name']);
        $name = !empty($name) ? $contact['display_name'] : $cid;
        $admin_url = get_admin_url();
        $contact_url = "<a href='" . $admin_url . "admin.php?page=CiviCRM&q=civicrm/contact/view&reset=1&cid=" . $cid . "'>View</a>";
        // Add order note
        if ($action == 'update') {
            $note = 'CiviCRM Contact Updated - ' . $contact_url;
        } else {
            $note = 'Created new CiviCRM Contact - ' . $contact_url;
        }
        $order->add_order_note($note);
    } catch (Exception $e) {
        CRM_Core_Error::debug_log_message('Not able to create/update contact');
        return FALSE;
    }
    //}
    //$loc_types = $GLOBALS["WooCommerceCiviCRMLocationTypes"];
    $woocommerce_billing = $loc_types['woocommerce-billing'];
    $woocommerce_shipping = $loc_types['woocommerce-shipping'];
    $civicrm_billing = get_option('woocommerce_civicrm_billing_location_type_id', 5);
    $civicrm_shipping = get_option('woocommerce_civicrm_shipping_location_type_id', 1);
    try {
        $existing_addresses = civicrm_api3('address', 'get', array('contact_id' => $cid));
        $existing_addresses = $existing_addresses['values'];
        $existing_phones = civicrm_api3('phone', 'get', array('contact_id' => $cid));
        $existing_phones = $existing_phones['values'];
        $shipping_address = $billing_address = array('contact_id' => $cid);
        $address_types = array('billing', 'shipping');
        foreach ($address_types as $address_type) {
            // Process Phone
            $phone_exists = FALSE;
            if (!empty($order->{$address_type . '_phone'})) {
                $phone = array('phone_type_id' => 1, 'location_type_id' => ${'civicrm_' . $address_type}, 'phone' => $order->{$address_type . '_phone'}, 'contact_id' => $cid);
                foreach ($existing_phones as $existing_phone) {
                    if ($existing_phone['location_type_id'] == ${'civicrm_' . $address_type}) {
                        $phone['id'] = $existing_phone['id'];
                    }
                    if ($existing_phone['phone'] == $phone['phone']) {
                        $phone_exists = TRUE;
                    }
                }
                if (!$phone_exists) {
                    civicrm_api3('phone', 'create', $phone);
                    $note = "Created new CiviCRM Phone of type {$address_type}: {$phone['phone']}";
                    $order->add_order_note($note);
                }
            }
            // Process Address
            $address_exists = FALSE;
            if (!empty($order->{$address_type . '_address_1'}) && !empty($order->{$address_type . '_postcode'})) {
                // Get country id
                $country_id = _woocommerce_civicrm_get_country_id($order->{$address_type . '_country'});
                $address = array('location_type_id' => ${'civicrm_' . $address_type}, 'city' => $order->{$address_type . '_city'}, 'postal_code' => $order->{$address_type . '_postcode'}, 'name' => $order->{$address_type . '_company'}, 'street_address' => $order->{$address_type . '_address_1'}, 'supplemental_address_1' => $order->{$address_type . '_address_2'}, 'country' => $country_id, 'contact_id' => $cid);
                foreach ($existing_addresses as $existing) {
                    if ($existing['location_type_id'] == ${'civicrm_' . $address_type}) {
                        $address['id'] = $existing['id'];
                    } elseif ($existing['street_address'] == $address['street_address'] && CRM_Utils_Array::value('supplemental_address_1', $existing) == CRM_Utils_Array::value('supplemental_address_1', $address) && $existing['city'] == $address['city'] && $existing['postal_code'] == $address['postal_code']) {
                        $address_exists = TRUE;
                    }
                }
                if (!$address_exists) {
                    civicrm_api3('address', 'create', $address);
                    $note = "Created new CiviCRM Address of type {$address_type}: {$address['street_address']}";
                    $order->add_order_note($note);
                }
            }
        }
    } catch (CiviCRM_Exception $e) {
        CRM_Core_Error::debug_log_message('Not able to add/update address or phone');
    }
    return $cid;
    //} catch (Exception $e) {
    //  CRM_Core_Error::debug_log_message('Not able to process contact');
    //  return FALSE;
    //}
}
Example #8
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);
     }
 }
Example #9
0
 /**
  * Browse all rule groups.
  */
 public function run()
 {
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 0);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $session = CRM_Core_Session::singleton();
     $contactIds = $session->get('selectedSearchContactIds');
     if ($context == 'search' || !empty($contactIds)) {
         $context = 'search';
         $this->assign('backURL', $session->readUserContext());
     }
     if ($action & CRM_Core_Action::RENEW) {
         // empty cache
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         if ($rgid) {
             $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
             $cacheKeyString = "merge {$contactType}";
             $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
             $cacheKeyString .= $gid ? "_{$gid}" : '_0';
             CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKeyString);
         }
         $urlQry = "reset=1&action=update&rgid={$rgid}";
         if ($gid) {
             $urlQry .= "&gid={$gid}";
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry));
     } elseif ($action & CRM_Core_Action::MAP) {
         // do a batch merge if requested
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         $result = CRM_Dedupe_Merger::batchMerge($rgid, $gid, 'safe', TRUE, 75);
         $skippedCount = CRM_Utils_Request::retrieve('skipped', 'Positive', $this, FALSE, 0);
         $skippedCount = $skippedCount + count($result['skipped']);
         $mergedCount = CRM_Utils_Request::retrieve('merged', 'Positive', $this, FALSE, 0);
         $mergedCount = $mergedCount + count($result['merged']);
         if (empty($result['merged']) && empty($result['skipped'])) {
             $message = '';
             if ($mergedCount >= 1) {
                 $message = ts("%1 pairs of duplicates were merged", array(1 => $mergedCount));
             }
             if ($skippedCount >= 1) {
                 $message = $message ? "{$message} and " : '';
                 $message .= ts("%1 pairs of duplicates were skipped due to conflict", array(1 => $skippedCount));
             }
             $message .= ts(" during the batch merge process with safe mode.");
             CRM_Core_Session::setStatus($message, ts('Merge Complete'), 'success');
             $urlQry = "reset=1&action=update&rgid={$rgid}";
             if ($gid) {
                 $urlQry .= "&gid={$gid}";
             }
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry));
         } else {
             $urlQry = "reset=1&action=map&rgid={$rgid}";
             if ($gid) {
                 $urlQry .= "&gid={$gid}";
             }
             $urlQry .= "&skipped={$skippedCount}&merged={$mergedCount}";
             CRM_Utils_System::jsRedirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlQry), ts('Batch Merge Task in progress'), ts('The batch merge task is still in progress. This page will be refreshed automatically.'));
         }
     }
     if ($action & CRM_Core_Action::UPDATE || $action & CRM_Core_Action::BROWSE) {
         $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
         $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE, 0);
         $this->action = CRM_Core_Action::UPDATE;
         //calculate the $contactType
         if ($rgid) {
             $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
         }
         $sourceParams = 'snippet=4';
         if ($gid) {
             $sourceParams .= "&gid={$gid}";
         }
         if ($rgid) {
             $sourceParams .= "&rgid={$rgid}";
         }
         if ($context == 'conflicts') {
             $sourceParams .= "&selected=1";
         }
         $this->assign('sourceUrl', CRM_Utils_System::url('civicrm/ajax/dedupefind', $sourceParams, FALSE, NULL, FALSE));
         //reload from cache table
         $cacheKeyString = "merge {$contactType}";
         $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
         $cacheKeyString .= $gid ? "_{$gid}" : '_0';
         $stats = CRM_Dedupe_Merger::getMergeStatsMsg($cacheKeyString);
         if ($stats) {
             CRM_Core_Session::setStatus($stats);
             // reset so we not displaying same message again
             CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
         }
         $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND\n                                                                 pn.entity_id2 = de.contact_id2 )";
         $where = "de.id IS NULL";
         if ($context == 'conflicts') {
             $where .= " AND pn.is_selected = 1";
         }
         $this->_mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
         if (empty($this->_mainContacts)) {
             if ($context == 'conflicts') {
                 // if the current screen was intended to list only selected contacts, move back to full dupe list
                 $sourceParams = 'reset=1&action=update';
                 if ($gid) {
                     $sourceParams .= "&gid={$gid}";
                 }
                 if ($rgid) {
                     $sourceParams .= "&rgid={$rgid}";
                 }
                 CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), $sourceParams));
             }
             if ($gid) {
                 $foundDupes = $this->get("dedupe_dupes_{$gid}");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid);
                 }
                 $this->set("dedupe_dupes_{$gid}", $foundDupes);
             } elseif (!empty($contactIds)) {
                 $foundDupes = $this->get("search_dedupe_dupes_{$gid}");
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIds);
                 }
                 $this->get("search_dedupe_dupes_{$gid}", $foundDupes);
             } else {
                 $foundDupes = $this->get('dedupe_dupes');
                 if (!$foundDupes) {
                     $foundDupes = CRM_Dedupe_Finder::dupes($rgid);
                 }
                 $this->set('dedupe_dupes', $foundDupes);
             }
             if (!$foundDupes) {
                 $ruleGroup = new CRM_Dedupe_BAO_RuleGroup();
                 $ruleGroup->id = $rgid;
                 $ruleGroup->find(TRUE);
                 $session = CRM_Core_Session::singleton();
                 $session->setStatus(ts('No possible duplicates were found using %1 rule.', array(1 => $ruleGroup->name)), ts('None Found'), 'info');
                 $url = CRM_Utils_System::url('civicrm/contact/deduperules', 'reset=1');
                 if ($context == 'search') {
                     $url = $session->readUserContext();
                 }
                 CRM_Utils_System::redirect($url);
             } else {
                 $cids = array();
                 foreach ($foundDupes as $dupe) {
                     $cids[$dupe[0]] = 1;
                     $cids[$dupe[1]] = 1;
                 }
                 $cidString = implode(', ', array_keys($cids));
                 $sql = "SELECT id, display_name FROM civicrm_contact WHERE id IN ({$cidString}) ORDER BY sort_name";
                 $dao = new CRM_Core_DAO();
                 $dao->query($sql);
                 $displayNames = array();
                 while ($dao->fetch()) {
                     $displayNames[$dao->id] = $dao->display_name;
                 }
                 // FIXME: sort the contacts; $displayName
                 // is already sort_name-sorted, so use that
                 // (also, consider sorting by dupe count first)
                 // lobo - change the sort to by threshold value
                 // so the more likely dupes are sorted first
                 $session = CRM_Core_Session::singleton();
                 $userId = $session->get('userID');
                 $mainContacts = $permission = array();
                 foreach ($foundDupes as $dupes) {
                     $srcID = $dupes[0];
                     $dstID = $dupes[1];
                     if ($dstID == $userId) {
                         $srcID = $dupes[1];
                         $dstID = $dupes[0];
                     }
                     /***
                      * Eliminate this since it introduces 3 queries PER merge row
                      * and hence is very expensive
                      * CRM-8822
                      * if ( !array_key_exists( $srcID, $permission ) ) {
                      * $permission[$srcID] = CRM_Contact_BAO_Contact_Permission::allow( $srcID, CRM_Core_Permission::EDIT );
                      * }
                      * if ( !array_key_exists( $dstID, $permission ) ) {
                      * $permission[$dstID] = CRM_Contact_BAO_Contact_Permission::allow( $dstID, CRM_Core_Permission::EDIT );
                      * }
                      *
                      * $canMerge = ( $permission[$dstID] && $permission[$srcID] );
                      *
                      */
                     // we'll do permission checking during the merge process
                     $canMerge = TRUE;
                     $mainContacts[] = $row = array('srcID' => $srcID, 'srcName' => $displayNames[$srcID], 'dstID' => $dstID, 'dstName' => $displayNames[$dstID], 'weight' => $dupes[2], 'canMerge' => $canMerge);
                     $data = CRM_Core_DAO::escapeString(serialize($row));
                     $values[] = " ( 'civicrm_contact', {$srcID}, {$dstID}, '{$cacheKeyString}', '{$data}' ) ";
                 }
                 if ($cid) {
                     $this->_cid = $cid;
                 }
                 if ($gid) {
                     $this->_gid = $gid;
                 }
                 $this->_rgid = $rgid;
                 $this->_mainContacts = $mainContacts;
                 CRM_Core_BAO_PrevNextCache::setItem($values);
                 $session = CRM_Core_Session::singleton();
                 if ($this->_cid) {
                     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/deduperules', "action=update&rgid={$this->_rgid}&gid={$this->_gid}&cid={$this->_cid}"));
                 } else {
                     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', "reset=1&action=update&rgid={$this->_rgid}"));
                 }
             }
         } else {
             if ($cid) {
                 $this->_cid = $cid;
             }
             if ($gid) {
                 $this->_gid = $gid;
             }
             $this->_rgid = $rgid;
         }
         $this->assign('action', $this->action);
         $this->browse();
     } else {
         $this->action = CRM_Core_Action::UPDATE;
         $this->edit($this->action);
         $this->assign('action', $this->action);
     }
     $this->assign('context', $context);
     // parent run
     return parent::run();
 }
Example #10
0
/**
 * Check parameters passed in.
 *
 * This function is on it's way out.
 *
 * @param array $params
 * @param bool $dupeCheck
 *
 * @return null
 * @throws API_Exception
 * @throws CiviCRM_API3_Exception
 */
function _civicrm_api3_contact_check_params(&$params, $dupeCheck)
{
    switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
        case 'household':
            civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
            break;
        case 'organization':
            civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
            break;
        case 'individual':
            civicrm_api3_verify_one_mandatory($params, NULL, array('first_name', 'last_name', 'email', 'display_name'));
            break;
    }
    // Fixme: This really needs to be handled at a lower level. @See CRM-13123
    if (isset($params['preferred_communication_method'])) {
        $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
    }
    if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
        if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type'])) {
            throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
        }
    }
    if ($dupeCheck) {
        // check for record already existing
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $params['check_permission'];
        }
        $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
        if (count($ids) > 0) {
            throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
        }
    }
    // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
    if (!empty($params['current_employer'])) {
        $organizationParams = array('organization_name' => $params['current_employer']);
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
        // check for mismatch employer name and id
        if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
            throw new API_Exception('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (empty($params['employer_id']) && count($dupeIds) > 1) {
            throw new API_Exception('Found more than one Organisation with same Name.');
        }
        if ($dupeIds) {
            $params['employer_id'] = $dupeIds[0];
        } else {
            $result = civicrm_api3('Contact', 'create', array('organization_name' => $params['current_employer'], 'contact_type' => 'Organization'));
            $params['employer_id'] = $result['id'];
        }
    }
    return NULL;
}
 /**
  * Method to check if the user is already registered for the event
  * and if result found redirect to the event info page
  *
  * @param array $fields  the input form values(anonymous user)
  * @param array $self    event data
  * @param boolean $isAdditional treat isAdditional participants a bit differently
  * @param boolean $returnContactId just find and return the contactID match to use
  * @param boolean $useDedupeRules force usage of dedupe rules
  *
  * @return void
  * @access public
  */
 static function checkRegistration($fields, &$self, $isAdditional = FALSE, $returnContactId = FALSE, $useDedupeRules = FALSE)
 {
     // CRM-3907, skip check for preview registrations
     // CRM-4320 participant need to walk wizard
     if (!$returnContactId && ($self->_mode == 'test' || $self->_allowConfirmation)) {
         return FALSE;
     }
     $contactID = NULL;
     $session = CRM_Core_Session::singleton();
     if (!$isAdditional) {
         $contactID = $self->getContactID();
     }
     if (!$contactID && is_array($fields) && $fields) {
         //CRM-6996
         //as we are allowing w/ same email address,
         //lets check w/ other contact params.
         if ($self->_values['event']['allow_same_participant_emails']) {
             $params = $fields;
             $level = $isAdditional ? 'Supervised' : 'Unsupervised';
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             // disable permission based on cache since event registration is public page/feature.
             $dedupeParams['check_permission'] = FALSE;
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', $level);
             $contactID = CRM_Utils_Array::value(0, $ids);
         } else {
             foreach ($fields as $fieldname => $fieldvalue) {
                 if (substr($fieldname, 0, 6) == 'email-') {
                     $emailString = trim($fieldvalue);
                     if (!empty($emailString)) {
                         $match = CRM_Contact_BAO_Contact::matchContactOnEmail($emailString, 'Individual');
                         if (!empty($match)) {
                             $contactID = $match->contact_id;
                         }
                     }
                 }
             }
         }
     }
     if ($returnContactId) {
         // CRM-7377
         // return contactID if contact already exists
         return $contactID;
     }
     if ($contactID) {
         $participant = new CRM_Event_BAO_Participant();
         $participant->contact_id = $contactID;
         $participant->event_id = $self->_values['event']['id'];
         if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
             $participant->role_id = $fields['participant_role'];
         } else {
             $participant->role_id = $self->_values['event']['default_role_id'];
         }
         $participant->is_test = 0;
         $participant->find();
         $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
         while ($participant->fetch()) {
             if (array_key_exists($participant->status_id, $statusTypes)) {
                 if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
                     $registerUrl = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_values['event']['id']}&cid=0");
                     if ($self->_pcpId) {
                         $registerUrl .= '&pcpId=' . $self->_pcpId;
                     }
                     $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
                     $session->setStatus($status, ts('Oops.'), 'alert');
                     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$self->_values['event']['id']}&noFullMsg=true");
                     if ($self->_action & CRM_Core_Action::PREVIEW) {
                         $url .= '&action=preview';
                     }
                     if ($self->_pcpId) {
                         $url .= '&pcpId=' . $self->_pcpId;
                     }
                     CRM_Utils_System::redirect($url);
                 }
                 if ($isAdditional) {
                     $status = ts("It looks like this participant is already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.");
                     $session->setStatus($status, ts('Oops.'), 'alert');
                     return $participant->id;
                 }
             }
         }
     }
 }
Example #12
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');
 }
 /**
  * Function to create is honor of
  *
  * @param array $params  associated array of fields (by reference)
  * @param int   $honorId honor Id
  * @param array $honorParams any params that should be send to the create function
  *
  * @return contact id
  */
 static function createHonorContact(&$params, $honorId = NULL, $honorParams = array())
 {
     $honorParams = array_merge(array('first_name' => $params['honor_first_name'], 'last_name' => $params['honor_last_name'], 'prefix_id' => $params['honor_prefix_id'], 'email-Primary' => $params['honor_email']), $honorParams);
     if (!$honorId) {
         $honorParams['email'] = $params['honor_email'];
         $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);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($honorParams, CRM_Core_DAO::$_nullArray, $honorId);
     return $contactID;
 }
Example #14
0
 /**
  * Create Current employer relationship for a individual
  *
  * @param int    $contactID        contact id of the individual
  * @param string $organization     it can be name or id of organization
  * 
  * @access public
  * @static
  */
 static function createCurrentEmployerRelationship($contactID, $organization)
 {
     require_once 'CRM/Contact/BAO/Relationship.php';
     $organizationId = null;
     // if organization id is passed.
     if (is_numeric($organization)) {
         $organizationId = $organization;
     } else {
         $orgName = explode('::', $organization);
         trim($orgName[0]);
         $organizationParams = array();
         $organizationParams['organization_name'] = $orgName[0];
         require_once 'CRM/Dedupe/Finder.php';
         $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
         $dedupeParams['check_permission'] = false;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Fuzzy');
         if (is_array($dupeIDs) && !empty($dupeIDs)) {
             // we should create relationship only w/ first org CRM-4193
             foreach ($dupeIDs as $orgId) {
                 $organizationId = $orgId;
                 break;
             }
         } else {
             //create new organization
             $newOrg = array('contact_type' => 'Organization', 'organization_name' => trim($orgName[0]));
             $org = CRM_Contact_BAO_Contact::add($newOrg);
             $organizationId = $org->id;
         }
     }
     if ($organizationId) {
         $cid = array('contact' => $contactID);
         // get the relationship type id of "Employee of"
         $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
         if (!$relTypeId) {
             CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
         }
         // create employee of relationship
         $relationshipParams = array('is_active' => true, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($organizationId => true));
         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid);
         // In case we change employer, clean prveovious employer related records.
         $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
         if ($previousEmployerID && $previousEmployerID != $organizationId) {
             self::clearCurrentEmployer($contactID, $previousEmployerID);
         }
         // set current employer
         self::setCurrentEmployer(array($contactID => $organizationId));
         // handle related meberships. CRM-3792
         self::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate);
     }
 }
 /**
  * @todo per totten's suggestion, wrap all these writes in a transaction;
  * see http://wiki.civicrm.org/confluence/display/CRMDOC43/Transaction+Reference
  */
 function postProcess()
 {
     $cid = CRM_Utils_Array::value('userID', $_SESSION['CiviCRM'], NULL);
     $values = $this->controller->exportValues();
     $profileFields = array();
     foreach ($this->getProfileIDs() as $profileID) {
         $profileFields += CRM_Core_BAO_UFGroup::getFields($profileID);
     }
     $profileValues = array_intersect_key($values, $profileFields);
     $activityValues = array_diff_key($values, $profileValues);
     // Search for duplicate
     if (!$cid) {
         $dedupeParams = CRM_Dedupe_Finder::formatParams($profileValues, 'Individual');
         $dedupeParams['check_permission'] = FALSE;
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
         if ($ids) {
             $cid = $ids[0];
         }
     }
     $cid = CRM_Contact_BAO_Contact::createProfileContact($profileValues, $profileFields, $cid);
     $activity_statuses = CRM_Activity_BAO_Activity::buildOptions('status_id', 'create');
     $projectNeeds = array();
     foreach ($this->_needs as $need) {
         $activityValues['volunteer_need_id'] = $need['id'];
         $activityValues['activity_date_time'] = CRM_Utils_Array::value('start_time', $need);
         $activityValues['assignee_contact_id'] = $cid;
         $activityValues['is_test'] = $this->_mode === 'test' ? 1 : 0;
         // below we assume that volunteers are always signing up only themselves;
         // for now this is a safe assumption, but we may need to revisit this.
         $activityValues['source_contact_id'] = $cid;
         // Set status to Available if user selected Flexible Need, else set to Scheduled.
         if (CRM_Utils_Array::value('is_flexible', $need)) {
             $activityValues['status_id'] = CRM_Utils_Array::key('Available', $activity_statuses);
         } else {
             $activityValues['status_id'] = CRM_Utils_Array::key('Scheduled', $activity_statuses);
         }
         $activityValues['time_scheduled_minutes'] = CRM_Utils_Array::value('duration', $need);
         CRM_Volunteer_BAO_Assignment::createVolunteerActivity($activityValues);
         if (!array_key_exists($need['project_id'], $projectNeeds)) {
             $projectNeeds[$need['project_id']] = array();
         }
         $need['role'] = $need['role_label'];
         $need['description'] = $need['role_description'];
         $need['duration'] = CRM_Utils_Array::value('duration', $need);
         $projectNeeds[$need['project_id']][$need['id']] = $need;
     }
     // Send confirmation email to volunteer
     list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($cid);
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     if ($email) {
         $tplParams = $this->prepareTplParams($projectNeeds);
         $sendTemplateParams = array('contactId' => $cid, 'from' => "{$domainEmailName} <" . $domainEmailAddress . ">", 'groupName' => 'msg_tpl_workflow_volunteer', 'isTest' => $this->_mode === 'test', 'toName' => $displayName, 'toEmail' => $email, 'tplParams' => array("volunteer_projects" => $tplParams), 'valueName' => 'volunteer_registration');
         $bcc = array();
         foreach ($tplParams as $data) {
             foreach ($data['contacts'] as $manager) {
                 $bcc[$manager['contact_id']] = "{$manager['display_name']} <{$manager['email']}>";
             }
         }
         if (count($bcc)) {
             $sendTemplateParams['bcc'] = implode(', ', $bcc);
         }
         CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     }
     $statusMsg = ts('You are scheduled to volunteer. Thank you!', array('domain' => 'org.civicrm.volunteer'));
     CRM_Core_Session::setStatus($statusMsg, '', 'success');
     CRM_Utils_System::redirect($this->_destination);
 }
Example #16
0
 /**
  * Searches for a contact in the db with similar attributes.
  *
  * @param array $params
  *   The list of values to be used in the where clause.
  * @param int $id
  *   The current contact id (hence excluded from matching).
  * @param string $contactType
  *
  * @return int|null
  *   contact_id if found, null otherwise
  */
 public static function findContact(&$params, $id = NULL, $contactType = 'Individual')
 {
     $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $contactType);
     $dedupeParams['check_permission'] = CRM_Utils_Array::value('check_permission', $params, TRUE);
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Supervised', array($id));
     if (!empty($ids)) {
         return implode(',', $ids);
     } else {
         return NULL;
     }
 }
Example #17
0
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  *   The uploaded files if any.
  * @param CRM_Core_Form $form
  *   The form object.
  *
  * @return bool|array
  *   true if no errors, else array of errors
  */
 public static function formRule($fields, $files, $form)
 {
     CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
     $errors = array();
     // if no values, return
     if (empty($fields)) {
         return TRUE;
     }
     $register = NULL;
     // hack we use a -1 in options to indicate that its registration
     if ($form->_id) {
         $form->_isUpdateDupe = 1;
     }
     if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
         $register = TRUE;
     }
     // dont check for duplicates during registration validation: CRM-375
     if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
         // fix for CRM-3240
         if (!empty($fields['email-Primary'])) {
             $fields['email'] = CRM_Utils_Array::value('email-Primary', $fields);
         }
         // fix for CRM-6141
         if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
             $fields['phone-Primary'] = $fields['phone-Primary-1'];
         }
         $ctype = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
         // If all profile fields is of Contact Type then consider
         // profile is of Individual type(default).
         if (!$ctype) {
             $ctype = 'Individual';
         }
         $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $ctype);
         if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
             // fix for CRM-2888
             $exceptions = array();
         } else {
             // for edit mode we need to allow our own record to be a dupe match!
             $exceptions = array($form->_session->get('userID'));
         }
         // for dialog mode we should always use fuzzy rule.
         $ruleType = 'Unsupervised';
         if ($form->_context == 'dialog') {
             $ruleType = 'Supervised';
         }
         $dedupeParams['check_permission'] = FALSE;
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $ctype, $ruleType, $exceptions, $form->_ruleGroupID);
         if ($ids) {
             if ($form->_isUpdateDupe == 2) {
                 CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
             } elseif ($form->_isUpdateDupe == 1) {
                 if (!$form->_id) {
                     $form->_id = $ids[0];
                 }
             } else {
                 if ($form->_context == 'dialog') {
                     $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
                     $duplicateContactsLinks = '<div class="matching-contacts-found">';
                     $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
                     if ($contactLinks['msg'] == 'view') {
                         $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
                     } else {
                         $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
                     }
                     $duplicateContactsLinks .= '</div>';
                     $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
                     $row = '';
                     for ($i = 0; $i < count($contactLinks['rows']); $i++) {
                         $row .= '  <tr>   ';
                         $row .= '    <td class="matching-contacts-name"> ';
                         $row .= $contactLinks['rows'][$i]['display_name'];
                         $row .= '    </td>';
                         $row .= '    <td class="matching-contacts-email"> ';
                         $row .= $contactLinks['rows'][$i]['primary_email'];
                         $row .= '    </td>';
                         $row .= '    <td class="action-items"> ';
                         $row .= $contactLinks['rows'][$i]['view'] . ' ';
                         $row .= $contactLinks['rows'][$i]['edit'];
                         $row .= '    </td>';
                         $row .= '  </tr>   ';
                     }
                     $duplicateContactsLinks .= $row . '</table>';
                     $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
                     $errors['_qf_default'] = $duplicateContactsLinks;
                     // let smarty know that there are duplicates
                     $template = CRM_Core_Smarty::singleton();
                     $template->assign('isDuplicate', 1);
                 } else {
                     $errors['_qf_default'] = ts('A record already exists with the same information.');
                 }
             }
         }
     }
     foreach ($fields as $key => $value) {
         list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
         if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
             // Validate Country - State list
             $countryId = $fields["country-{$locTypeId}"];
             $stateProvinceId = $value;
             if ($stateProvinceId && $countryId) {
                 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
                 $stateProvinceDAO->id = $stateProvinceId;
                 $stateProvinceDAO->find(TRUE);
                 if ($stateProvinceDAO->country_id != $countryId) {
                     // country mismatch hence display error
                     $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
                     $countries = CRM_Core_PseudoConstant::country();
                     $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
                 }
             }
         }
         if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
             // Validate County - State list
             $stateProvinceId = $fields["state_province-{$locTypeId}"];
             $countyId = $value;
             if ($countyId && $stateProvinceId) {
                 $countyDAO = new CRM_Core_DAO_County();
                 $countyDAO->id = $countyId;
                 $countyDAO->find(TRUE);
                 if ($countyDAO->state_province_id != $stateProvinceId) {
                     // state province mismatch hence display error
                     $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
                     $counties = CRM_Core_PseudoConstant::county();
                     $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
                 }
             }
         }
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
                 $errors[$greeting . '_custom'] = ts('Custom  %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', ' ', $greeting))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #18
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;
     }
 }
 CRM_Core_Error::debug('$rows', $rows[0] . '/n \\n');
 $contactResult = civicrm_api3('Contact', 'get', array('return' => 'id', 'external_identifier' => $rows[0]));
 $membershipResult = array();
 if (empty($contactResult['id'])) {
     $contactParams = array('external_identifier' => $rows[0], 'contact_type' => 'Organization', 'sort_name' => $rows[3], 'contact_sub_type' => $contactSubType[$rows[2]], 'display_name' => $rows[3], 'source' => 'Import via script', 'organization_name' => $rows[5], 'email' => $rows[19], 'api.Address.create' => array('location_type_id' => 3, 'is_primary' => 1, 'street_address' => $rows[7], 'city' => $rows[13], 'state_province_id' => array_search($rows[14], $stateProvince), 'postal_code' => $rows[15], 'country_id' => 1039), 'api.Phone.create' => array(array('location_type_id' => 3, 'is_primary' => 1, 'phone' => $rows[11], 'phone_type_id' => 1), array('location_type_id' => 3, 'is_primary' => 1, 'phone' => $rows[12], 'phone_type_id' => 3)));
     $contactResult = civicrm_api3('Contact', 'create', $contactParams);
 } else {
     $errors['org'][] = $rows[0];
     // check for membership for CFRA ID
     $membershipResult = civicrm_api3('Membership', 'get', array('contact_id' => $contactResult['id'], 'return' => 'id'));
 }
 if (!empty($rows[9]) && !empty($rows[10])) {
     $contacts = array('first_name' => $rows[9], 'last_name' => $rows[10], 'contact_type' => 'Individual', 'source' => 'Import via script', 'job_title' => $rows[4], 'employer_id' => $contactResult['id']);
     $dedupeParams = CRM_Dedupe_Finder::formatParams($contacts, 'Individual');
     $dedupeParams['check_permission'] = FALSE;
     $dupes = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', NULL, array(), 11);
     if (!CRM_Utils_Array::value('0', $dupes, NULL)) {
         $contacts['api.Address.create'] = array('location_type_id' => 3, 'is_primary' => 1, 'street_address' => $rows[7], 'city' => $rows[13], 'state_province_id' => array_search($rows[14], $stateProvince), 'postal_code' => $rows[15], 'country_id' => 1039);
         civicrm_api3('Contact', 'create', $contacts);
     } else {
         $errors['ind'][] = $rows[0];
     }
 }
 $membershipParams = array('contact_id' => $contactResult['id'], 'membership_type_id' => 7, 'source' => 'Import From script');
 if (!empty($rows[16])) {
     $membershipParams['join_date'] = date('Y-m-d', strtotime($rows[16]));
 }
 if (!empty($rows[17])) {
     $membershipParams['start_date'] = date('Y-m-d', strtotime($rows[17]));
 } else {
     $errors['mem'][] = $rows[0];
Example #20
0
  function run() {
    $chat = "";
    if (isset($_POST['data'])) {
      $json = stripslashes($_POST['data']);
      $chat = json_decode($json, true);
    }
    
    // Get the secret code from the callback
    $checkCode = CRM_Utils_Request::retrieve('olarksecret', 'String', CRM_Core_DAO::$_nullArray, FALSE, NULL, 'GET');
    // Get the secret code which is set in the database
    $secretCode = CRM_Core_OptionGroup::values('olark_secret', TRUE);

    if ($chat && ($checkCode == $secretCode['Secret Code'])) { // check if codes match
      // log messages
      foreach ($chat['items'] as $key => $elements) {
        $messages[] = $elements['nickname'].': '.$elements['body'];
      }
  
      // operator
      foreach ($chat['operators'] as $key => $elements) {
        $operators['email'] = $elements['emailAddress'];
      }
      $operators['version'] = 3;
      //operator details
      $operator = civicrm_api( 'Contact', 'get', $operators );
      $operatorName = CRM_Contact_BAO_Contact::displayName($operator['id']);

      // visitor
      $visitor['display_name'] = $chat['visitor']['fullName'];
      $visitor['email'] = $chat['visitor']['emailAddress'];
      $visitor['contact_type'] = 'Individual';
      $visitor['version'] = 3;
      $dedupeParams = CRM_Dedupe_Finder::formatParams($visitor, 'Individual');
      $dedupeParams['check_permission'] = FALSE;
      $dupes = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
      if (count($dupes) == 1) {
        $visitor['contact_id'] = $dupes[0];
      } 
      elseif (count($dupes) > 1) {
        $dao = new CRM_Core_DAO_UFMatch();
        $dao->uf_name = $visitor['email'];
        if ($dao->find(TRUE)) {
          $visitor['contact_id'] = $dao->contact_id;
        }
        else { 
          $visitor['contact_id'] = $dupes[0];
        }
      }
      $contact = civicrm_api( 'Contact', 'create', $visitor );

      // create the activity
      $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
      $activityParams = array(
        'activity_type_id' => array_search('Chat Activity', $activityTypes),
        'subject' => 'Chat between '.$visitor['display_name'].' and '.$operatorName,
        'status_id' => 2,
        'activity_date_time' => date('YmdHis'),
        'source_contact_id' => $operator['id'],
        'target_contact_id' => $contact['id'],
        'assignee_contact_id' => $operator['id'],
        'details' => implode('<br/>', $messages),
        'version' => 3,
      );
      $activity = civicrm_api( 'Activity', 'create', $activityParams);
    }
    parent::run();
  }
Example #21
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;
     }
 }
/**
 * Ensure that we have the right input parameters
 *
 * @todo We also need to make sure we run all the form rules on the params list
 *       to ensure that the params are valid
 *
 * @param array   $params          Associative array of property name/value
 *                                 pairs to insert in new contact.
 * @param boolean $dupeCheck       Should we check for duplicate contacts
 * @param boolean $dupeErrorArray  Should we return values of error
 *                                 object in array foramt
 * @param boolean $requiredCheck   Should we check if required params
 *                                 are present in params array
 * @param int   $dedupeRuleGroupID - the dedupe rule ID to use if present
 *
 * @return null on success, error message otherwise
 * @access public
 */
function civicrm_contact_check_params(&$params, $dupeCheck = TRUE, $dupeErrorArray = FALSE, $requiredCheck = TRUE, $dedupeRuleGroupID = NULL)
{
    if ($requiredCheck) {
        $required = array('Individual' => array(array('first_name', 'last_name'), 'email'), 'Household' => array('household_name'), 'Organization' => array('organization_name'));
        // cannot create a contact with empty params
        if (empty($params)) {
            return civicrm_create_error('Input Parameters empty');
        }
        if (!array_key_exists('contact_type', $params)) {
            return civicrm_create_error('Contact Type not specified');
        }
        // contact_type has a limited number of valid values
        $fields = CRM_Utils_Array::value($params['contact_type'], $required);
        if ($fields == NULL) {
            return civicrm_create_error("Invalid Contact Type: {$params['contact_type']}");
        }
        if ($csType = CRM_Utils_Array::value('contact_sub_type', $params)) {
            if (!CRM_Contact_BAO_ContactType::isExtendsContactType($csType, $params['contact_type'])) {
                return civicrm_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array) $csType));
            }
        }
        if (!CRM_Utils_Array::value('contact_id', $params)) {
            $valid = FALSE;
            $error = '';
            foreach ($fields as $field) {
                if (is_array($field)) {
                    $valid = TRUE;
                    foreach ($field as $element) {
                        if (!CRM_Utils_Array::value($element, $params)) {
                            $valid = FALSE;
                            $error .= $element;
                            break;
                        }
                    }
                } else {
                    if (CRM_Utils_Array::value($field, $params)) {
                        $valid = TRUE;
                    }
                }
                if ($valid) {
                    break;
                }
            }
            if (!$valid) {
                return civicrm_create_error("Required fields not found for {$params['contact_type']} : {$error}");
            }
        }
    }
    if ($dupeCheck) {
        // check for record already existing
        require_once 'CRM/Dedupe/Finder.php';
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $fields['check_permission'];
        }
        $ids = implode(',', CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array(), $dedupeRuleGroupID));
        if ($ids != NULL) {
            if ($dupeErrorArray) {
                $error = CRM_Core_Error::createError("Found matching contacts: {$ids}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $ids);
                return civicrm_create_error($error->pop());
            }
            return civicrm_create_error("Found matching contacts: {$ids}", array($ids));
        }
    }
    //check for organisations with same name
    if (CRM_Utils_Array::value('current_employer', $params)) {
        $organizationParams = array();
        $organizationParams['organization_name'] = $params['current_employer'];
        require_once 'CRM/Dedupe/Finder.php';
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Fuzzy');
        // check for mismatch employer name and id
        if (CRM_Utils_Array::value('employer_id', $params) && !in_array($params['employer_id'], $dupeIds)) {
            return civicrm_create_error('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (!CRM_Utils_Array::value('employer_id', $params) && count($dupeIds) > 1) {
            return civicrm_create_error('Found more than one Organisation with same Name.');
        }
    }
    return NULL;
}
Example #23
0
 static function processAPIContribution($params)
 {
     if (empty($params) || array_key_exists('error', $params)) {
         return false;
     }
     // add contact using dedupe rule
     require_once 'CRM/Dedupe/Finder.php';
     $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
     $dedupeParams['check_permission'] = false;
     $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
     // if we find more than one contact, use the first one
     if (CRM_Utils_Array::value(0, $dupeIds)) {
         $params['contact_id'] = $dupeIds[0];
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact = CRM_Contact_BAO_Contact::create($params);
     if (!$contact->id) {
         return false;
     }
     // only pass transaction params to contribution::create, if available
     if (array_key_exists('transaction', $params)) {
         $params = $params['transaction'];
         $params['contact_id'] = $contact->id;
     }
     // handle contribution custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Contribution', false, false, CRM_Utils_Array::value('contribution_type_id', $params));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, CRM_Utils_Array::value('id', $params, null), 'Contribution');
     // create contribution
     // if this is a recurring contribution then process it first
     if ($params['trxn_type'] == 'subscrpayment') {
         // see if a recurring record already exists
         require_once 'CRM/Contribute/BAO/ContributionRecur.php';
         $recurring = new CRM_Contribute_BAO_ContributionRecur();
         $recurring->processor_id = $params['processor_id'];
         if (!$recurring->find(true)) {
             $recurring = new CRM_Contribute_BAO_ContributionRecur();
             $recurring->invoice_id = $params['invoice_id'];
             $recurring->find(true);
         }
         // This is the same thing the CiviCRM IPN handler does to handle
         // subsequent recurring payments to avoid duplicate contribution
         // errors due to invoice ID. See:
         // ./CRM/Core/Payment/PayPalIPN.php:200
         if ($recurring->id) {
             $params['invoice_id'] = md5(uniqid(rand(), true));
         }
         $recurring->copyValues($params);
         $recurring->save();
         if (is_a($recurring, 'CRM_Core_Error')) {
             return false;
         } else {
             $params['contribution_recur_id'] = $recurring->id;
         }
     }
     require_once 'CRM/Contribute/BAO/Contribution.php';
     $contribution =& CRM_Contribute_BAO_Contribution::create($params, CRM_Core_DAO::$_nullArray);
     if (!$contribution->id) {
         return false;
     }
     return true;
 }
Example #24
0
/**
 * Check for duplicate contacts.
 *
 * @param array $params
 *   Params per getfields metadata.
 *
 * @return array
 *   API formatted array
 */
function civicrm_api3_contact_duplicatecheck($params)
{
    $dedupeParams = CRM_Dedupe_Finder::formatParams($params['match'], $params['match']['contact_type']);
    // CRM-6431
    // setting 'check_permission' here means that the dedupe checking will be carried out even if the
    // person does not have permission to carry out de-dupes
    // this is similar to the front end form
    if (isset($params['check_permission'])) {
        $dedupeParams['check_permission'] = $params['check_permission'];
    }
    $dupes = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array::value('dedupe_rule_id', $params));
    $values = empty($dupes) ? array() : array_fill_keys($dupes, array());
    return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
}
Example #25
0
 /**
  * @param $fields
  *
  * @return mixed|null
  */
 static function find_contact($fields)
 {
     $dedupe_params = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
     $dedupe_params['check_permission'] = FALSE;
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupe_params, 'Individual');
     if (is_array($ids)) {
         return array_pop($ids);
     } else {
         return NULL;
     }
 }
/**
 * @param array $params
 * @param bool $dupeCheck
 * @param bool $dupeErrorArray
 * @param bool $requiredCheck
 * @param int $dedupeRuleGroupID
 *
 * @return array|null
 */
function _civicrm_api3_deprecated_contact_check_params(&$params, $dupeCheck = TRUE, $dupeErrorArray = FALSE, $requiredCheck = TRUE, $dedupeRuleGroupID = NULL)
{
    if (isset($params['id']) && is_numeric($params['id'])) {
        $requiredCheck = FALSE;
    }
    if ($requiredCheck) {
        if (isset($params['id'])) {
            $required = array('Individual', 'Household', 'Organization');
        }
        $required = array('Individual' => array(array('first_name', 'last_name'), 'email'), 'Household' => array('household_name'), 'Organization' => array('organization_name'));
        // contact_type has a limited number of valid values
        if (empty($params['contact_type'])) {
            return civicrm_api3_create_error("No Contact Type");
        }
        $fields = CRM_Utils_Array::value($params['contact_type'], $required);
        if ($fields == NULL) {
            return civicrm_api3_create_error("Invalid Contact Type: {$params['contact_type']}");
        }
        if ($csType = CRM_Utils_Array::value('contact_sub_type', $params)) {
            if (!CRM_Contact_BAO_ContactType::isExtendsContactType($csType, $params['contact_type'])) {
                return civicrm_api3_create_error("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $csType));
            }
        }
        if (empty($params['contact_id']) && !empty($params['id'])) {
            $valid = FALSE;
            $error = '';
            foreach ($fields as $field) {
                if (is_array($field)) {
                    $valid = TRUE;
                    foreach ($field as $element) {
                        if (empty($params[$element])) {
                            $valid = FALSE;
                            $error .= $element;
                            break;
                        }
                    }
                } else {
                    if (!empty($params[$field])) {
                        $valid = TRUE;
                    }
                }
                if ($valid) {
                    break;
                }
            }
            if (!$valid) {
                return civicrm_api3_create_error("Required fields not found for {$params['contact_type']} : {$error}");
            }
        }
    }
    if ($dupeCheck) {
        // @todo switch to using api version by uncommenting these lines & removing following 11.
        // Any change here is too scary for a stable release.
        // $dupes = civicrm_api3('Contact', 'duplicatecheck', (array('match' => $params, 'dedupe_rule_id' => $dedupeRuleGroupID)));
        // $ids = $dupes['count'] ? implode(',', array_keys($dupes['values'])) : NULL;
        // check for record already existing
        require_once 'CRM/Dedupe/Finder.php';
        $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
        // CRM-6431
        // setting 'check_permission' here means that the dedupe checking will be carried out even if the
        // person does not have permission to carry out de-dupes
        // this is similar to the front end form
        if (isset($params['check_permission'])) {
            $dedupeParams['check_permission'] = $params['check_permission'];
        }
        $ids = implode(',', CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array(), $dedupeRuleGroupID));
        if ($ids != NULL) {
            if ($dupeErrorArray) {
                $error = CRM_Core_Error::createError("Found matching contacts: {$ids}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $ids);
                return civicrm_api3_create_error($error->pop());
            }
            return civicrm_api3_create_error("Found matching contacts: {$ids}");
        }
    }
    // check for organisations with same name
    if (!empty($params['current_employer'])) {
        $organizationParams = array();
        $organizationParams['organization_name'] = $params['current_employer'];
        require_once 'CRM/Dedupe/Finder.php';
        $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
        $dedupParams['check_permission'] = FALSE;
        $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
        // check for mismatch employer name and id
        if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
            return civicrm_api3_create_error('Employer name and Employer id Mismatch');
        }
        // show error if multiple organisation with same name exist
        if (empty($params['employer_id']) && count($dupeIds) > 1) {
            return civicrm_api3_create_error('Found more than one Organisation with same Name.');
        }
    }
    return NULL;
}
 /**
  * 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;
 }
Example #28
0
 /**
  * searches for a contact in the db with similar attributes
  *
  * @param array $params the list of values to be used in the where clause
  * @param int    $id          the current contact id (hence excluded from matching)
  * @param boolean $flatten should we flatten the input params
  *
  * @return contact_id if found, null otherwise
  * @access public
  * @static
  */
 public static function findContact(&$params, $id = null, $contactType = 'Individual')
 {
     require_once 'CRM/Dedupe/Finder.php';
     $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $contactType);
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Fuzzy', array($id));
     if (!empty($ids)) {
         return implode(',', $ids);
     } else {
         return null;
     }
 }
Example #29
0
 /**
  * That checks for duplicate contacts.
  *
  * @param array $fields
  *   Fields array which are submitted.
  * @param $errors
  * @param int $contactID
  *   Contact id.
  * @param string $contactType
  *   Contact type.
  */
 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType)
 {
     // if this is a forced save, ignore find duplicate rule
     if (empty($fields['_qf_Contact_upload_duplicate'])) {
         $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $contactType);
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, 'Supervised', array($contactID));
         if ($ids) {
             $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
             $duplicateContactsLinks = '<div class="matching-contacts-found">';
             $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
             if ($contactLinks['msg'] == 'view') {
                 $duplicateContactsLinks .= ts('You can View the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts'));
             } else {
                 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts'));
             }
             if ($contactLinks['msg'] == 'merge') {
                 // We should also get a merge link if this is for an existing contact
                 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
             }
             $duplicateContactsLinks .= '.';
             $duplicateContactsLinks .= '</div>';
             $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
             $row = '';
             for ($i = 0; $i < count($contactLinks['rows']); $i++) {
                 $row .= '  <tr>   ';
                 $row .= '    <td class="matching-contacts-name"> ';
                 $row .= $contactLinks['rows'][$i]['display_name'];
                 $row .= '    </td>';
                 $row .= '    <td class="matching-contacts-email"> ';
                 $row .= $contactLinks['rows'][$i]['primary_email'];
                 $row .= '    </td>';
                 $row .= '    <td class="action-items"> ';
                 $row .= $contactLinks['rows'][$i]['view'];
                 $row .= $contactLinks['rows'][$i]['edit'];
                 $row .= CRM_Utils_Array::value('merge', $contactLinks['rows'][$i]);
                 $row .= '    </td>';
                 $row .= '  </tr>   ';
             }
             $duplicateContactsLinks .= $row . '</table>';
             $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
             $errors['_qf_default'] = $duplicateContactsLinks;
             // let smarty know that there are duplicates
             $template = CRM_Core_Smarty::singleton();
             $template->assign('isDuplicate', 1);
         } elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
             // add a session message for no matching contacts
             CRM_Core_Session::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
         }
     }
 }
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     $session = CRM_Core_Session::singleton();
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $contributionParams = $requestParams = $_REQUEST;
     $contactID = $session->get('userID');
     if ($contactID && empty($contributionParams['email'])) {
         $emailDetails = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
         if (!empty($emailDetails)) {
             $contributionParams['email'] = $emailDetails[1];
             // for email to be prefilled
             $this->assign('email', $emailDetails[1]);
         }
     }
     $pageConfig = civicrm_api3('ContributionPage', 'getsingle', array('id' => $this->_id));
     if (is_array($pageConfig['payment_processor'])) {
         CRM_Core_Error::fatal(ts('Multiple payment processors not supported with quick donate.'));
     }
     $processorDetails = CRM_Financial_BAO_PaymentProcessor::getPayment($pageConfig['payment_processor'], 'live');
     //MV: get amount details if other amount enabled for contribution page.
     if ($pageConfig['amount_block_is_active']) {
         $sql = "SELECT cpfv.amount, cpfv.is_default, cpfv.weight \n        FROM civicrm_price_field_value cpfv \n        INNER JOIN civicrm_price_field cpf ON (cpf.id = cpfv.price_field_id)\n        INNER JOIN civicrm_price_set_entity cpse ON (cpse.price_set_id = cpf.price_set_id)\n        WHERE cpse.entity_id = %1 AND cpf.name = 'contribution_amount'\n      ";
         $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($pageConfig['id'], 'Integer')));
         $amount = 0;
         while ($dao->fetch()) {
             if ($dao->weight == 1 || $dao->is_default == 1) {
                 $amount = $dao->amount;
             }
         }
     }
     $pageConfig['default_amount'] = $amount ? $amount : $pageConfig['min_amount'];
     $pageConfig['currency_symbol'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $pageConfig['currency'], 'symbol', 'name');
     $this->assign('pageConfig', $pageConfig);
     $this->assign('key', $processorDetails['password']);
     $this->assign('currency', strtolower($pageConfig['currency']));
     if (!empty($requestParams['stripe_token'])) {
         //FIXME: could go in post process
         if (!$contributionParams['email']) {
             CRM_Core_Error::fatal(ts('Email address is required'));
         }
         $contributionParams['financial_type_id'] = $pageConfig['financial_type_id'];
         if (!$contactID) {
             $contactParams = array('email' => $contributionParams['email'], 'contact_type' => 'Individual');
             $dedupeParams = CRM_Dedupe_Finder::formatParams($contactParams, '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);
             if (!$contactID) {
                 $cont = civicrm_api3('Contact', 'create', $contactParams);
                 $contactID = $cont['id'];
             }
         }
         $contributionParams['contact_id'] = $contactID;
         $contributionParams['payment_processor_id'] = $pageConfig['payment_processor'];
         $contributionParams['currencyID'] = $pageConfig['currency'];
         //gift aid
         //get gift aid custom field id
         $sqlCF = "SELECT cf.id \n      FROM civicrm_custom_field cf \n      INNER JOIN civicrm_custom_group cg ON (cg.id = cf.custom_group_id) \n      WHERE cg.name = %1 AND cf.name = %2";
         $sqlCFParams = array(1 => array(self::C_CUSTOM_GROUP_GIFT_AID, 'String'), 2 => array(self::C_CUSTOM_FIELD_GIFT_AID, 'String'));
         $cfId = CRM_Core_DAO::singleValueQuery($sqlCF, $sqlCFParams);
         if ($cfId && $contributionParams['donation_form']['gift_aid']) {
             $contributionParams["custom_{$cfId}"] = 1;
         }
         //gift aid end
         //campaign
         if ($pageConfig['campaign_id']) {
             $contributionParams['campaign_id'] = $pageConfig['campaign_id'];
         }
         try {
             $result = civicrm_api3('Contribution', 'transact', $contributionParams);
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             $this->assign('error', $error);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         }
         if (!empty($result['error'])) {
             $this->assign('error', $result['error']);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         } else {
             if ($result) {
                 $contributionID = $result['id'];
                 $contactID = $result['values'][$contributionID]['contact_id'];
                 // Send receipt
                 civicrm_api3('contribution', 'sendconfirmation', array('id' => $contributionID) + $pageConfig);
                 CRM_Utils_System::setTitle(ts('Thank you'));
                 $this->assign('status', 'thankyou');
                 $profileID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'Supporter Profile', 'id', 'title');
                 // Link (button) for users to create their own Personal Campaign page
                 if ($profileID && !$session->get('userID')) {
                     $ufId = CRM_Core_BAO_UFMatch::getUFId($contactID);
                     if ($ufId) {
                         $config = CRM_Core_Config::singleton();
                         $loginURL = $config->userSystem->getLoginURL();
                         $this->assign('loginURL', $loginURL);
                     } else {
                         $linkTextUrl = CRM_Utils_System::url('civicrm/profile/create', "gid={$profileID}&reset=1", FALSE, NULL, TRUE);
                         $this->assign('linkTextUrl', $linkTextUrl);
                     }
                 }
                 //redirect if the logged in user
                 if ($session->get('userID')) {
                     $urlParams = array('pageId' => $this->_id, 'component' => 'contribute', 'reset' => 1);
                     $sql = "SELECT pcp.id FROM civicrm_pcp pcp \n          INNER JOIN  civicrm_pcp_block cpb ON (cpb.id = pcp.pcp_block_id)\n          WHERE cpb.entity_id = %1 AND pcp.contact_id = %2\n          ";
                     $sqlparams = array(1 => array($pageConfig['id'], 'Integer'), 2 => array($contactID, 'Integer'));
                     $pcpId = CRM_Core_DAO::singleValueQuery($sql, $sqlparams);
                     if ($pcpId) {
                         $urlParams['id'] = $pcpId;
                     }
                     $url = CRM_Utils_System::url('civicrm/pcp/setup', $urlParams);
                     CRM_Utils_System::redirect($url);
                 }
             }
         }
     } else {
         if (!empty($requestParams['_qf_Main_display'])) {
             //$this->assign('error', $error);
             CRM_Utils_System::setTitle(ts('Oops! There was a problem'));
         } else {
             $this->assign('status', 'quickdonate');
             CRM_Core_Resources::singleton()->addStyleFile('uk.co.vedaconsulting.quickdonate', 'css/quickdonatebox.css');
         }
     }
 }