Exemplo n.º 1
0
 /**
  * Run the page.
  *
  * This method is called after the page is created.
  */
 public function run()
 {
     // get the emails for this contact
     $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $locBlockNo = CRM_Utils_Request::retrieve('locno', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $addressId = CRM_Utils_Request::retrieve('aid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
     $address = array();
     if ($addressId > 0) {
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'display_name'));
         $entityBlock = array('id' => $addressId);
         $address = CRM_Core_BAO_Address::getValues($entityBlock, FALSE, 'id');
         if (!empty($address)) {
             foreach ($address as $key => &$value) {
                 $value['location_type'] = $locationTypes[$value['location_type_id']];
             }
         }
     }
     // we just need current address block
     $currentAddressBlock['address'][$locBlockNo] = array_pop($address);
     if (!empty($currentAddressBlock['address'][$locBlockNo])) {
         // get contact name of shared contact names
         $sharedAddresses = array();
         $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($currentAddressBlock['address']);
         foreach ($currentAddressBlock['address'] as $key => $addressValue) {
             if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
                 $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']);
             }
         }
         $idValue = $currentAddressBlock['address'][$locBlockNo]['id'];
         if (!empty($currentAddressBlock['address'][$locBlockNo]['master_id'])) {
             $idValue = $currentAddressBlock['address'][$locBlockNo]['master_id'];
         }
         // add custom data of type address
         $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', $this, $idValue);
         // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var.
         $currentAddressBlock['address'][$locBlockNo]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_");
         $this->assign("dnc_viewCustomData", NULL);
         $this->assign('add', $currentAddressBlock['address'][$locBlockNo]);
         $this->assign('sharedAddresses', $sharedAddresses);
     }
     $contact = new CRM_Contact_BAO_Contact();
     $contact->id = $contactId;
     $contact->find(TRUE);
     $privacy = array();
     foreach (CRM_Contact_BAO_Contact::$_commPrefs as $name) {
         if (isset($contact->{$name})) {
             $privacy[$name] = $contact->{$name};
         }
     }
     $this->assign('contactId', $contactId);
     $this->assign('locationIndex', $locBlockNo);
     $this->assign('addressId', $addressId);
     $this->assign('privacy', $privacy);
     // check logged in user permission
     CRM_Contact_Page_View::checkUserPermission($this, $contactId);
     // finally call parent
     parent::run();
 }
 /**
  * Run the page.
  *
  * This method is called after the page is created.
  *
  * @return void
  * @access public
  *
  */
 function run()
 {
     // get the emails for this contact
     $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $locBlockNo = CRM_Utils_Request::retrieve('locno', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $addressId = CRM_Utils_Request::retrieve('aid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
     $address = array();
     if ($addressId > 0) {
         $locationTypes = CRM_Core_PseudoConstant::locationDisplayName();
         $entityBlock = array('id' => $addressId);
         $address = CRM_Core_BAO_Address::getValues($entityBlock, FALSE, 'id');
         if (!empty($address)) {
             foreach ($address as $key => &$value) {
                 $value['location_type'] = $locationTypes[$value['location_type_id']];
             }
         }
     }
     // we just need current address block
     $currentAddressBlock['address'][$locBlockNo] = array_pop($address);
     if (!empty($currentAddressBlock['address'][$locBlockNo])) {
         // get contact name of shared contact names
         $sharedAddresses = array();
         $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($currentAddressBlock['address']);
         foreach ($currentAddressBlock['address'] as $key => $addressValue) {
             if (CRM_Utils_Array::value('master_id', $addressValue) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
                 $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']);
             }
         }
         // add custom data of type address
         $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', $this, $currentAddressBlock['address'][$locBlockNo]['id']);
         // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var.
         $currentAddressBlock['address'][$locBlockNo]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_");
         $this->assign("dnc_viewCustomData", NULL);
         $this->assign('add', $currentAddressBlock['address'][$locBlockNo]);
         $this->assign('sharedAddresses', $sharedAddresses);
     }
     $this->assign('contactId', $contactId);
     $this->assign('locationIndex', $locBlockNo);
     $this->assign('addressId', $addressId);
     $appendBlockIndex = CRM_Core_BAO_Address::getAddressCount($contactId);
     // check if we are adding new address, then only append add link
     if ($appendBlockIndex == $locBlockNo) {
         if ($appendBlockIndex) {
             $appendBlockIndex++;
         }
     } else {
         $appendBlockIndex = 0;
     }
     $this->assign('appendBlockIndex', $appendBlockIndex);
     // check logged in user permission
     CRM_Contact_Page_View::checkUserPermission($this, $contactId);
     // finally call parent
     parent::run();
 }
Exemplo n.º 3
0
 /**
  * Build all the data structures needed to build the form.
  *
  * @return void
  */
 public function preProcess()
 {
     // initialize the task and row fields
     parent::preProcess();
     //get the contact read only fields to display.
     $readOnlyFields = array_merge(array('sort_name' => ts('Name')), CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_autocomplete_options', TRUE, NULL, FALSE, 'name', TRUE));
     //get the read only field data.
     $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
     $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_memberIds, 'CiviMember', $returnProperties);
     $this->assign('contactDetails', $contactDetails);
     $this->assign('readOnlyFields', $readOnlyFields);
 }
Exemplo n.º 4
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
     $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
     if ($this->_crid) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
         $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
         // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
         if ($this->_subscriptionDetails->membership_id) {
             $this->_mid = $this->_subscriptionDetails->membership_id;
         }
     }
     $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
     if ($this->_coid) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
         $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
     }
     if ($this->_mid) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
         $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership');
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
         $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
         $this->_mode = 'auto_renew';
     }
     if (!$this->_crid && !$this->_coid && !$this->_mid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) {
         CRM_Core_Error::fatal('Required information missing.');
     }
     if (!CRM_Core_Permission::check('edit contributions')) {
         $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
         if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
             CRM_Core_Error::fatal(ts('You do not have permission to cancel subscription.'));
         }
         $this->_selfService = TRUE;
     }
     if (!$this->_paymentProcessor['object']->isSupported('updateSubscriptionBillingInfo')) {
         CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.", array(1 => $this->_paymentProcessor['object']->_processorName)));
     }
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $this->assignBillingType();
     $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
     $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
     $this->assign('amount', $this->_subscriptionDetails->amount);
     $this->assign('installments', $this->_subscriptionDetails->installments);
     $this->assign('mode', $this->_mode);
     // handle context redirection
     CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
 }
Exemplo n.º 5
0
 /**
  * build all the data structures needed to build the form
  *
  * @return void
  * @access public
  */
 function preProcess()
 {
     /*
      * initialize the task and row fields
      */
     parent::preProcess();
     //get the contact read only fields to display.
     require_once 'CRM/Core/BAO/Preferences.php';
     $readOnlyFields = array_merge(array('sort_name' => ts('Name')), CRM_Core_BAO_Preferences::valueOptions('contact_autocomplete_options', true, null, false, 'name', true));
     //get the read only field data.
     $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
     require_once 'CRM/Contact/BAO/Contact/Utils.php';
     $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_contributionIds, 'CiviContribute', $returnProperties);
     $this->assign('contactDetails', $contactDetails);
     $this->assign('readOnlyFields', $readOnlyFields);
 }
Exemplo n.º 6
0
 public function preProcess()
 {
     $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
     if ($this->_crid) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
         $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
     }
     $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
     if ($this->_coid) {
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
         $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
         $this->_crid = $this->_subscriptionDetails->recur_id;
     } elseif ($this->_crid) {
         $this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_crid, 'id', 'contribution_recur_id');
     }
     if (!$this->_crid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) {
         CRM_Core_Error::fatal('Required information missing.');
     }
     if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
         CRM_Core_Error::fatal(ts('You cannot update the subscription.'));
     }
     if (!CRM_Core_Permission::check('edit contributions')) {
         $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
         if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
             CRM_Core_Error::fatal(ts('You do not have permission to update subscription.'));
         }
         $this->_selfService = TRUE;
     }
     $this->assign('self_service', $this->_selfService);
     if (!$this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
         $userAlert = ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
         CRM_Core_Session::setStatus($userAlert, ts('Warning'), 'alert');
     }
     $this->assign('isChangeSupported', $this->_paymentProcessorObj->isSupported('changeSubscriptionAmount'));
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
     $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
     if ($this->_subscriptionDetails->contact_id) {
         list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
     }
     CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
     // handle context redirection
     CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
 }
Exemplo n.º 7
0
 public function testProfileChecksum()
 {
     $this->webtestLogin('admin');
     // Profile fields.
     $fields = array('first_name' => array('type' => 'Individual', 'label' => 'First Name', 'default_value' => substr(sha1(rand()), 0, 7), 'update_value' => substr(sha1(rand()), 0, 7), 'element_name' => 'first_name'), 'last_name' => array('type' => 'Individual', 'label' => 'Last Name', 'default_value' => substr(sha1(rand()), 0, 7), 'update_value' => substr(sha1(rand()), 0, 7), 'element_name' => 'last_name'), 'email' => array('type' => 'Contact', 'label' => 'Email', 'location' => 0, 'default_value' => substr(sha1(rand()), 0, 5) . '@example.com', 'update_value' => substr(sha1(rand()), 0, 7) . '@example.com', 'element_name' => 'email-Primary'), 'city' => array('type' => 'Contact', 'label' => 'City', 'location' => 0, 'default_value' => substr(sha1(rand()), 0, 7), 'update_value' => substr(sha1(rand()), 0, 7), 'element_name' => 'city-Primary'), 'country' => array('type' => 'Contact', 'label' => 'Country', 'location' => 0, 'default_value' => '1228', 'update_value' => '1228', 'update_value_label' => 'UNITED STATES', 'element_name' => 'country-Primary', 'html_type' => 'select'), 'state_province' => array('type' => 'Contact', 'label' => 'State', 'location' => 0, 'default_value' => '1004', 'update_value' => '1031', 'update_value_label' => 'NY', 'element_name' => 'state_province-Primary', 'html_type' => 'select'));
     // Create a contact.
     $this->webtestAddContact($fields['first_name']['default_value'], $fields['last_name']['default_value'], $fields['email']['default_value']);
     // Get contact id from url.
     $contactId = $this->urlArg('cid');
     // Create profile for contact
     $profileName = "Profile_" . substr(sha1(rand()), 0, 7);
     $profileId = $this->_testCreateContactProfile($fields, $profileName);
     // Check for profile create/edit permissions.
     $permission = array('edit-1-profile-edit', 'edit-1-profile-create', 'edit-1-access-all-custom-data', 'edit-1-edit-all-contacts');
     $this->changePermissions($permission);
     // Get checksum of the newly created contact.
     $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId);
     // logout.
     $this->webtestLogout();
     // Go to edit profile page of the created contact.
     $this->openCiviPage("profile/edit", "id={$contactId}&gid={$profileId}&reset=1&cs={$cs}", NULL);
     $this->waitForTextPresent($profileName);
     // Check all profile fields, update their values.
     foreach ($fields as $field) {
         $this->assertTrue($this->isElementPresent($field['element_name']), "Missing Field: {$field['label']}.");
         if (isset($field['html_type']) && $field['html_type'] == 'select') {
             $this->waitForElementPresent($field['element_name']);
             $this->select($field['element_name'], "value={$field['update_value']}");
         } else {
             $this->type($field['element_name'], $field['update_value']);
         }
     }
     // Save profile.
     $this->click("_qf_Edit_next");
     $this->waitForPageToLoad(2 * $this->getTimeoutMsec());
     // Check profile view page.
     $this->waitForTextPresent($profileName);
     // Check updated values of all fields.
     $checkFieldValues = array();
     foreach ($fields as $field) {
         $checkFieldValues[] = isset($field['update_value_label']) ? $field['update_value_label'] : $field['update_value'];
     }
     $this->assertStringsPresent($checkFieldValues);
 }
Exemplo n.º 8
0
 /**
  * Build all the data structures needed to build the form.
  *
  * @return void
  */
 public function preProcess()
 {
     // initialize the task and row fields
     parent::preProcess();
     $session = CRM_Core_Session::singleton();
     $this->_userContext = $session->readUserContext();
     $validate = FALSE;
     //validations
     if (count($this->_contactIds) > $this->_maxContacts) {
         CRM_Core_Session::setStatus(ts("The maximum number of contacts you can select for Batch Update is %1. You have selected %2. Please select fewer contacts from your search results and try again.", array(1 => $this->_maxContacts, 2 => count($this->_contactIds))), ts('Maximum Exceeded'), 'error');
         $validate = TRUE;
     }
     if (CRM_Contact_BAO_Contact_Utils::checkContactType($this->_contactIds)) {
         CRM_Core_Session::setStatus(ts("Batch update requires that all selected contacts be the same basic type (e.g. all Individuals OR all Organizations...). Please modify your selection and try again."), ts('Contact Type Mismatch'), 'error');
         $validate = TRUE;
     }
     // than redirect
     if ($validate) {
         CRM_Utils_System::redirect($this->_userContext);
     }
 }
Exemplo n.º 9
0
 /**
  * Build all the data structures needed to build the form.
  */
 public function preProcess()
 {
     // Initialize the task and row fields.
     parent::preProcess();
     // Get the contact read only fields to display.
     $readOnlyFields = array_merge(array('sort_name' => ts('Added By'), 'target_sort_name' => ts('With Contact')), CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_autocomplete_options', TRUE, NULL, FALSE, 'name', TRUE));
     // Get the read only field data.
     $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
     $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_activityHolderIds, 'Activity', $returnProperties);
     $readOnlyFields['assignee_display_name'] = ts('Assigned to');
     if (!empty($contactDetails)) {
         foreach ($contactDetails as $key => $value) {
             $assignee = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($key);
             foreach ($assignee as $keys => $values) {
                 $assigneeContact[] = CRM_Contact_BAO_Contact::displayname($values);
             }
             $contactDetails[$key]['assignee_display_name'] = !empty($assigneeContact) ? implode(';', $assigneeContact) : NULL;
         }
     }
     $this->assign('contactDetails', $contactDetails);
     $this->assign('readOnlyFields', $readOnlyFields);
 }
 /**
  * build all the data structures needed to build the form
  *
  * @return void
  * @access public
  */
 function preProcess()
 {
     /*
      * initialize the task and row fields
      */
     parent::preProcess();
     $session = CRM_Core_Session::singleton();
     $this->_userContext = $session->readUserContext();
     $validate = FALSE;
     //validations
     if (count($this->_contactIds) > $this->_maxContacts) {
         CRM_Core_Session::setStatus("The maximum number of contacts you can select for Batch Update is {$this->_maxContacts}. You have selected " . count($this->_contactIds) . ". Please select fewer contacts from your search results and try again.");
         $validate = TRUE;
     }
     if (CRM_Contact_BAO_Contact_Utils::checkContactType($this->_contactIds)) {
         CRM_Core_Session::setStatus("Batch update requires that all selected contacts be the same type (e.g. all Individuals OR all Organizations...). Please modify your selected contacts and try again.");
         $validate = TRUE;
     }
     // than redirect
     if ($validate) {
         CRM_Utils_System::redirect($this->_userContext);
     }
 }
Exemplo n.º 11
0
 /**
  * Send mail and create activity
  * when participant status changed.
  *
  * @param int $participantId
  *   Participant id.
  * @param array $participantValues
  *   Participant detail values. status id for participants.
  * @param array $eventDetails
  *   Required event details.
  * @param array $contactDetails
  *   Required contact details.
  * @param array $domainValues
  *   Required domain values.
  * @param string $mailType
  *   (eg 'approval', 'confirm', 'expired' ).
  *
  * @return bool
  */
 public static function sendTransitionParticipantMail($participantId, $participantValues, $eventDetails, $contactDetails, &$domainValues, $mailType)
 {
     //send emails.
     $mailSent = FALSE;
     //don't send confirmation mail to additional
     //since only primary able to confirm registration.
     if (!empty($participantValues['registered_by_id']) && $mailType == 'Confirm') {
         return $mailSent;
     }
     $toEmail = CRM_Utils_Array::value('email', $contactDetails);
     if ($toEmail) {
         $contactId = $participantValues['contact_id'];
         $participantName = $contactDetails['display_name'];
         //calculate the checksum value.
         $checksumValue = NULL;
         if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
             $checksumLife = 'inf';
             $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
             if ($endDate) {
                 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
             }
             $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
         }
         //take a receipt from as event else domain.
         $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
         if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
             $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
         }
         list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'participant_' . strtolower($mailType), 'contactId' => $contactId, 'tplParams' => array('contact' => $contactDetails, 'domain' => $domainValues, 'participant' => $participantValues, 'event' => $eventDetails, 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails), 'isAdditional' => $participantValues['registered_by_id'], 'isExpired' => $mailType == 'Expired', 'isConfirm' => $mailType == 'Confirm', 'checksumValue' => $checksumValue), 'from' => $receiptFrom, 'toName' => $participantName, 'toEmail' => $toEmail, 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails)));
         // 3. create activity record.
         if ($mailSent) {
             $now = date('YmdHis');
             $activityType = 'Event Registration';
             $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $participantId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']), 'is_test' => $participantValues['is_test'], 'status_id' => 2);
             if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
                 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
             }
         }
     }
     return $mailSent;
 }
Exemplo n.º 12
0
 /**
  * Returns all the rows in the given offset and rowCount.
  *
  * @param string $action
  *   The action being performed.
  * @param int $offset
  *   The row number to start from.
  * @param int $rowCount
  *   The number of rows to return.
  * @param string $sort
  *   The sql string that describes the sort order.
  * @param string $output
  *   What should the result set include (web/email/csv).
  *
  * @return array
  *   rows in the given offset and rowCount
  */
 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_eventClause);
     // process the result of the query
     $rows = array();
     //lets handle view, edit and delete separately. CRM-4418
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('edit event participants')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviEvent')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $statusTypes = CRM_Event_PseudoConstant::participantStatus();
     $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
     $participantRoles = CRM_Event_PseudoConstant::participantRole();
     $sep = CRM_Core_DAO::VALUE_SEPARATOR;
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach (self::$_properties as $property) {
             if (isset($result->{$property})) {
                 $row[$property] = $result->{$property};
             }
         }
         //carry campaign on selectors.
         $row['campaign'] = CRM_Utils_Array::value($result->participant_campaign_id, $allCampaigns);
         $row['campaign_id'] = $result->participant_campaign_id;
         // gross hack to show extra information for pending status
         $statusClass = NULL;
         if (isset($row['participant_status_id']) && ($statusId = array_search($row['participant_status_id'], $statusTypes))) {
             $statusClass = $statusClasses[$statusId];
         }
         $row['showConfirmUrl'] = $statusClass == 'Pending' ? TRUE : FALSE;
         if (!empty($row['participant_is_test'])) {
             $row['participant_status'] .= ' (' . ts('test') . ')';
         }
         $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
         $links = self::links($this->_key, $this->_context, $this->_compContext);
         if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Payment'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Payment'));
         }
         if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
             $links[CRM_Core_Action::ADD] = array('name' => ts('Record Refund'), 'url' => 'civicrm/payment', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event', 'title' => ts('Record Refund'));
         }
         $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->participant_id, 'cid' => $result->contact_id, 'cxt' => $this->_context), ts('more'), FALSE, 'participant.selector.row', 'Participant', $result->participant_id);
         $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id);
         $row['paid'] = CRM_Event_BAO_Event::isMonetary($row['event_id']);
         if (!empty($row['participant_fee_level'])) {
             CRM_Event_BAO_Participant::fixEventLevel($row['participant_fee_level']);
         }
         if (CRM_Event_BAO_Event::usesPriceSet($row['event_id'])) {
             // add line item details if applicable
             $lineItems[$row['participant_id']] = CRM_Price_BAO_LineItem::getLineItems($row['participant_id']);
         }
         if (!empty($row['participant_role_id'])) {
             $viewRoles = array();
             foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
                 $viewRoles[] = $participantRoles[$v];
             }
             $row['participant_role_id'] = implode(', ', $viewRoles);
         }
         $rows[] = $row;
     }
     CRM_Core_Selector_Controller::$_template->assign_by_ref('lineItems', $lineItems);
     return $rows;
 }
Exemplo n.º 13
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.');
             }
         }
     }
 }
Exemplo n.º 14
0
 /**
  * Update the DB record for this setting.
  *
  * @param string $name
  *   The simple name of the setting.
  * @param mixed $value
  *   The new value of the setting.
  */
 protected function setDb($name, $value)
 {
     if (\CRM_Core_BAO_Setting::isUpgradeFromPreFourOneAlpha1()) {
         // civicrm_setting table is not going to be present.
         return;
     }
     $fields = array();
     $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput(array($name => $value), $fields);
     //We haven't traditionally validated inputs to setItem, so this breaks things.
     //foreach ($fieldsToSet as $settingField => &$settingValue) {
     //  self::validateSetting($settingValue, $fields['values'][$settingField]);
     //}
     $metadata = $fields['values'][$name];
     $dao = new \CRM_Core_DAO_Setting();
     $dao->name = $name;
     $dao->domain_id = $this->domainId;
     if ($this->contactId) {
         $dao->contact_id = $this->contactId;
         $dao->is_domain = 0;
     } else {
         $dao->is_domain = 1;
     }
     $dao->find(TRUE);
     if (isset($metadata['on_change'])) {
         foreach ($metadata['on_change'] as $callback) {
             call_user_func(\Civi\Core\Resolver::singleton()->get($callback), unserialize($dao->value), $value, $metadata, $this->domainId);
         }
     }
     if (\CRM_Utils_System::isNull($value)) {
         $dao->value = 'null';
     } else {
         $dao->value = serialize($value);
     }
     $dao->created_date = \CRM_Utils_Time::getTime('Ymdhis');
     $session = \CRM_Core_Session::singleton();
     if (\CRM_Contact_BAO_Contact_Utils::isContactId($session->get('userID'))) {
         $dao->created_id = $session->get('userID');
     }
     $dao->save();
     $dao->free();
 }
Exemplo n.º 15
0
 /**
  * Function to authenticate pledge user during online payment.
  *
  * @access public
  *
  * @return None
  */
 public function authenticatePledgeUser()
 {
     //get the userChecksum and contact id
     $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
     $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     //get pledge status and contact id
     $pledgeValues = array();
     $pledgeParams = array('id' => $this->_values['pledge_id']);
     $returnProperties = array('contact_id', 'status_id');
     CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
     //get all status
     $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $validStatus = array(array_search('Pending', $allStatus), array_search('In Progress', $allStatus), array_search('Overdue', $allStatus));
     $validUser = FALSE;
     if ($this->_userID && $this->_userID == $pledgeValues['contact_id']) {
         //check for authenticated  user.
         $validUser = TRUE;
     } elseif ($userChecksum && $pledgeValues['contact_id']) {
         //check for anonymous user.
         $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
         //make sure cid is same as pledge contact id
         if ($validUser && $pledgeValues['contact_id'] != $contactID) {
             $validUser = FALSE;
         }
     }
     if (!$validUser) {
         CRM_Core_Error::fatal(ts("Oops. It looks like you have an incorrect or incomplete link (URL). Please make sure you've copied the entire link, and try again. Contact the site administrator if this error persists."));
     }
     //check for valid pledge status.
     if (!in_array($pledgeValues['status_id'], $validStatus)) {
         CRM_Core_Error::fatal(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', array(1 => CRM_Utils_Array::value($pledgeValues['status_id'], $allStatus))));
     }
 }
Exemplo n.º 16
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');
         }
     }
 }
Exemplo n.º 17
0
 /**
  * Get contact if for a form object. Prioritise
  *   - cid in URL if 0 (on behalf on someoneelse)
  *      (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
  *   - logged in user id if it matches the one in the cid in the URL
  *   - contact id validated from a checksum from a checksum
  *   - cid from the url if the caller has ACL permission to view
  *   - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
  *
  * @return NULL|int
  */
 protected function setContactID()
 {
     $tempID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     if (isset($this->_params) && isset($this->_params['select_contact_id'])) {
         $tempID = $this->_params['select_contact_id'];
     }
     if (isset($this->_params, $this->_params[0]) && !empty($this->_params[0]['select_contact_id'])) {
         // event form stores as an indexed array, contribution form not so much...
         $tempID = $this->_params[0]['select_contact_id'];
     }
     // force to ignore the authenticated user
     if ($tempID === '0' || $tempID === 0) {
         // we set the cid on the form so that this will be retained for the Confirm page
         // in the multi-page form & prevent us returning the $userID when this is called
         // from that page
         // we don't really need to set it when $tempID is set because the params have that stored
         $this->set('cid', 0);
         CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
         return (int) $tempID;
     }
     $userID = $this->getLoggedInUserContactID();
     if (!is_null($tempID) && $tempID === $userID) {
         CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
         return (int) $userID;
     }
     //check if this is a checksum authentication
     $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
     if ($userChecksum) {
         //check for anonymous user.
         $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
         if ($validUser) {
             CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
             CRM_Core_Resources::singleton()->addVars('coreForm', array('checksum' => (int) $tempID));
             return $tempID;
         }
     } elseif ($tempID && CRM_Contact_BAO_Contact_Permission::allow($tempID)) {
         CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
         return $tempID;
     }
     if (is_numeric($userID)) {
         CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $userID));
     }
     return is_numeric($userID) ? $userID : NULL;
 }
Exemplo n.º 18
0
 /**
  * @param $rows
  */
 function addActions(&$rows)
 {
     $config = CRM_Core_Config::singleton();
     $permissions = array(CRM_Core_Permission::getPermission());
     if (CRM_Core_Permission::check('delete contacts')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     // mask value to hide map link if there are not lat/long
     $mapMask = $mask & 4095;
     // mask value to hide map link if there are not lat/long
     $mapMask = $mask & 4095;
     $links = self::links($this->_context, $this->_contextMenu, $this->_key);
     foreach ($rows as $id => &$row) {
         if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')) {
             $links = array(array('name' => ts('View'), 'url' => 'civicrm/contact/view', 'qs' => 'reset=1&cid=%%id%%', 'class' => 'no-popup', 'title' => ts('View Contact Details')), array('name' => ts('Restore'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&restore=1', 'title' => ts('Restore Contact')));
             if (CRM_Core_Permission::check('delete contacts')) {
                 $links[] = array('name' => ts('Delete Permanently'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1', 'title' => ts('Permanently Delete Contact'));
             }
             $row['action'] = CRM_Core_Action::formLink($links, null, array('id' => $row['contact_id']), ts('more'), FALSE, 'contact.selector.actions', 'Contact', $row['contact_id']);
         } elseif (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && !empty($row['city']) && CRM_Utils_Array::value('state_province', $row)) {
             $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $row['contact_id']), ts('more'), FALSE, 'contact.selector.actions', 'Contact', $row['contact_id']);
         } else {
             $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $row['contact_id']), ts('more'), FALSE, 'contact.selector.actions', 'Contact', $row['contact_id']);
         }
         // allow components to add more actions
         CRM_Core_Component::searchAction($row, $row['contact_id']);
         if (!empty($row['contact_type_orig'])) {
             $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'], FALSE, $row['contact_id']);
         }
     }
 }
 /**
  * Set default values for the form.
  *
  * @param CRM_Core_Form $form
  * @param array $defaults
  */
 public static function setDefaultValues(&$form, &$defaults)
 {
     if (!empty($defaults['preferred_language'])) {
         $languages = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
         $defaults['preferred_language'] = CRM_Utils_Array::key($defaults['preferred_language'], $languages);
     }
     // CRM-7119: set preferred_language to default if unset
     if (empty($defaults['preferred_language'])) {
         $config = CRM_Core_Config::singleton();
         $defaults['preferred_language'] = $config->lcMessages;
     }
     if (empty($defaults['communication_style_id'])) {
         $defaults['communication_style_id'] = array_pop(CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1'));
     }
     // CRM-17778 -- set preferred_mail_format to default if unset
     if (empty($defaults['preferred_mail_format'])) {
         $defaults['preferred_mail_format'] = 'Both';
     } else {
         $defaults['preferred_mail_format'] = array_search($defaults['preferred_mail_format'], CRM_Core_SelectValues::pmf());
     }
     //set default from greeting types CRM-4575, CRM-9739
     if ($form->_action & CRM_Core_Action::ADD) {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             if (empty($defaults[$greeting . '_id'])) {
                 if ($defaultGreetingTypeId = CRM_Contact_BAO_Contact_Utils::defaultGreeting($form->_contactType, $greeting)) {
                     $defaults[$greeting . '_id'] = $defaultGreetingTypeId;
                 }
             }
         }
     } else {
         foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
             $name = "{$greeting}_display";
             $form->assign($name, CRM_Utils_Array::value($name, $defaults));
         }
     }
 }
Exemplo n.º 20
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values, $doGeocodeAddress = false)
 {
     $config =& CRM_Core_Config::singleton();
     $this->_unparsedStreetAddressContacts = array();
     if (!$doGeocodeAddress) {
         // CRM-5854, reset the geocode method to null to prevent geocoding
         $config->geocodeMethod = null;
     }
     // first make sure this is a valid line
     //$this->_updateWithId = false;
     $response = $this->summary($values);
     $statusFieldName = $this->_statusFieldName;
     if ($response != CRM_Import_Parser::VALID) {
         $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})");
         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('contact_type' => $this->_contactType);
     static $contactFields = null;
     if ($contactFields == null) {
         require_once "CRM/Contact/DAO/Contact.php";
         $contactFields =& CRM_Contact_DAO_Contact::import();
     }
     //check if external identifier exists in database
     if (CRM_Utils_Array::value('external_identifier', $params) && (CRM_Utils_Array::value('id', $params) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) {
         require_once "CRM/Contact/BAO/Contact.php";
         if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             if ($internalCid != CRM_Utils_Array::value('id', $params)) {
                 $errorMessage = ts('External Identifier already exists in database.');
                 array_unshift($values, $errorMessage);
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if (!empty($this->_contactSubType)) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) {
         if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, false, 'label')) {
             $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, false, null);
             $params['contact_sub_type'] = array_search($subType, $subTypes);
         } elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) {
             $message = "Mismatched or Invalid Contact SubType.";
             array_unshift($values, $message);
             return CRM_Import_Parser::NO_MATCH;
         }
     }
     //get contact id to format common data in update/fill mode,
     //if external identifier is present, CRM-4423
     if ($this->_updateWithId && !CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
         if ($cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
             $formatted['id'] = $cid;
         }
     }
     //format common data, CRM-4062
     $this->formatCommonData($params, $formatted, $contactFields);
     $relationship = false;
     $createNewContact = true;
     // Support Match and Update Via Contact ID
     if ($this->_updateWithId) {
         $createNewContact = false;
         if (!CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
             if ($cid) {
                 $params['id'] = $cid;
             } else {
                 //update contact if dedupe found contact id, CRM-4148
                 $dedupeParams = $formatted;
                 //special case to check dedupe if external id present.
                 //if we send external id dedupe will stop.
                 unset($dedupeParams['external_identifier']);
                 $checkDedupe = _civicrm_duplicate_formatted_contact($dedupeParams);
                 if (civicrm_duplicate($checkDedupe)) {
                     $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
                     if (count($matchingContactIds) == 1) {
                         $params['id'] = array_pop($matchingContactIds);
                     } else {
                         $message = "More than one matching contact found for given criteria.";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     $createNewContact = true;
                 }
             }
         }
         $error = _civicrm_duplicate_formatted_contact($formatted);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 $updateflag = true;
                 foreach ($matchedIDs as $contactId) {
                     if ($params['id'] == $contactId) {
                         $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                         if ($formatted['contact_type'] == $contactType) {
                             //validation of subtype for update mode
                             //CRM-5125
                             $contactSubType = null;
                             if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                                 $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                             }
                             if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                                 $message = "Mismatched contact SubTypes :";
                                 array_unshift($values, $message);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::NO_MATCH;
                             } else {
                                 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId, false);
                                 $updateflag = false;
                                 $this->_retCode = CRM_Import_Parser::VALID;
                             }
                         } else {
                             $message = "Mismatched contact Types :";
                             array_unshift($values, $message);
                             $updateflag = false;
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         }
                     }
                 }
                 if ($updateflag) {
                     $message = "Mismatched contact IDs OR Mismatched contact Types :";
                     array_unshift($values, $message);
                     $this->_retCode = CRM_Import_Parser::NO_MATCH;
                 }
             }
         } else {
             $contactType = null;
             if (CRM_Utils_Array::value('id', $params)) {
                 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
                 if ($contactType) {
                     if ($formatted['contact_type'] == $contactType) {
                         //validation of subtype for update mode
                         //CRM-5125
                         $contactSubType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $params)) {
                             $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
                         }
                         if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
                             $message = "Mismatched contact SubTypes :";
                             array_unshift($values, $message);
                             $this->_retCode = CRM_Import_Parser::NO_MATCH;
                         } else {
                             $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], false);
                             $this->_retCode = CRM_Import_Parser::VALID;
                         }
                     } else {
                         $message = "Mismatched contact Types :";
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 } else {
                     // we should avoid multiple errors for single record
                     // since we have already retCode and we trying to force again.
                     if ($this->_retCode != CRM_Import_Parser::NO_MATCH) {
                         $message = "No contact found for this contact ID:" . $params['id'];
                         array_unshift($values, $message);
                         $this->_retCode = CRM_Import_Parser::NO_MATCH;
                     }
                 }
             } else {
                 //CRM-4148
                 //now we want to create new contact on update/fill also.
                 $createNewContact = true;
             }
         }
         if (is_a($newContact, 'CRM_Contact_BAO_Contact')) {
             $relationship = true;
         } else {
             if (is_a($error, 'CRM_Core_Error')) {
                 $newContact = $error;
                 $relationship = true;
             }
         }
     }
     //fixed CRM-4148
     //now we create new contact in update/fill mode also.
     if ($createNewContact) {
         //CRM-4430, don't carry if not submitted.
         foreach (array('prefix', 'suffix', 'gender') as $name) {
             if (array_key_exists($name, $formatted)) {
                 if (in_array($name, array('prefix', 'suffix'))) {
                     $formattedName = "individual_{$name}";
                     $formatted[$formattedName] = CRM_Core_OptionGroup::getValue($formattedName, (string) $formatted[$name]);
                 } else {
                     $formatted[$name] = CRM_Core_OptionGroup::getValue($name, (string) $formatted[$name]);
                 }
             }
         }
         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate);
     }
     if (is_object($newContact) || $newContact instanceof CRM_Contact_BAO_Contact) {
         $relationship = true;
         $newContact = clone $newContact;
         $this->_newContacts[] = $newContact->id;
         //get return code if we create new contact in update mode, CRM-4148
         if ($this->_updateWithId) {
             $this->_retCode = CRM_Import_Parser::VALID;
         }
     } else {
         if (civicrm_duplicate($newContact)) {
             $relationship = true;
             $contactID = $newContact['error_message']['params'][0];
             if (!in_array($contactID, $this->_newContacts)) {
                 $this->_newContacts[] = $contactID;
             }
         }
     }
     if ($relationship) {
         $primaryContactId = null;
         if (civicrm_duplicate($newContact)) {
             if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) {
                 $primaryContactId = $newContact['error_message']['params'][0];
             }
         } else {
             $primaryContactId = $newContact->id;
         }
         if ((civicrm_duplicate($newContact) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) {
             //relationship contact insert
             foreach ($params as $key => $field) {
                 list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3);
                 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
                     continue;
                 }
                 $relationType = new CRM_Contact_DAO_RelationshipType();
                 $relationType->id = $id;
                 $relationType->find(true);
                 $direction = "contact_sub_type_{$second}";
                 $formatting = array('contact_type' => $params[$key]['contact_type']);
                 //set subtype for related contact CRM-5125
                 if (isset($relationType->{$direction})) {
                     //validation of related contact subtype for update mode
                     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->{$direction}) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $formatting['contact_sub_type'] = $relationType->{$direction};
                     }
                 }
                 $relationType->free();
                 $contactFields = null;
                 $contactFields = CRM_Contact_DAO_Contact::import();
                 //Relation on the basis of External Identifier.
                 if (!CRM_Utils_Array::value('id', $params[$key]) && isset($params[$key]['external_identifier'])) {
                     $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier');
                 }
                 // check for valid related contact id in update/fill mode, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL)) && CRM_Utils_Array::value('id', $params[$key])) {
                     $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type');
                     if (!$relatedContactType) {
                         $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id']));
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         //validation of related contact subtype for update mode
                         //CRM-5125
                         $relatedCsType = null;
                         if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                             $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type');
                         }
                         if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                             $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact ID: %1", array(1 => $params[$key]['id']));
                             array_unshift($values, $errorMessage);
                             return CRM_Import_Parser::NO_MATCH;
                         } else {
                             // get related contact id to format data in update/fill mode,
                             //if external identifier is present, CRM-4423
                             $formatting['id'] = $params[$key]['id'];
                         }
                     }
                 }
                 //format common data, CRM-4062
                 $this->formatCommonData($field, $formatting, $contactFields);
                 //fixed for CRM-4148
                 if ($params[$key]['id']) {
                     $contact = array('contact_id' => $params[$key]['id']);
                     $defaults = array();
                     $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
                 } else {
                     $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, null, false);
                 }
                 if (is_object($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     $relatedNewContact = clone $relatedNewContact;
                 }
                 $matchedIDs = array();
                 // To update/fill contact, get the matching contact Ids if duplicate contact found
                 // otherwise get contact Id from object of related contact
                 if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) {
                     if (civicrm_duplicate($relatedNewContact)) {
                         $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]);
                     } else {
                         $errorMessage = $relatedNewContact['error_message'];
                         array_unshift($values, $errorMessage);
                         $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                         return CRM_Import_Parser::ERROR;
                     }
                 } else {
                     $matchedIDs[] = $relatedNewContact->id;
                 }
                 // update/fill related contact after getting matching Contact Ids, CRM-4424
                 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) {
                     //validation of related contact subtype for update mode
                     //CRM-5125
                     $relatedCsType = null;
                     if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
                         $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type');
                     }
                     if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
                         $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
                         array_unshift($values, $errorMessage);
                         return CRM_Import_Parser::NO_MATCH;
                     } else {
                         $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]);
                     }
                 }
                 static $relativeContact = array();
                 if (civicrm_duplicate($relatedNewContact)) {
                     if (count($matchedIDs) >= 1) {
                         $relContactId = $matchedIDs[0];
                         //add relative contact to count during update & fill mode.
                         //logic to make count distinct by contact id.
                         if ($this->_newRelatedContacts || !empty($relativeContact)) {
                             $reContact = array_keys($relativeContact, $relContactId);
                             if (empty($reContact)) {
                                 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                             }
                         } else {
                             $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                         }
                     }
                 } else {
                     $relContactId = $relatedNewContact->id;
                     $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
                 }
                 if (civicrm_duplicate($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) {
                     //fix for CRM-1993.Checks for duplicate related contacts
                     if (count($matchedIDs) >= 1) {
                         //if more than one duplicate contact
                         //found, create relationship with first contact
                         // now create the relationship record
                         $relationParams = array();
                         $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1), 'is_active' => 1, 'skipRecentView' => true);
                         // we only handle related contact success, we ignore failures for now
                         // at some point wold be nice to have related counts as separate
                         $relationIds = array('contact' => $primaryContactId);
                         list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
                         CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds);
                         //handle current employer, CRM-3532
                         if ($valid) {
                             require_once 'CRM/Core/PseudoConstant.php';
                             $allRelationships = CRM_Core_PseudoConstant::relationshipType('name');
                             $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $key);
                             $relationshipType = str_replace($relationshipTypeId . '_', '', $key);
                             $orgId = $individualId = null;
                             if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') {
                                 $orgId = $relContactId;
                                 $individualId = $primaryContactId;
                             } else {
                                 if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
                                     $orgId = $primaryContactId;
                                     $individualId = $relContactId;
                                 }
                             }
                             if ($orgId && $individualId) {
                                 $currentEmpParams[$individualId] = $orgId;
                                 require_once 'CRM/Contact/BAO/Contact/Utils.php';
                                 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($this->_updateWithId) {
         //return warning if street address is unparsed, CRM-5886
         return $this->processMessage($values, $statusFieldName, $this->_retCode);
     }
     //dupe checking
     if (is_array($newContact) && civicrm_error($newContact)) {
         $code = null;
         if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && $code == CRM_Core_Error::DUPLICATE_CONTACT) {
             $urls = array();
             // need to fix at some stage and decide if the error will return an
             // array or string, crude hack for now
             if (is_array($newContact['error_message']['params'][0])) {
                 $cids = $newContact['error_message']['params'][0];
             } else {
                 $cids = explode(',', $newContact['error_message']['params'][0]);
             }
             foreach ($cids as $cid) {
                 $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true);
             }
             $url_string = implode("\n", $urls);
             // If we duplicate more than one record, skip no matter what
             if (count($cids) > 1) {
                 $errorMessage = ts('Record duplicates multiple contacts');
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 //combine error msg to avoid mismatch between error file columns.
                 $errorMessage .= "\n" . $url_string;
                 array_unshift($values, $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
             // Params only had one id, so shift it out
             $contactId = array_shift($cids);
             $cid = null;
             $vals = array('contact_id' => $contactId);
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) {
                 $result = civicrm_replace_contact_formatted($contactId, $formatted, $contactFields);
                 $cid = $result['result'];
             } else {
                 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                     $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                 } else {
                     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                         $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
                     }
                 }
             }
             // else skip does nothing and just returns an error code.
             if ($cid) {
                 $contact = array('contact_id' => $cid);
                 $defaults = array();
                 $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
             }
             if (civicrm_error($newContact)) {
                 $contactID = $newContact['error_message']['params'][0];
                 if (!in_array($contactID, $this->_newContacts)) {
                     $this->_newContacts[] = $contactID;
                 }
             }
             //CRM-262 No Duplicate Checking
             if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
                 array_unshift($values, $url_string);
                 $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => "Skipping duplicate record");
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::DUPLICATE;
             }
             $importRecordParams = array($statusFieldName => 'IMPORTED');
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             //return warning if street address is not parsed, CRM-5886
             return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
         } else {
             // Not a dupe, so we had an error
             $errorMessage = $newContact['error_message'];
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::ERROR;
         }
     }
     // sleep(3);
     return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
 }
Exemplo n.º 21
0
 /**
  * Test case for getDisplayAndImage( ).
  */
 public function testGetDisplayAndImage()
 {
     //get the contact params
     $params = $this->contactParams();
     //create contact
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contactId = $contact->id;
     //get DisplayAndImage.
     list($displayName, $image) = CRM_Contact_BAO_Contact::getDisplayAndImage($contactId);
     $checkImage = CRM_Contact_BAO_Contact_Utils::getImage($params['contact_type'], FALSE, $contactId);
     $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
     $suffix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
     //build display name
     $paramsDisplayName = $prefix[$params['prefix_id']] . ' ' . $params['first_name'] . ' ' . $params['last_name'] . ' ' . $suffix[$params['suffix_id']];
     $this->assertEquals($displayName, $paramsDisplayName, 'Check For Display Name');
     $this->assertEquals($image, $checkImage, 'Check For Image');
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
 }
Exemplo n.º 22
0
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     // Process / save address
     $params['contact_id'] = $this->_contactId;
     $params['updateBlankLocInfo'] = TRUE;
     // process shared contact address.
     CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
     if ($this->_parseStreetAddress) {
         CRM_Contact_Form_Contact::parseAddress($params);
     }
     if ($this->_addressId > 0) {
         $params['address'][$this->_locBlockNo]['id'] = $this->_addressId;
     }
     // save address changes
     $address = CRM_Core_BAO_Address::create($params, TRUE);
     $this->log();
     $this->ajaxResponse['addressId'] = $address[0]->id;
     $this->response();
 }
 /**
  * Get the subscription URL.
  *
  * @param int $entityID
  * @param null $entity
  * @param string $action
  *
  * @return string
  */
 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel')
 {
     $url = parent::subscriptionURL($entityID, $entity, $action);
     if (!isset($url)) {
         return NULL;
     }
     if (stristr($url, '&cs=')) {
         return $url;
     }
     $user_id = CRM_Core_Session::singleton()->get('userID');
     $contact_id = $this->getContactID($entity, $entityID);
     if ($contact_id && $user_id != $contact_id) {
         return $url . '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contact_id, NULL, 'inf');
     }
     return $url;
 }
Exemplo n.º 24
0
 /**
  * @return mixed
  */
 function getContactID()
 {
     //XXX when do we query 'cid' ?
     $tempID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     //check if this is a checksum authentication
     $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
     if ($userChecksum) {
         //check for anonymous user.
         $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
         if ($validUser) {
             return $tempID;
         }
     }
     // check if the user is registered and we have a contact ID
     $session = CRM_Core_Session::singleton();
     return $session->get('userID');
 }
Exemplo n.º 25
0
 /**
  * Retrieve cases related to particular contact or whole contact
  * used in Dashboad and Tab
  *
  * @param boolean $allCases
  *
  * @param int $userID
  *
  * @param String $type /upcoming,recent,all/
  *
  * @param string $context
  *
  * @return array     Array of Cases
  *
  * @access public
  */
 static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard')
 {
     $condition = NULL;
     $casesList = array();
     //validate access for own cases.
     if (!self::accessCiviCase()) {
         return $casesList;
     }
     if (!$userID) {
         $session = CRM_Core_Session::singleton();
         $userID = $session->get('userID');
     }
     //validate access for all cases.
     if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
         $allCases = FALSE;
     }
     $condition = " AND civicrm_case.is_deleted = 0 ";
     if (!$allCases) {
         $condition .= " AND case_relationship.contact_id_b = {$userID} ";
     }
     if ($type == 'upcoming' || $type == 'any') {
         $closedId = CRM_Core_OptionGroup::getValue('case_status', 'Closed', 'name');
         $condition .= "\nAND civicrm_case.status_id != {$closedId}";
     }
     $query = self::getCaseActivityQuery($type, $userID, $condition);
     $queryParams = array();
     $result = CRM_Core_DAO::executeQuery($query, $queryParams);
     $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
     $resultFields = array('contact_id', 'contact_type', 'sort_name', 'phone', 'case_id', 'case_subject', 'case_type', 'case_type_id', 'status_id', 'case_status', 'case_status_name', 'activity_type_id', 'case_start_date', 'case_role');
     if ($type == 'upcoming') {
         $resultFields[] = 'case_scheduled_activity_date';
         $resultFields[] = 'case_scheduled_activity_type_name';
         $resultFields[] = 'case_scheduled_activity_type';
         $resultFields[] = 'case_scheduled_activity_id';
     } elseif ($type == 'recent') {
         $resultFields[] = 'case_recent_activity_date';
         $resultFields[] = 'case_recent_activity_type_name';
         $resultFields[] = 'case_recent_activity_type';
         $resultFields[] = 'case_recent_activity_id';
     } elseif ($type == 'any') {
         $resultFields[] = 'case_activity_date';
         $resultFields[] = 'case_activity_type_name';
         $resultFields[] = 'case_activity_type';
         $resultFields[] = 'case_activity_id';
     }
     // we're going to use the usual actions, so doesn't make sense to duplicate definitions
     $actions = CRM_Case_Selector_Search::links();
     // check is the user has view/edit signer permission
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('access all cases and activities') || !$allCases && CRM_Core_Permission::check('access my cases and activities')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviCase')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     while ($result->fetch()) {
         foreach ($resultFields as $donCare => $field) {
             $casesList[$result->case_id][$field] = $result->{$field};
             if ($field == 'contact_type') {
                 $casesList[$result->case_id]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type);
                 $casesList[$result->case_id]['action'] = CRM_Core_Action::formLink($actions['primaryActions'], $mask, array('id' => $result->case_id, 'cid' => $result->contact_id, 'cxt' => $context), ts('more'), FALSE, 'case.actions.primary', 'Case', $result->case_id);
                 $casesList[$result->case_id]['moreActions'] = CRM_Core_Action::formLink($actions['moreActions'], $mask, array('id' => $result->case_id, 'cid' => $result->contact_id, 'cxt' => $context), ts('more'), TRUE, 'case.actions.more', 'Case', $result->case_id);
             } elseif ($field == 'case_status') {
                 if (in_array($result->{$field}, $caseStatus)) {
                     $casesList[$result->case_id]['class'] = "status-urgent";
                 } else {
                     $casesList[$result->case_id]['class'] = "status-normal";
                 }
             }
         }
         //CRM-4510.
         $caseTypes = CRM_Case_PseudoConstant::caseType('name');
         $caseManagerContact = self::getCaseManagerContact($caseTypes[$result->case_type_id], $result->case_id);
         if (!empty($caseManagerContact)) {
             $casesList[$result->case_id]['casemanager_id'] = CRM_Utils_Array::value('casemanager_id', $caseManagerContact);
             $casesList[$result->case_id]['casemanager'] = CRM_Utils_Array::value('casemanager', $caseManagerContact);
         }
         //do check user permissions for edit/view activity.
         if (($actId = CRM_Utils_Array::value('case_scheduled_activity_id', $casesList[$result->case_id])) || ($actId = CRM_Utils_Array::value('case_recent_activity_id', $casesList[$result->case_id]))) {
             $casesList[$result->case_id]["case_{$type}_activity_editable"] = self::checkPermission($actId, 'edit', $casesList[$result->case_id]['activity_type_id'], $userID);
             $casesList[$result->case_id]["case_{$type}_activity_viewable"] = self::checkPermission($actId, 'view', $casesList[$result->case_id]['activity_type_id'], $userID);
         }
     }
     return $casesList;
 }
Exemplo n.º 26
0
 /**
  * Set default values for address block.
  *
  * @param array $defaults
  *   Defaults associated array.
  * @param CRM_Core_Form $form
  *   Form object.
  */
 public static function setDefaultValues(&$defaults, &$form)
 {
     $addressValues = array();
     if (isset($defaults['address']) && is_array($defaults['address']) && !CRM_Utils_System::isNull($defaults['address'])) {
         // start of contact shared adddress defaults
         $sharedAddresses = array();
         $masterAddress = array();
         // get contact name of shared contact names
         $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
         foreach ($defaults['address'] as $key => $addressValue) {
             if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
                 $master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id'];
                 $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'], 'options' => CRM_Core_BAO_Address::getValues(array('entity_id' => $master_cid, 'contact_id' => $master_cid)), 'master_id' => $addressValue['master_id']);
                 $defaults['address'][$key]['master_contact_id'] = $master_cid;
             } else {
                 $defaults['address'][$key]['use_shared_address'] = 0;
             }
             //check if any address is shared by any other contacts
             $masterAddress[$key] = CRM_Core_BAO_Address::checkContactSharedAddress($addressValue['id']);
         }
         $form->assign('sharedAddresses', $sharedAddresses);
         $form->assign('masterAddress', $masterAddress);
         // end of shared address defaults
         // start of parse address functionality
         // build street address, CRM-5450.
         if ($form->_parseStreetAddress) {
             $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
             foreach ($defaults['address'] as $cnt => &$address) {
                 $streetAddress = NULL;
                 foreach (array('street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
                     if (in_array($fld, array('street_name', 'street_unit'))) {
                         $streetAddress .= ' ';
                     }
                     $streetAddress .= CRM_Utils_Array::value($fld, $address);
                 }
                 $streetAddress = trim($streetAddress);
                 if (!empty($streetAddress)) {
                     $address['street_address'] = $streetAddress;
                 }
                 if (isset($address['street_number'])) {
                     $address['street_number'] .= CRM_Utils_Array::value('street_number_suffix', $address);
                 }
                 // build array for set default.
                 foreach ($parseFields as $field) {
                     $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address);
                 }
                 // don't load fields, use js to populate.
                 foreach (array('street_number', 'street_name', 'street_unit') as $f) {
                     if (isset($address[$f])) {
                         unset($address[$f]);
                     }
                 }
             }
             $form->assign('allAddressFieldValues', json_encode($addressValues));
             //hack to handle show/hide address fields.
             $parsedAddress = array();
             if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])) {
                 foreach ($_POST['address'] as $cnt => $values) {
                     $showField = 'streetAddress';
                     foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
                         if (!empty($values[$fld])) {
                             $showField = 'addressElements';
                             break;
                         }
                     }
                     $parsedAddress[$cnt] = $showField;
                 }
             }
             $form->assign('showHideAddressFields', $parsedAddress);
             $form->assign('loadShowHideAddressFields', empty($parsedAddress) ? FALSE : TRUE);
         }
         // end of parse address functionality
     }
 }
Exemplo n.º 27
0
 /**
  * @param int $contactID
  * @param CRM_Core_Form $form
  * @param bool $redirect
  *
  * @return bool
  */
 public static function validateOnlyChecksum($contactID, &$form, $redirect = TRUE)
 {
     // check if this is of the format cs=XXX
     if (!CRM_Contact_BAO_Contact_Utils::validChecksum($contactID, CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE))) {
         if ($redirect) {
             // also set a message in the UF framework
             $message = ts('You do not have permission to edit this contact record. Contact the site administrator if you need assistance.');
             CRM_Utils_System::setUFMessage($message);
             $config = CRM_Core_Config::singleton();
             CRM_Core_Error::statusBounce($message, $config->userFrameworkBaseURL);
             // does not come here, we redirect in the above statement
         }
         return FALSE;
     }
     // set appropriate AUTH source
     self::initChecksumAuthSrc(TRUE, $form);
     // so here the contact is posing as $contactID, lets set the logging contact ID variable
     // CRM-8965
     CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1', array(1 => array($contactID, 'Integer')));
     return TRUE;
 }
Exemplo n.º 28
0
 /**
  * @param $token
  * @param $contact
  * @param bool $html
  * @param bool $returnBlankToken
  * @param bool $escapeSmarty
  *
  * @return bool|mixed|null|string
  */
 public static function getContactTokenReplacement($token, &$contact, $html = FALSE, $returnBlankToken = FALSE, $escapeSmarty = FALSE)
 {
     if (self::$_tokens['contact'] == NULL) {
         /* This should come from UF */
         self::$_tokens['contact'] = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields('All')), array('checksum', 'contact_id'));
     }
     // Construct value from $token and $contact
     $value = NULL;
     $noReplace = FALSE;
     // Support legacy tokens
     $token = CRM_Utils_Array::value($token, self::legacyContactTokens(), $token);
     // check if the token we were passed is valid
     // we have to do this because this function is
     // called only when we find a token in the string
     if (!in_array($token, self::$_tokens['contact'])) {
         $noReplace = TRUE;
     } elseif ($token == 'checksum') {
         $hash = CRM_Utils_Array::value('hash', $contact);
         $contactID = CRM_Utils_Array::retrieveValueRecursive($contact, 'contact_id');
         $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, NULL, $hash);
         $value = "cs={$cs}";
     } else {
         $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token);
         // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
         if (is_array($value)) {
             $value = $value[1];
         } elseif ($value && is_numeric($value)) {
             $allFields = CRM_Contact_BAO_Contact::exportableFields('All');
             if (!empty($allFields[$token]['pseudoconstant'])) {
                 $value = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $token, $value);
             }
         }
     }
     if (!$html) {
         $value = str_replace('&amp;', '&', $value);
     }
     // if null then return actual token
     if ($returnBlankToken && !$value) {
         $noReplace = TRUE;
     }
     if ($noReplace) {
         $value = "{contact.{$token}}";
     }
     if ($escapeSmarty && !($returnBlankToken && $noReplace)) {
         // $returnBlankToken means the caller wants to do further attempts at
         // processing unreplaced tokens -- so don't escape them yet in this case.
         $value = self::tokenEscapeSmarty($value);
     }
     return $value;
 }
Exemplo n.º 29
0
 /**
  * Returns all the rows in the given offset and rowCount.
  *
  * @param string $action
  *   The action being performed.
  * @param int $offset
  *   The row number to start from.
  * @param int $rowCount
  *   The number of rows to return.
  * @param string $sort
  *   The sql string that describes the sort order.
  * @param string $output
  *   What should the result set include (web/email/csv).
  *
  * @return array
  *   rows in the given offset and rowCount
  */
 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_activityClause);
     $rows = array();
     $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
     $accessCiviMail = CRM_Core_Permission::check('access CiviMail');
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     $engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     //get all activity types
     $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
     while ($result->fetch()) {
         $row = array();
         // ignore rows where we dont have an activity id
         if (empty($result->activity_id)) {
             continue;
         }
         // the columns we are interested in
         foreach (self::$_properties as $property) {
             if (isset($result->{$property})) {
                 $row[$property] = $result->{$property};
             }
         }
         $contactId = CRM_Utils_Array::value('contact_id', $row);
         if (!$contactId) {
             $contactId = CRM_Utils_Array::value('source_contact_id', $row);
         }
         $row['target_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $targetID);
         $row['assignee_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $assigneeID);
         list($row['source_contact_name'], $row['source_contact_id']) = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $sourceID, TRUE);
         $row['source_contact_name'] = implode(',', array_values($row['source_contact_name']));
         $row['source_contact_id'] = implode(',', $row['source_contact_id']);
         if ($this->_context == 'search') {
             $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->activity_id;
         }
         $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id);
         $accessMailingReport = FALSE;
         $activityTypeId = $row['activity_type_id'];
         if ($row['activity_is_test']) {
             $row['activity_type'] = $row['activity_type'] . " (test)";
         }
         $bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes);
         $row['mailingId'] = '';
         if ($accessCiviMail && ($mailingIDs === TRUE || in_array($result->source_record_id, $mailingIDs)) && $bulkActivityTypeID == $activityTypeId) {
             $row['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report', "mid={$result->source_record_id}&reset=1&cid={$contactId}&context=activitySelector");
             $row['recipients'] = ts('(recipients)');
             $row['target_contact_name'] = '';
             $row['assignee_contact_name'] = '';
             $accessMailingReport = TRUE;
         }
         $activityActions = new CRM_Activity_Selector_Activity($result->contact_id, NULL);
         $actionLinks = $activityActions->actionLinks($activityTypeId, CRM_Utils_Array::value('source_record_id', $row), $accessMailingReport, CRM_Utils_Array::value('activity_id', $row), $this->_key, $this->_compContext);
         $row['action'] = CRM_Core_Action::formLink($actionLinks, NULL, array('id' => $result->activity_id, 'cid' => $contactId, 'cxt' => $this->_context), ts('more'), FALSE, 'activity.selector.row', 'Activity', $result->activity_id);
         //carry campaign to selector.
         $row['campaign'] = CRM_Utils_Array::value($result->activity_campaign_id, $allCampaigns);
         $row['campaign_id'] = $result->activity_campaign_id;
         if ($engagementLevel = CRM_Utils_Array::value('activity_engagement_level', $row)) {
             $row['activity_engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
         }
         //Check if recurring activity
         $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity');
         $row['repeat'] = '';
         if ($repeat) {
             $row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
         }
         $rows[] = $row;
     }
     return $rows;
 }
Exemplo n.º 30
0
 /**
  * Retrieve list of duplicate pairs from cache table.
  */
 public static function getDedupes()
 {
     $offset = isset($_REQUEST['start']) ? CRM_Utils_Type::escape($_REQUEST['start'], 'Integer') : 0;
     $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type::escape($_REQUEST['length'], 'Integer') : 25;
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive');
     $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive');
     $selected = isset($_REQUEST['selected']) ? CRM_Utils_Type::escape($_REQUEST['selected'], 'Integer') : 0;
     if ($rowCount < 0) {
         $rowCount = 0;
     }
     $whereClause = $orderByClause = '';
     $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid);
     $searchRows = array();
     $searchParams = self::getSearchOptionsFromRequest();
     $queryParams = array();
     $join = '';
     $where = array();
     $isOrQuery = self::isOrQuery();
     $nextParamKey = 3;
     $mappings = array('dst' => 'cc1.display_name', 'src' => 'cc2.display_name', 'dst_email' => 'ce1.email', 'src_email' => 'ce2.email', 'dst_postcode' => 'ca1.postal_code', 'src_postcode' => 'ca2.postal_code', 'dst_street' => 'ca1.street', 'src_street' => 'ca2.street');
     foreach ($mappings as $key => $dbName) {
         if (!empty($searchParams[$key])) {
             $queryParams[$nextParamKey] = array('%' . $searchParams[$key] . '%', 'String');
             $where[] = $dbName . " LIKE %{$nextParamKey} ";
             $nextParamKey++;
         }
     }
     if ($isOrQuery) {
         $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
     } else {
         if (!empty($where)) {
             $whereClause = implode(' AND ', $where);
         }
     }
     $whereClause .= $whereClause ? ' AND de.id IS NULL' : ' de.id IS NULL';
     if ($selected) {
         $whereClause .= ' AND pn.is_selected = 1';
     }
     $join .= CRM_Dedupe_Merger::getJoinOnDedupeTable();
     $select = array('cc1.contact_type' => 'dst_contact_type', 'cc1.display_name' => 'dst_display_name', 'cc1.contact_sub_type' => 'dst_contact_sub_type', 'cc2.contact_type' => 'src_contact_type', 'cc2.display_name' => 'src_display_name', 'cc2.contact_sub_type' => 'src_contact_sub_type', 'ce1.email' => 'dst_email', 'ce2.email' => 'src_email', 'ca1.postal_code' => 'dst_postcode', 'ca2.postal_code' => 'src_postcode', 'ca1.street_address' => 'dst_street', 'ca2.street_address' => 'src_street');
     if ($select) {
         $join .= " INNER JOIN civicrm_contact cc1 ON cc1.id = pn.entity_id1";
         $join .= " INNER JOIN civicrm_contact cc2 ON cc2.id = pn.entity_id2";
         $join .= " LEFT JOIN civicrm_email ce1 ON (ce1.contact_id = pn.entity_id1 AND ce1.is_primary = 1 )";
         $join .= " LEFT JOIN civicrm_email ce2 ON (ce2.contact_id = pn.entity_id2 AND ce2.is_primary = 1 )";
         $join .= " LEFT JOIN civicrm_address ca1 ON (ca1.contact_id = pn.entity_id1 AND ca1.is_primary = 1 )";
         $join .= " LEFT JOIN civicrm_address ca2 ON (ca2.contact_id = pn.entity_id2 AND ca2.is_primary = 1 )";
     }
     $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
     if (!empty($_REQUEST['order'])) {
         foreach ($_REQUEST['order'] as $orderInfo) {
             if (!empty($orderInfo['column'])) {
                 $orderColumnNumber = $orderInfo['column'];
                 $dir = $orderInfo['dir'];
             }
         }
         $columnDetails = CRM_Utils_Array::value($orderColumnNumber, $_REQUEST['columns']);
     }
     if (!empty($columnDetails)) {
         switch ($columnDetails['data']) {
             case 'src':
                 $orderByClause = " ORDER BY cc2.display_name {$dir}";
                 break;
             case 'src_email':
                 $orderByClause = " ORDER BY ce2.email {$dir}";
                 break;
             case 'src_street':
                 $orderByClause = " ORDER BY ca2.street_address {$dir}";
                 break;
             case 'src_postcode':
                 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
                 break;
             case 'dst':
                 $orderByClause = " ORDER BY cc1.display_name {$dir}";
                 break;
             case 'dst_email':
                 $orderByClause = " ORDER BY ce1.email {$dir}";
                 break;
             case 'dst_street':
                 $orderByClause = " ORDER BY ca1.street_address {$dir}";
                 break;
             case 'dst_postcode':
                 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
                 break;
             default:
                 $orderByClause = " ORDER BY cc1.display_name ASC";
                 break;
         }
     }
     $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
     $iFilteredTotal = CRM_Core_DAO::singleValueQuery("SELECT FOUND_ROWS()");
     $count = 0;
     foreach ($dupePairs as $key => $pairInfo) {
         $pair = $pairInfo['data'];
         $srcContactSubType = CRM_Utils_Array::value('src_contact_sub_type', $pairInfo);
         $dstContactSubType = CRM_Utils_Array::value('dst_contact_sub_type', $pairInfo);
         $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($srcContactSubType ? $srcContactSubType : $pairInfo['src_contact_type'], FALSE, $pairInfo['entity_id2']);
         $dstTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($dstContactSubType ? $dstContactSubType : $pairInfo['dst_contact_type'], FALSE, $pairInfo['entity_id1']);
         $searchRows[$count]['is_selected'] = $pairInfo['is_selected'];
         $searchRows[$count]['is_selected_input'] = "<input type='checkbox' class='crm-dedupe-select' name='pnid_{$pairInfo['prevnext_id']}' value='{$pairInfo['is_selected']}' onclick='toggleDedupeSelect(this)'>";
         $searchRows[$count]['src_image'] = $srcTypeImage;
         $searchRows[$count]['src'] = CRM_Utils_System::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
         $searchRows[$count]['src_email'] = CRM_Utils_Array::value('src_email', $pairInfo);
         $searchRows[$count]['src_street'] = CRM_Utils_Array::value('src_street', $pairInfo);
         $searchRows[$count]['src_postcode'] = CRM_Utils_Array::value('src_postcode', $pairInfo);
         $searchRows[$count]['dst_image'] = $dstTypeImage;
         $searchRows[$count]['dst'] = CRM_Utils_System::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
         $searchRows[$count]['dst_email'] = CRM_Utils_Array::value('dst_email', $pairInfo);
         $searchRows[$count]['dst_street'] = CRM_Utils_Array::value('dst_street', $pairInfo);
         $searchRows[$count]['dst_postcode'] = CRM_Utils_Array::value('dst_postcode', $pairInfo);
         $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array::value('conflicts', $pair));
         $searchRows[$count]['weight'] = CRM_Utils_Array::value('weight', $pair);
         if (!empty($pairInfo['data']['canMerge'])) {
             $mergeParams = "reset=1&cid={$pairInfo['entity_id1']}&oid={$pairInfo['entity_id2']}&action=update&rgid={$rgid}&limit=" . CRM_Utils_Request::retrieve('limit', 'Integer');
             if ($gid) {
                 $mergeParams .= "&gid={$gid}";
             }
             $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a>&nbsp;|&nbsp;";
             $searchRows[$count]['actions'] .= CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
             $searchRows[$count]['actions'] .= "&nbsp;|&nbsp;<a id='notDuplicate' href='#' onClick=\"processDupes( {$pairInfo['entity_id1']}, {$pairInfo['entity_id2']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
         } else {
             $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
         }
         $count++;
     }
     $dupePairs = array('data' => $searchRows, 'recordsTotal' => $iTotal, 'recordsFiltered' => $iFilteredTotal);
     if (!empty($_REQUEST['is_unit_test'])) {
         return $dupePairs;
     }
     CRM_Utils_JSON::output($dupePairs);
 }