/**
  * Trigger a rule for this trigger
  *
  * @param $op
  * @param $objectName
  * @param $objectId
  * @param $objectRef
  */
 public function triggerTrigger($op, $objectName, $objectId, $objectRef)
 {
     $t = $this->getTriggerDataFromPost($op, $objectName, $objectId, $objectRef);
     //trigger for each client
     $clients = CRM_Case_BAO_Case::getCaseClients($objectId);
     foreach ($clients as $client) {
         $triggerData = clone $t;
         $triggerData->setEntityData('Relationship', null);
         $triggerData->setContactId($client);
         CRM_Civirules_Engine::triggerRule($this, $triggerData);
     }
     //trigger for each case role
     $relatedContacts = CRM_Case_BAO_Case::getRelatedContacts($objectId);
     foreach ($relatedContacts as $contact) {
         $triggerData = clone $t;
         $relationshipData = null;
         $relationship = new CRM_Contact_BAO_Relationship();
         $relationship->contact_id_b = $contact['contact_id'];
         $relationship->case_id = $objectId;
         if ($relationship->find(true)) {
             CRM_Core_DAO::storeValues($relationship, $relationshipData);
         }
         $triggerData->setEntityData('Relationship', $relationshipData);
         $triggerData->setContactId($contact['contact_id']);
         CRM_Civirules_Engine::triggerRule($this, $triggerData);
     }
 }
 /**
  * Add relationships from form.
  */
 public function addRelationships()
 {
     if (!is_array($this->_contactIds)) {
         // Could this really happen?
         return;
     }
     $relationshipTypeParts = explode('_', $this->params['relationship_type_id']);
     $params = array('relationship_type_id' => $relationshipTypeParts[0], 'is_active' => 1);
     $secondaryRelationshipSide = $relationshipTypeParts[1];
     $primaryRelationshipSide = $relationshipTypeParts[2];
     $primaryFieldName = 'contact_id_' . $primaryRelationshipSide;
     $secondaryFieldName = 'contact_id_' . $secondaryRelationshipSide;
     $relationshipLabel = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $params['relationship_type_id'], "label_{$secondaryRelationshipSide}_{$primaryRelationshipSide}");
     $params[$secondaryFieldName] = $this->_contactIds;
     $params[$primaryFieldName] = $this->params['contact_check'];
     $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $primaryRelationshipSide);
     $relatedContactName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$primaryFieldName], 'display_name');
     $status = array(ts('%count %2 %3 relationship created', array('count' => $outcome['valid'], 'plural' => '%count %2 %3 relationships created', 2 => $relationshipLabel, 3 => $relatedContactName)));
     if ($outcome['duplicate']) {
         $status[] = ts('%count was skipped because the contact is already %2 %3', array('count' => $outcome['duplicate'], 'plural' => '%count were skipped because the contacts are already %2 %3', 2 => $relationshipLabel, 3 => $relatedContactName));
     }
     if ($outcome['invalid']) {
         $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', array('count' => $outcome['invalid'], 'plural' => '%count relationships were not created because the contact is not of the right type for this relationship'));
     }
     $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
     CRM_Core_Session::setStatus($status, ts('Relationship created.', array('count' => $outcome['valid'], 'plural' => 'Relationships created.')), 'success', array('expires' => 0));
 }
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     CRM_Utils_System::setTitle(ts('Add Contacts to Organization'));
     $this->addElement('text', 'name', ts('Find Target Organization'));
     $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + CRM_Contact_BAO_Relationship::getRelationType("Organization"), TRUE);
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     if ($searchRows) {
         $checkBoxes = array();
         $chekFlag = 0;
         foreach ($searchRows as $id => $row) {
             if (!$chekFlag) {
                 $chekFlag = $id;
             }
             $checkBoxes[$id] = $this->createElement('radio', NULL, NULL, NULL, $id);
         }
         $this->addGroup($checkBoxes, 'contact_check');
         if ($chekFlag) {
             $checkBoxes[$chekFlag]->setChecked(TRUE);
         }
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $this->get('searchDone'));
     $this->assign('contact_type_display', ts('Organization'));
     $this->addElement('submit', $this->getButtonName('refresh'), ts('Search'), array('class' => 'crm-form-submit'));
     $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), array('class' => 'crm-form-submit'));
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Add to Organization'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
 function __construct()
 {
     $contact_type = CRM_Contact_BAO_ContactType::getSelectElements(false, true, '_');
     $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('display_name_a' => array('title' => ts('Contact A'), 'name' => 'display_name', 'required' => true), 'id' => array('no_display' => true, 'required' => true)), 'filters' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING)), 'grouping' => 'conact_a_fields'), 'civicrm_contact_b' => array('dao' => 'CRM_Contact_DAO_Contact', 'alias' => 'contact_b', 'fields' => array('display_name_b' => array('title' => ts('Contact B'), 'name' => 'display_name', 'required' => true), 'id' => array('no_display' => true, 'required' => true)), 'filters' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING)), 'grouping' => 'conact_b_fields'), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email_a' => array('title' => ts('Email of Contact A'), 'name' => 'email')), 'grouping' => 'conact_a_fields'), 'civicrm_email_b' => array('dao' => 'CRM_Core_DAO_Email', 'alias' => 'email_b', 'fields' => array('email_b' => array('title' => ts('Email of Contact B'), 'name' => 'email')), 'grouping' => 'conact_b_fields'), 'civicrm_relationship_type' => array('dao' => 'CRM_Contact_DAO_RelationshipType', 'fields' => array('label_a_b' => array('title' => ts('Relationship A-B '), 'default' => true), 'label_b_a' => array('title' => ts('Relationship B-A '), 'default' => true)), 'filters' => array('contact_type_a' => array('title' => ts('Contact Type  A'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING), 'contact_type_b' => array('title' => ts('Contact Type  B'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'relation-fields'), 'civicrm_relationship' => array('dao' => 'CRM_Contact_DAO_Relationship', 'fields' => array('start_date' => array('title' => ts('Relationship Start Date')), 'end_date' => array('title' => ts('Relationship End Date')), 'description' => array('title' => ts('Description'))), 'filters' => array('is_active' => array('title' => ts('Relationship Status'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- Any -', 1 => 'Active', 0 => 'Inactive'), 'type' => CRM_Utils_Type::T_INT), 'relationship_type_id' => array('title' => ts('Relationship'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- any relationship type -') + CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, null, true), 'type' => CRM_Utils_Type::T_INT)), 'grouping' => 'relation-fields'), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'filters' => array('country_id' => array('title' => ts('Country'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::country()), 'state_province_id' => array('title' => ts('State/Province'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::stateProvince())), 'grouping' => 'contact-fields'), 'civicrm_group' => array('dao' => 'CRM_Contact_DAO_Group', 'alias' => 'cgroup', 'filters' => array('gid' => array('name' => 'group_id', 'title' => ts('Group'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'group' => true, 'options' => CRM_Core_PseudoConstant::group()))));
     $this->_tagFilter = true;
     parent::__construct();
 }
Beispiel #5
0
 /**
  * Set variables up before form is built.
  *
  * @param CRM_Core_Form $form
  */
 public static function preProcess(&$form)
 {
     $session = CRM_Core_Session::singleton();
     $contactID = $form->_contactID;
     $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $form->_id);
     $profileId = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
     $form->_profileId = $profileId[0];
     if (!$form->_profileId || !CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_profileId, 'is_active')) {
         CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.'));
     }
     $requiredProfileFields = array('organization_name', 'email');
     $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_profileId, $requiredProfileFields);
     if (!$validProfile) {
         CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the required fields of the selected onbehalf profile are disabled.'));
     }
     $form->assign('profileId', $form->_profileId);
     $form->assign('mode', $form->_mode);
     if ($contactID) {
         $form->_employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($contactID);
         if (!empty($form->_membershipContactID) && $contactID != $form->_membershipContactID) {
             // renewal case - membership being renewed may or may not be for organization
             if (!empty($form->_employers) && array_key_exists($form->_membershipContactID, $form->_employers)) {
                 // if _membershipContactID belongs to employers list, we can say:
                 $form->_relatedOrganizationFound = TRUE;
             }
         } elseif (!empty($form->_employers)) {
             // not a renewal case and _employers list is not empty
             $form->_relatedOrganizationFound = TRUE;
         }
         if ($form->_relatedOrganizationFound) {
             // Related org url - pass checksum if needed
             $args = array('cid' => '');
             if (!empty($_GET['cs'])) {
                 $args = array('uid' => $form->_contactID, 'cs' => $_GET['cs'], 'cid' => '');
             }
             $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
             $form->assign('locDataURL', $locDataURL);
             if (!empty($form->_submitValues['onbehalf'])) {
                 if (!empty($form->_submitValues['onbehalfof_id'])) {
                     $form->assign('submittedOnBehalf', $form->_submitValues['onbehalfof_id']);
                 }
                 $form->assign('submittedOnBehalfInfo', json_encode($form->_submitValues['onbehalf']));
             }
         }
         if ($form->_values['is_for_organization'] != 2) {
             $form->assign('relatedOrganizationFound', $form->_relatedOrganizationFound);
         } else {
             $form->assign('onBehalfRequired', $form->_onBehalfRequired);
         }
         if (count($form->_employers) == 1) {
             foreach ($form->_employers as $id => $value) {
                 $form->_organizationName = $value['name'];
                 $orgId = $id;
             }
             $form->assign('orgId', $orgId);
             $form->assign('organizationName', $form->_organizationName);
         }
     }
 }
Beispiel #6
0
 /**
  * Class constructor.
  */
 public function __construct()
 {
     $contact_type = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, '_');
     $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE), 'contact_type_a' => array('title' => ts('Contact Type (Contact A)'), 'name' => 'contact_type'), 'contact_sub_type_a' => array('title' => ts('Contact Subtype (Contact A)'), 'name' => 'contact_sub_type')), 'filters' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING), 'contact_type_a' => array('title' => ts('Contact Type A'), 'name' => 'contact_type', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'contact_a_fields'), 'civicrm_contact_b' => array('dao' => 'CRM_Contact_DAO_Contact', 'alias' => 'contact_b', 'fields' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE), 'contact_type_b' => array('title' => ts('Contact Type (Contact B)'), 'name' => 'contact_type'), 'contact_sub_type_b' => array('title' => ts('Contact Subtype (Contact B)'), 'name' => 'contact_sub_type')), 'filters' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING), 'contact_type_b' => array('title' => ts('Contact Type B'), 'name' => 'contact_type', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'contact_b_fields'), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email_a' => array('title' => ts('Email (Contact A)'), 'name' => 'email')), 'grouping' => 'contact_a_fields'), 'civicrm_email_b' => array('dao' => 'CRM_Core_DAO_Email', 'alias' => 'email_b', 'fields' => array('email_b' => array('title' => ts('Email (Contact B)'), 'name' => 'email')), 'grouping' => 'contact_b_fields'), 'civicrm_phone' => array('dao' => 'CRM_Core_DAO_Phone', 'alias' => 'phone_a', 'fields' => array('phone_a' => array('title' => ts('Phone (Contact A)'), 'name' => 'phone'), 'phone_ext_a' => array('title' => ts('Phone Ext (Contact A)'), 'name' => 'phone_ext')), 'grouping' => 'contact_a_fields'), 'civicrm_phone_b' => array('dao' => 'CRM_Core_DAO_Phone', 'alias' => 'phone_b', 'fields' => array('phone_b' => array('title' => ts('Phone (Contact B)'), 'name' => 'phone'), 'phone_ext_b' => array('title' => ts('Phone Ext (Contact B)'), 'name' => 'phone_ext')), 'grouping' => 'contact_b_fields'), 'civicrm_relationship_type' => array('dao' => 'CRM_Contact_DAO_RelationshipType', 'fields' => array('label_a_b' => array('title' => ts('Relationship A-B '), 'default' => TRUE), 'label_b_a' => array('title' => ts('Relationship B-A '), 'default' => TRUE)), 'grouping' => 'relation-fields'), 'civicrm_relationship' => array('dao' => 'CRM_Contact_DAO_Relationship', 'fields' => array('start_date' => array('title' => ts('Relationship Start Date')), 'end_date' => array('title' => ts('Relationship End Date')), 'description' => array('title' => ts('Description')), 'relationship_id' => array('title' => ts('Rel ID'), 'name' => 'id')), 'filters' => array('is_active' => array('title' => ts('Relationship Status'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- Any -', 1 => 'Active', 0 => 'Inactive'), 'type' => CRM_Utils_Type::T_INT), 'is_valid' => array('title' => ts('Relationship Dates Validity'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array(NULL => ts('- Any -'), 1 => ts('Not expired'), 0 => ts('Expired')), 'type' => CRM_Utils_Type::T_INT), 'relationship_type_id' => array('title' => ts('Relationship'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE), 'type' => CRM_Utils_Type::T_INT), 'start_date' => array('title' => ts('Start Date'), 'type' => CRM_Utils_Type::T_DATE), 'end_date' => array('title' => ts('End Date'), 'type' => CRM_Utils_Type::T_DATE)), 'grouping' => 'relation-fields'), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'filters' => array('country_id' => array('title' => ts('Country'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::country()), 'state_province_id' => array('title' => ts('State/Province'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::stateProvince())), 'grouping' => 'contact-fields'));
     $this->_groupFilter = TRUE;
     $this->_tagFilter = TRUE;
     parent::__construct();
 }
Beispiel #7
0
 /**
  * set defaults for the form
  *
  * @return array
  * @access public
  */
 public function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     if ($this->_contactType == 'Individual') {
         // set current employer details
         $currentEmployer = CRM_Contact_BAO_Relationship::getCurrentEmployer(array($this->_contactId));
         $defaults['current_employer_id'] = CRM_Utils_Array::value('org_id', $currentEmployer[$this->_contactId]);
         $this->assign('currentEmployer', CRM_Utils_Array::value('current_employer_id', $defaults));
     }
     return $defaults;
 }
 /**
  * This function is called prior to building and submitting the form
  */
 function preProcess()
 {
     // check contact_id
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     if (empty($this->_contactId)) {
         CRM_Core_Error::statusBounce(ts('Could not get a contact id.'), NULL, ts('Lidmaatschap Wijziging - Contact'));
         // this also redirects to the default civicrm page
     }
     // check for permissions
     $session = CRM_Core_Session::singleton();
     if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
         CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'), NULL, ts('Lidmaatschap Wijziging - Contact'));
         // this also redirects to the default civicrm page
     }
     // get session
     $session = CRM_Core_Session::singleton();
     // redirect user after postProcess
     //$urlParams = 'reset=1&cid=' . $this->_contactId;
     //$session->pushUserContext(CRM_Utils_System::url('civicrm/lidmaatschapwijziging/contact', $urlParams));
     // get values
     $this->_configContact = CRM_Lidmaatschapwijziging_ConfigContact::singleton($this->_contactId);
     $this->_values = $this->_configContact->getContact();
     // set display name
     $this->_display_name = $this->_values['display_name'];
     // set title
     CRM_Utils_System::setTitle('LidmaatschapWijziging - Contact - ' . $this->_values['display_name']);
     // set contact id
     $this->_values['contact_id'] = $this->_contactId;
     // change the default name like huppeldepup_35 to huppeldepup, this
     // ensures the we can use the know names for custom fields in the template like
     // huppeldepup and not the column_names like huppeldepup_35
     $values = $this->_configContact->getVnvInfoCustomValues();
     // set vnvn info id, is neede for update or insert in the postProccess
     if (isset($values['id']) and !empty($values['id'])) {
         $this->_vnvinfoId = $values['id'];
     }
     foreach ($this->_configContact->getVnvInfoCustomFields() as $key => $field) {
         $this->_values[$field['name']] = $values[$field['column_name']];
     }
     $values = $this->_configContact->getWerkgeverCustomValues();
     // set werkgever id, is neede for update or insert in the postProccess
     if (isset($values['id']) and !empty($values['id'])) {
         $this->_werkgeverId = $values['id'];
     }
     foreach ($this->_configContact->getWerkgeverCustomFields() as $key => $field) {
         $this->_values[$field['name']] = $values[$field['column_name']];
     }
     $currentEmployer = CRM_Contact_BAO_Relationship::getCurrentEmployer(array($this->_contactId));
     $defaults['current_employer_id'] = CRM_Utils_Array::value('org_id', $currentEmployer[$this->_contactId]);
     // assign values needed for the template
     $this->assign('contactId', $this->_contactId);
     $this->assign('employerDataURL', '/civicrm/ajax/rest?className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=contact&org=1&employee_id=' . $this->_contactId);
     $this->assign('currentEmployer', $this->_values['employer_id']);
 }
 /**
  * @param CRM_Core_Form $form
  */
 public static function basic(&$form)
 {
     $form->addElement('hidden', 'hidden_basic', 1);
     // text for sort_name
     $form->addElement('text', 'target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     $allRelationshipType = array();
     $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     $form->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType, FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple'));
     // relation status
     $relStatusOption = array(ts('Active'), ts('Inactive'), ts('All'));
     $form->addRadio('is_active', ts('Relationship Status'), $relStatusOption);
     $form->setDefaults(array('is_active' => 0));
     CRM_Core_Form_Date::buildDateRange($form, 'start_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'end_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 static function preProcess(&$form)
 {
     $session = CRM_Core_Session::singleton();
     $contactID = $session->get('userID');
     $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $form->_id);
     $profileId = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
     $form->_profileId = $profileId[0];
     if (!$form->_profileId || !CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_profileId, 'is_active')) {
         CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.'));
     }
     $requiredProfileFields = array('organization_name', 'email');
     $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_profileId, $requiredProfileFields);
     if (!$validProfile) {
         CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the required fields of the selected onbehalf profile are disabled.'));
     }
     $form->assign('profileId', $form->_profileId);
     $form->assign('mode', $form->_mode);
     if ($contactID) {
         $form->_employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($contactID);
         if (!empty($form->_employers)) {
             $form->_relatedOrganizationFound = TRUE;
             $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', 'cid=', FALSE, NULL, FALSE);
             $form->assign('locDataURL', $locDataURL);
             $dataURL = CRM_Utils_System::url('civicrm/ajax/employer', 'cid=' . $contactID, FALSE, NULL, FALSE);
             $form->assign('employerDataURL', $dataURL);
         }
         if ($form->_values['is_for_organization'] != 2) {
             $form->assign('relatedOrganizationFound', $form->_relatedOrganizationFound);
         } else {
             $form->assign('onBehalfRequired', $form->_onBehalfRequired);
         }
         if (count($form->_employers) == 1) {
             foreach ($form->_employers as $id => $value) {
                 $form->_organizationName = $value['name'];
                 $orgId = $id;
             }
             $form->assign('orgId', $orgId);
             $form->assign('organizationName', $form->_organizationName);
         }
     }
 }
Beispiel #11
0
 /**
  * Test the function that extracts the arrays used to structure the output.
  *
  * The keys in the output fields array should by matched by field aliases in the sql query (with
  * exceptions of course - currently country is one - although maybe a future refactor can change that!).
  *
  * We are trying to move towards simpler processing in the per row iteration as that may be
  * repeated 100,000 times and in general we should simply be able to match the query fields to
  * our expected rows & do a little pseudoconstant mapping.
  */
 public function testGetExportStructureArrays()
 {
     // This is how return properties are formatted internally within the function for passing to the BAO query.
     $returnProperties = array('first_name' => 1, 'last_name' => 1, 'receive_date' => 1, 'contribution_source' => 1, 'location' => array('Home' => array('street_address' => 1, 'city' => 1, 'country' => 1, 'email' => 1, 'im-1' => 1, 'im_provider' => 1, 'phone-1' => 1)), 'phone' => 1, 'trxn_id' => 1, 'contribution_id' => 1);
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE);
     $query = new CRM_Contact_BAO_Query(array(), $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE, FALSE, TRUE, TRUE, NULL, 'AND');
     list($select) = $query->query();
     $pattern = '/as `?([^`,]*)/';
     $queryFieldAliases = array();
     preg_match_all($pattern, $select, $queryFieldAliases, PREG_PATTERN_ORDER);
     list($outputFields) = CRM_Export_BAO_Export::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, '', array());
     foreach (array_keys($outputFields) as $fieldAlias) {
         if ($fieldAlias == 'Home-country') {
             $this->assertTrue(in_array($fieldAlias . '_id', $queryFieldAliases[1]), 'Country is subject to some funky translate so we make sure country id is present');
         } else {
             $this->assertTrue(in_array($fieldAlias, $queryFieldAliases[1]), 'looking for field ' . $fieldAlias . ' in generaly the alias fields need to match the outputfields');
         }
     }
 }
Beispiel #12
0
 public static function getCaseClientRelationships()
 {
     $caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
     $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
     $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
     // Retrieve ALL client relationships
     $relClient = CRM_Contact_BAO_Relationship::getRelationship($contactID, CRM_Contact_BAO_Relationship::CURRENT, 0, 0, 0, NULL, NULL, FALSE);
     $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
     // Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
     // so they don't show up twice.
     $clientRelationships = array();
     foreach ($relClient as $r) {
         if (!array_key_exists($r['id'], $caseRelationships)) {
             $clientRelationships[] = $r;
         }
     }
     // sort clientRelationships array using jquery call params
     foreach ($clientRelationships as $key => $row) {
         $sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
     }
     $sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
     array_multisort($sortArray, constant($sort_type), $clientRelationships);
     $relationships = array();
     // after sort we can update username fields to be a url
     foreach ($clientRelationships as $key => $value) {
         $relationship = array();
         $relationship['relation'] = $value['relation'];
         $relationship['name'] = '<a href=' . CRM_Utils_System::url('civicrm/contact/view', 'action=view&reset=1&cid=' . $clientRelationships[$key]['cid']) . '>' . $clientRelationships[$key]['name'] . '</a>';
         $relationship['phone'] = $value['phone'];
         $relationship['email'] = $value['email'];
         array_push($relationships, $relationship);
     }
     $clientRelationshipsDT = array();
     $clientRelationshipsDT['data'] = $relationships;
     $clientRelationshipsDT['recordsTotal'] = count($relationships);
     $clientRelationshipsDT['recordsFiltered'] = count($relationships);
     CRM_Utils_JSON::output($clientRelationshipsDT);
 }
Beispiel #13
0
 /**
  * This function sets the default values for the form. Note that in edit/view mode
  * the default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 function setDefaultValues()
 {
     $defaults = $this->_values;
     $params = array();
     if ($this->_action & CRM_Core_Action::ADD) {
         if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
             // set group and tag defaults if any
             if ($this->_gid) {
                 $defaults['group'][$this->_gid] = 1;
             }
             if ($this->_tid) {
                 $defaults['tag'][$this->_tid] = 1;
             }
         }
         if ($this->_contactSubType) {
             $defaults['contact_sub_type'] = $this->_contactSubType;
         }
     } else {
         if (isset($this->_elementIndex["shared_household"])) {
             $sharedHousehold = $this->getElementValue("shared_household");
             if ($sharedHousehold) {
                 $this->assign('defaultSharedHousehold', $sharedHousehold);
             } elseif (CRM_Utils_Array::value('mail_to_household_id', $defaults)) {
                 $defaults['use_household_address'] = true;
                 $this->assign('defaultSharedHousehold', $defaults['mail_to_household_id']);
             }
             $defaults['shared_household_id'] = CRM_Utils_Array::value('mail_to_household_id', $defaults);
             if (array_key_exists(1, $defaults['address'])) {
                 $this->assign('sharedHouseholdAddress', $defaults['address'][1]['display']);
             }
         }
         require_once 'CRM/Contact/BAO/Relationship.php';
         $currentEmployer = CRM_Contact_BAO_Relationship::getCurrentEmployer(array($this->_contactId));
         $defaults['current_employer_id'] = CRM_Utils_Array::value('org_id', $currentEmployer[$this->_contactId]);
         $this->assign('currentEmployer', $defaults['current_employer_id']);
     }
     // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
     foreach ($this->_editOptions as $name => $label) {
         if (!in_array($name, array('Address', 'Notes'))) {
             require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_Form_Edit_" . $name) . ".php";
             eval('CRM_Contact_Form_Edit_' . $name . '::setDefaultValues( $this, $defaults );');
         }
     }
     //set location type and country to default for each block
     $this->blockSetDefaults($defaults);
     return $defaults;
 }
Beispiel #14
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     // current contribution page id
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     if (!$this->_id) {
         // seems like the session is corrupted and/or we lost the id trail
         // lets just bump this to a regular session error and redirect user to main page
         $this->controller->invalidKeyRedirect();
     }
     // this was used prior to the cleverer this_>getContactID - unsure now
     $this->_userID = $session->get('userID');
     $this->_contactID = $this->_membershipContactID = $this->getContactID();
     $this->_mid = NULL;
     if ($this->_contactID) {
         $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
         if ($this->_mid) {
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_mid;
             if ($membership->find(TRUE)) {
                 $this->_defaultMemTypeId = $membership->membership_type_id;
                 if ($membership->contact_id != $this->_contactID) {
                     $validMembership = FALSE;
                     $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
                     if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) {
                         $this->_membershipContactID = $membership->contact_id;
                         $this->assign('membershipContactID', $this->_membershipContactID);
                         $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
                         $validMembership = TRUE;
                     } else {
                         $membershipType = new CRM_Member_BAO_MembershipType();
                         $membershipType->id = $membership->membership_type_id;
                         if ($membershipType->find(TRUE)) {
                             // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
                             // Convert to commma separated list.
                             $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
                             $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
                             if (array_key_exists($membership->contact_id, $permContacts)) {
                                 $this->_membershipContactID = $membership->contact_id;
                                 $validMembership = TRUE;
                             }
                         }
                     }
                     if (!$validMembership) {
                         CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
                     }
                 }
             } else {
                 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
             }
             unset($membership);
         }
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', FALSE);
     // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
     // Use Browser Print instead.
     $this->assign('browserPrint', TRUE);
     // action
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
     $this->assign('action', $this->_action);
     // current mode
     $this->_mode = $this->_action == 1024 ? 'test' : 'live';
     $this->_values = $this->get('values');
     $this->_fields = $this->get('fields');
     $this->_bltID = $this->get('bltID');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     $this->_priceSetId = $this->get('priceSetId');
     $this->_priceSet = $this->get('priceSet');
     if (!$this->_values) {
         // get all the values from the dao object
         $this->_values = array();
         $this->_fields = array();
         CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
         // check if form is active
         if (!CRM_Utils_Array::value('is_active', $this->_values)) {
             // form is inactive, die a fatal death
             CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
         }
         // also check for billing informatin
         // get the billing location type
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
         // CRM-8108 remove ts around Billing location type
         //$this->_bltID = array_search( ts('Billing'),  $locationTypes );
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         // check for is_monetary status
         $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
         $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
         //FIXME: to support multiple payment processors
         if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor', $this->_values))) {
             $ppID = CRM_Utils_Array::value('payment_processor', $this->_values);
             if (!$ppID) {
                 CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).'));
             }
             $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
             $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode);
             $this->set('paymentProcessors', $this->_paymentProcessors);
             //set default payment processor
             if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) {
                 foreach ($this->_paymentProcessors as $ppId => $values) {
                     if ($values['is_default'] == 1 || count($this->_paymentProcessors) == 1) {
                         $defaultProcessorId = $ppId;
                         break;
                     }
                 }
             }
             if (isset($defaultProcessorId)) {
                 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode);
                 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
             }
             if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
                 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
                     // check selected payment processor is active
                     if (empty($eachPaymentProcessor)) {
                         CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
                     }
                     // ensure that processor has a valid config
                     $this->_paymentObject =& CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this);
                     $error = $this->_paymentObject->checkConfig();
                     if (!empty($error)) {
                         CRM_Core_Error::fatal($error);
                     }
                 }
             }
         }
         // get price info
         // CRM-5095
         CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page');
         // this avoids getting E_NOTICE errors in php
         $setNullFields = array('amount_block_is_active', 'honor_block_is_active', 'is_allow_other_amount', 'footer_text');
         foreach ($setNullFields as $f) {
             if (!isset($this->_values[$f])) {
                 $this->_values[$f] = NULL;
             }
         }
         //check if Membership Block is enabled, if Membership Fields are included in profile
         //get membership section for this contribution page
         $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
         $this->set('membershipBlock', $this->_membershipBlock);
         if ($this->_values['custom_pre_id']) {
             $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
         }
         if ($this->_values['custom_post_id']) {
             $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
         }
         if ((isset($postProfileType) && $postProfileType == 'Membership' || isset($preProfileType) && $preProfileType == 'Membership') && !$this->_membershipBlock['is_active']) {
             CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
         }
         $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
         if ($pledgeBlock) {
             $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
             $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
             $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
             $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
             //set pledge id in values
             $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
             //authenticate pledge user for pledge payment.
             if ($pledgeId) {
                 $this->_values['pledge_id'] = $pledgeId;
                 //lets override w/ pledge campaign.
                 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'campaign_id');
                 self::authenticatePledgeUser();
             }
         }
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
     }
     // Handle PCP
     $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
     if ($pcpId) {
         $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
         $this->_pcpId = $pcp['pcpId'];
         $this->_pcpBlock = $pcp['pcpBlock'];
         $this->_pcpInfo = $pcp['pcpInfo'];
     }
     // Link (button) for users to create their own Personal Campaign page
     if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
         $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}&component=contribute", FALSE, NULL, TRUE);
         $this->assign('linkTextUrl', $linkTextUrl);
         $this->assign('linkText', $linkText);
     }
     //set pledge block if block id is set
     if (CRM_Utils_Array::value('pledge_block_id', $this->_values)) {
         $this->assign('pledgeBlock', TRUE);
     }
     // check if one of the (amount , membership)  bloks is active or not
     $this->_membershipBlock = $this->get('membershipBlock');
     if (!$this->_values['amount_block_is_active'] && !$this->_membershipBlock['is_active'] && !$this->_priceSetId) {
         CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
     }
     if ($this->_values['amount_block_is_active']) {
         $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
     }
     $this->_contributeMode = $this->get('contributeMode');
     $this->assign('contributeMode', $this->_contributeMode);
     //assigning is_monetary and is_email_receipt to template
     $this->assign('is_monetary', $this->_values['is_monetary']);
     $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
     $this->assign('bltID', $this->_bltID);
     //assign cancelSubscription URL to templates
     $this->assign('cancelSubscriptionUrl', CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values));
     // assigning title to template in case someone wants to use it, also setting CMS page title
     if ($this->_pcpId) {
         $this->assign('title', $this->_pcpInfo['title']);
         CRM_Utils_System::setTitle($this->_pcpInfo['title']);
     } else {
         $this->assign('title', $this->_values['title']);
         CRM_Utils_System::setTitle($this->_values['title']);
     }
     $this->_defaults = array();
     $this->_amount = $this->get('amount');
     //CRM-6907
     $config = CRM_Core_Config::singleton();
     $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency);
     //lets allow user to override campaign.
     $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
     if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
         $this->_values['campaign_id'] = $campID;
     }
     //do check for cancel recurring and clean db, CRM-7696
     if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) {
         self::cancelRecurring();
     }
 }
Beispiel #15
0
 /**
  * Retrieve contact relationships.
  */
 public static function getContactRelationships()
 {
     $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
     $context = CRM_Utils_Type::escape($_GET['context'], 'String');
     $relationship_type_id = CRM_Utils_Type::escape(CRM_Utils_Array::value('relationship_type_id', $_GET), 'Integer', FALSE);
     if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
         return CRM_Utils_System::permissionDenied();
     }
     $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
     $params['contact_id'] = $contactID;
     $params['context'] = $context;
     if ($relationship_type_id) {
         $params['relationship_type_id'] = $relationship_type_id;
     }
     // get the contact relationships
     $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
     CRM_Utils_JSON::output($relationships);
 }
Beispiel #16
0
 /**
  * Retrieve contact relationships.
  */
 public static function getContactRelationships()
 {
     $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
     $context = CRM_Utils_Type::escape($_GET['context'], 'String');
     $relationship_type_id = CRM_Utils_Type::escape(CRM_Utils_Array::value('relationship_type_id', $_GET), 'Integer', FALSE);
     if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
         return CRM_Utils_System::permissionDenied();
     }
     $sortMapper = array();
     foreach ($_GET['columns'] as $key => $value) {
         $sortMapper[$key] = $value['data'];
     }
     $offset = isset($_GET['start']) ? CRM_Utils_Type::escape($_GET['start'], 'Integer') : 0;
     $rowCount = isset($_GET['length']) ? CRM_Utils_Type::escape($_GET['length'], 'Integer') : 25;
     $sort = isset($_GET['order'][0]['column']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_GET['order'][0]['column'], 'Integer'), $sortMapper) : NULL;
     $sortOrder = isset($_GET['order'][0]['dir']) ? CRM_Utils_Type::escape($_GET['order'][0]['dir'], 'String') : 'asc';
     $params = $_GET;
     if ($sort && $sortOrder) {
         $params['sortBy'] = $sort . ' ' . $sortOrder;
     }
     $params['page'] = $offset / $rowCount + 1;
     $params['rp'] = $rowCount;
     $params['contact_id'] = $contactID;
     $params['context'] = $context;
     if ($relationship_type_id) {
         $params['relationship_type_id'] = $relationship_type_id;
     }
     // get the contact relationships
     $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
     CRM_Utils_JSON::output($relationships);
 }
Beispiel #17
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);
 }
Beispiel #18
0
 /**
  * Test case for createProfileContact.
  */
 public function testCreateProfileContact()
 {
     $fields = CRM_Contact_BAO_Contact::exportableFields('Individual');
     //current employer field for individual
     $fields['organization_name'] = array('name' => 'organization_name', 'where' => 'civicrm_organization.organization_name', 'title' => 'Current Employer');
     //get the common params
     $contactParams = $this->contactParams();
     $unsetParams = array('location', 'privacy');
     foreach ($unsetParams as $param) {
         unset($contactParams[$param]);
     }
     $profileParams = array('organization_name' => 'Yahoo', 'gender_id' => '2', 'prefix_id' => '3', 'suffix_id' => '2', 'city-Primary' => 'Newark', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '18.219023', 'geo_code_2-Primary' => '-105.00973', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.smith', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '303443689', 'phone-Primary-2' => '9833910234', 'postal_code-Primary' => '01903', 'postal_code_suffix-Primary' => '12345', 'state_province-Primary' => '1029', 'street_address-Primary' => 'Saint Helier St', 'supplemental_address_1-Primary' => 'Hallmark Ct', 'supplemental_address_2-Primary' => 'Jersey Village', 'user_unique_id' => '123456789', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('3' => '1', '4' => '1', '1' => '1'));
     $createParams = array_merge($contactParams, $profileParams);
     //create the contact using create profile contact.
     $contactId = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, NULL, NULL, NULL, NULL, TRUE);
     //get the parameters to compare.
     $params = $this->contactParams();
     //check the values in DB.
     foreach ($params as $key => $val) {
         if (!is_array($params[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $params[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($params['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $profileParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $profileParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $params['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $params['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $params['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $profileParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $profileParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $profileParams), 'city' => CRM_Utils_Array::value('city-Primary', $profileParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $profileParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $profileParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $profileParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $profileParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $profileParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($profileParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($profileParams['tag'], $tagIds);
     //update Contact mode
     $updateCParams = array('first_name' => 'john', 'last_name' => 'doe', 'contact_type' => 'Individual', 'middle_name' => 'abc', 'prefix_id' => 2, 'suffix_id' => 3, 'nick_name' => 'Nick Name Updated', 'job_title' => 'software Developer', 'gender_id' => 1, 'is_deceased' => 1, 'website' => array(1 => array('website_type_id' => 1, 'url' => 'http://civicrmUpdate.org')), 'contact_source' => 'test contact', 'external_identifier' => 111222333, 'preferred_mail_format' => 'Both', 'is_opt_out' => 0, 'legal_identifier' => '123123123123', 'image_URL' => 'http://imageupdate.com', 'deceased_date' => '1981-10-10', 'birth_date' => '1951-11-11', 'privacy' => array('do_not_phone' => 1, 'do_not_email' => 1), 'preferred_communication_method' => array('1' => 0, '2' => 1, '3' => 0, '4' => 1, '5' => 0));
     $updatePfParams = array('organization_name' => 'Google', 'city-Primary' => 'Mumbai', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '31.694842', 'geo_code_2-Primary' => '-106.29998', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.doe', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '02115245336', 'phone-Primary-2' => '9766323895', 'postal_code-Primary' => '12345', 'postal_code_suffix-Primary' => '123', 'state_province-Primary' => '1004', 'street_address-Primary' => 'Oberoi Garden', 'supplemental_address_1-Primary' => 'A-wing:3037', 'supplemental_address_2-Primary' => 'Andhery', 'user_unique_id' => '1122334455', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('2' => '1', '5' => '1'));
     $createParams = array_merge($updateCParams, $updatePfParams);
     //create the contact using create profile contact.
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, $contactId, NULL, NULL, NULL, TRUE);
     //check the contact ids
     $this->assertEquals($contactId, $contactID, 'check for Contact ids');
     //check the values in DB.
     foreach ($updateCParams as $key => $val) {
         if (!is_array($updateCParams[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $updateCParams[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($updateCParams['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $updatePfParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $updatePfParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $updateCParams['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $updateCParams['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $updateCParams['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $updatePfParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $updatePfParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $updatePfParams), 'city' => CRM_Utils_Array::value('city-Primary', $updatePfParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $updatePfParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $updatePfParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $updatePfParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $updatePfParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $updatePfParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($updatePfParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($updatePfParams['tag'], $tagIds);
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
 }
 /**
  * Browse all custom data groups.
  *
  * @param string $action   the action to be invoked
  *
  * @return void
  * @access public
  */
 function browse($action = NULL)
 {
     // get all custom groups sorted by weight
     $customGroup = array();
     $dao = new CRM_Core_DAO_CustomGroup();
     $dao->orderBy('weight, title');
     $dao->find();
     while ($dao->fetch()) {
         $customGroup[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $customGroup[$dao->id]);
         // form all action links
         $action = array_sum(array_keys($this->actionLinks()));
         // update enable/disable links depending on custom_group properties.
         if ($dao->is_active) {
             $action -= CRM_Core_Action::ENABLE;
         } else {
             $action -= CRM_Core_Action::DISABLE;
         }
         $customGroup[$dao->id]['order'] = $customGroup[$dao->id]['weight'];
         $customGroup[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id));
     }
     $customGroupExtends = CRM_Core_SelectValues::customGroupExtends();
     foreach ($customGroup as $key => $array) {
         CRM_Core_DAO_CustomGroup::addDisplayEnums($customGroup[$key]);
         $customGroup[$key]['extends_display'] = $customGroupExtends[$customGroup[$key]['extends']];
     }
     //fix for Displaying subTypes
     $subTypes = array();
     $subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
     $subTypes['Contribution'] = CRM_Contribute_PseudoConstant::contributionType();
     $subTypes['Membership'] = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
     $subTypes['Event'] = CRM_Core_OptionGroup::values('event_type');
     $subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type');
     $subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType();
     $subTypes['Participant'] = array();
     $subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role');
     $subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event();
     $subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type');
     $subTypes['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
     $subTypes['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
     $subTypes['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
     $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
     $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
     $allRelationshipType = array();
     $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
     $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
     //adding subtype specific relationships CRM-5256
     $relSubType = CRM_Contact_BAO_ContactType::subTypeInfo();
     foreach ($relSubType as $subType => $val) {
         $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType);
         $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes);
     }
     $subTypes['Relationship'] = $allRelationshipType;
     $cSubTypes = CRM_Core_Component::contactSubTypes();
     $contactSubTypes = array();
     foreach ($cSubTypes as $key => $value) {
         $contactSubTypes[$key] = $key;
     }
     $subTypes['Contact'] = $contactSubTypes;
     CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($subTypes);
     foreach ($customGroup as $key => $values) {
         $subValue = CRM_Utils_Array::value('extends_entity_column_value', $customGroup[$key]);
         $subName = CRM_Utils_Array::value('extends_entity_column_id', $customGroup[$key]);
         $type = CRM_Utils_Array::value('extends', $customGroup[$key]);
         if ($subValue) {
             $subValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subValue, 1, -1));
             $colValue = NULL;
             foreach ($subValue as $sub) {
                 if ($sub) {
                     if ($type == 'Participant') {
                         if ($subName == 1) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantRole'][$sub] : $subTypes['ParticipantRole'][$sub];
                         } elseif ($subName == 2) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventName'][$sub] : $subTypes['ParticipantEventName'][$sub];
                         } elseif ($subName == 3) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventType'][$sub] : $subTypes['ParticipantEventType'][$sub];
                         }
                     } elseif ($type == 'Relationship') {
                         $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_a_b'] : $subTypes[$type][$sub . '_a_b'];
                         if (isset($subTypes[$type][$sub . '_b_a'])) {
                             $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_b_a'] : $subTypes[$type][$sub . '_b_a'];
                         }
                     } else {
                         $colValue = $colValue ? $colValue . (isset($subTypes[$type][$sub]) ? ', ' . $subTypes[$type][$sub] : '') : (isset($subTypes[$type][$sub]) ? $subTypes[$type][$sub] : '');
                     }
                 }
             }
             $customGroup[$key]["extends_entity_column_value"] = $colValue;
         } else {
             if (is_array(CRM_Utils_Array::value($type, $subTypes))) {
                 $customGroup[$key]["extends_entity_column_value"] = ts("Any");
             }
         }
     }
     $returnURL = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1&action=browse");
     CRM_Utils_Weight::addOrder($customGroup, 'CRM_Core_DAO_CustomGroup', 'id', $returnURL);
     $this->assign('rows', $customGroup);
 }
Beispiel #20
0
 /**
  * Add on behalf of organization and it's location.
  *
  * This situation occurs when on behalf of is enabled for the contribution page and the person
  * signing up does so on behalf of an organization.
  *
  * @param array $behalfOrganization
  *   array of organization info.
  * @param int $contactID
  *   individual contact id. One.
  *   who is doing the process of signup / contribution.
  *
  * @param array $values
  *   form values array.
  * @param array $params
  * @param array $fields
  *   Array of fields from the onbehalf profile relevant to the organization.
  */
 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL)
 {
     $isNotCurrentEmployer = FALSE;
     $dupeIDs = array();
     $orgID = NULL;
     if (!empty($behalfOrganization['organization_id'])) {
         $orgID = $behalfOrganization['organization_id'];
         unset($behalfOrganization['organization_id']);
     } else {
         // get the Employee relationship type id
         $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
         // keep relationship params ready
         $relParams['relationship_type_id'] = $relTypeId . '_a_b';
         $relParams['is_permission_a_b'] = 1;
         $relParams['is_active'] = 1;
         $isNotCurrentEmployer = TRUE;
     }
     // formalities for creating / editing organization.
     $behalfOrganization['contact_type'] = 'Organization';
     if (!$orgID) {
         // check if matching organization contact exists
         $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
         $dedupeParams['check_permission'] = FALSE;
         $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
         // CRM-6243 says to pick the first org even if more than one match
         if (count($dupeIDs) >= 1) {
             $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
             // don't allow name edit
             unset($behalfOrganization['organization_name']);
         }
     } else {
         // if found permissioned related organization, allow location edit
         $behalfOrganization['contact_id'] = $orgID;
         // don't allow name edit
         unset($behalfOrganization['organization_name']);
     }
     // handling for image url
     if (!empty($behalfOrganization['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
     }
     // create organization, add location
     $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID, NULL, NULL, 'Organization');
     // create relationship
     if ($isNotCurrentEmployer) {
         $relParams['contact_check'][$orgID] = 1;
         $cid = array('contact' => $contactID);
         CRM_Contact_BAO_Relationship::legacyCreateMultiple($relParams, $cid);
     }
     // if multiple match - send a duplicate alert
     if ($dupeIDs && count($dupeIDs) > 1) {
         $values['onbehalf_dupe_alert'] = 1;
         // required for IPN
         $params['onbehalf_dupe_alert'] = 1;
     }
     // make sure organization-contact-id is considered for recording
     // contribution/membership etc..
     if ($contactID != $orgID) {
         // take a note of contact-id, so we can send the
         // receipt to individual contact as well.
         // required for mailing/template display ..etc
         $values['related_contact'] = $contactID;
         //make this employee of relationship as current
         //employer / employee relationship,  CRM-3532
         if ($isNotCurrentEmployer && $orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id')) {
             $isNotCurrentEmployer = FALSE;
         }
         if (!$isNotCurrentEmployer && $orgID) {
             //build current employer params
             $currentEmpParams[$contactID] = $orgID;
             CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
         }
         // contribution / signup will be done using this
         // organization id.
         $contactID = $orgID;
     }
 }
Beispiel #21
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Contact/Form/Relationship.php';
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $this->set('searchDone', 0);
     if (CRM_Utils_Array::value('_qf_AddToOrganization_refresh', $_POST)) {
         $searchParams['contact_type'] = array('Organization' => 'Organization');
         $searchParams['rel_contact'] = $params['name'];
         CRM_Contact_Form_Relationship::search($searchParams);
         $this->set('searchDone', 1);
         return;
     }
     $data = array();
     //$params['relationship_type_id']='4_a_b';
     $data['relationship_type_id'] = $params['relationship_type_id'];
     $data['is_active'] = 1;
     $invalid = 0;
     $valid = 0;
     $duplicate = 0;
     if (is_array($this->_contactIds)) {
         foreach ($this->_contactIds as $value) {
             $ids = array();
             $ids['contact'] = $value;
             //contact b --> organization
             // contact a  -> individual
             $errors = CRM_Contact_BAO_Relationship::checkValidRelationship($params, $ids, $params['contact_check']);
             if ($errors) {
                 $invalid = $invalid + 1;
                 continue;
             }
             if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($params, CRM_Utils_Array::value('contact', $ids), $params['contact_check'])) {
                 // step 2
                 $duplicate++;
                 continue;
             }
             CRM_Contact_BAO_Relationship::add($data, $ids, $params['contact_check']);
             $valid++;
         }
         $status = array(ts('Added Contact(s) to Organization'), ts('Total Selected Contact(s): %1', array(1 => $valid + $invalid + $duplicate)));
         if ($valid) {
             $status[] = ts('New relationship record(s) created: %1.', array(1 => $valid)) . '<br/>';
         }
         if ($invalid) {
             $status[] = ts('Relationship record(s) not created due to invalid target contact type: %1.', array(1 => $invalid)) . '<br/>';
         }
         if ($duplicate) {
             $status[] = ts('Relationship record(s) not created - duplicate of existing relationship: %1.', array(1 => $duplicate)) . '<br/>';
         }
         CRM_Core_Session::setStatus($status);
     }
 }
 /**
  * where / qill clause for relationship
  *
  * @return void
  * @access public
  */
 function relationship(&$values)
 {
     list($name, $op, $value, $grouping, $wildcard) = $values;
     // also get values array for relation_target_name
     // for relatinship search we always do wildcard
     $targetName = $this->getWhereValues('relation_target_name', $grouping);
     $relStatus = $this->getWhereValues('relation_status', $grouping);
     $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
     $nameClause = $name = NULL;
     if ($targetName) {
         $name = trim($targetName[2]);
         if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') {
             $name = substr($name, 1, -1);
             $name = strtolower(CRM_Core_DAO::escapeString($name));
             $nameClause = "= '{$name}'";
         } else {
             $name = strtolower(CRM_Core_DAO::escapeString($name));
             $nameClause = "LIKE '%{$name}%'";
         }
     }
     $rel = explode('_', $value);
     self::$_relType = $rel[1];
     $params = array('id' => $rel[0]);
     $rTypeValues = array();
     $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues);
     if (!$rType) {
         return;
     }
     if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
         self::$_relType = 'reciprocal';
     }
     if ($nameClause) {
         $this->_where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )";
     }
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
     $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
     $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
     $allRelationshipType = array();
     $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
     $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
     if ($nameClause || !$targetGroup) {
         $this->_qill[$grouping][] = "{$allRelationshipType[$value]}  {$name}";
     }
     //check to see if the target contact is in specified group
     if ($targetGroup) {
         //add contacts from static groups
         $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id";
         $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN  (" . implode(",", $targetGroup[2]) . ") )";
         //add contacts from saved searches
         $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
         //set the group where clause
         if ($ssWhere) {
             $groupWhere[] = "( " . $ssWhere . " )";
         }
         $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
         //Get the names of the target groups for the qill
         $groupNames =& CRM_Core_PseudoConstant::group();
         $qillNames = array();
         foreach ($targetGroup[2] as $groupId) {
             if (array_key_exists($groupId, $groupNames)) {
                 $qillNames[] = $groupNames[$groupId];
             }
         }
         $this->_qill[$grouping][] = "{$allRelationshipType[$value]}  ( " . implode(", ", $qillNames) . " )";
     }
     //check for active, inactive and all relation status
     $today = date('Ymd');
     if ($relStatus[2] == 0) {
         $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 1 AND\n( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND\n( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )\n)";
         $this->_qill[$grouping][] = ts('Relationship - Active');
     } elseif ($relStatus[2] == 1) {
         $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 0 OR\ncivicrm_relationship.end_date < {$today} OR\ncivicrm_relationship.start_date > {$today}\n)";
         $this->_qill[$grouping][] = ts('Relationship - Inactive');
     }
     $this->_where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0];
     $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
     $this->_useDistinct = TRUE;
 }
Beispiel #23
0
 /**
  * Get the list the export fields.
  *
  * @param int $selectAll
  *   User preference while export.
  * @param array $ids
  *   Contact ids.
  * @param array $params
  *   Associated array of fields.
  * @param string $order
  *   Order by clause.
  * @param array $fields
  *   Associated array of fields.
  * @param array $moreReturnProperties
  *   Additional return fields.
  * @param int $exportMode
  *   Export mode.
  * @param string $componentClause
  *   Component clause.
  * @param string $componentTable
  *   Component table.
  * @param bool $mergeSameAddress
  *   Merge records if they have same address.
  * @param bool $mergeSameHousehold
  *   Merge records if they belong to the same household.
  *
  * @param array $exportParams
  * @param string $queryOperator
  *
  */
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = $selectedPaymentFields = FALSE;
     $origFields = $fields;
     $relationField = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE);
     $queryMode = self::getQueryMode($exportMode);
     if ($fields) {
         //construct return properties
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = $imProviderId = NULL;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id separately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } elseif ($fieldName == 'im') {
                 $imProviderId = CRM_Utils_Array::value(3, $value);
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (!empty($value[2])) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 'Primary';
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(4, $value);
                     }
                 } elseif (!empty($value[4])) {
                     $relationField = CRM_Utils_Array::value(4, $value);
                     $relLocTypeId = CRM_Utils_Array::value(5, $value);
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                     } elseif ($relationField == 'im') {
                         $relIMProviderId = CRM_Utils_Array::value(6, $value);
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } elseif ($relIMProviderId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                     } else {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                     }
                     $relPhoneTypeId = $relIMProviderId = NULL;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } elseif (is_numeric($locTypeId)) {
                 if ($phoneTypeId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                 } elseif ($imProviderId) {
                     $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                 } else {
                     $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                 }
             } else {
                 //hack to fix component fields
                 //revert mix of event_id and title
                 if ($fieldName == 'event_id') {
                     $returnProperties['event_id'] = 1;
                 } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) {
                     $selectedPaymentFields = TRUE;
                     $paymentTableId = 'participant_id';
                     $returnProperties[$fieldName] = 1;
                 } else {
                     $returnProperties[$fieldName] = 1;
                 }
             }
         }
         $returnProperties[self::defaultReturnProperty($exportMode)] = 1;
     } else {
         $primary = TRUE;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = FALSE;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = TRUE;
                 $paymentTableId = 'participant_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = TRUE;
                 $paymentTableId = 'membership_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = TRUE;
                 $paymentTableId = 'pledge_payment_id';
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
                 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
                 $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
             }
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset non exportable fields for components
             $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id');
             foreach ($nonExpoFields as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($mergeSameAddress) {
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['postal_greeting'] = 1;
         $returnProperties['email_greeting'] = 1;
         $returnProperties['street_name'] = 1;
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
         $returnProperties['city'] = 1;
         $returnProperties['state_province'] = 1;
         // some columns are required for assistance incase they are not already present
         $exportParams['merge_same_address']['temp_columns'] = array();
         $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
         foreach ($tempColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
                 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
             }
         }
     }
     if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
         // If an Additional Group is selected, then all contacts in that group are
         // added to the export set (filtering out duplicates).
         $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
         CRM_Core_DAO::executeQuery($query);
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (!empty($moreReturnProperties['group'])) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $exportParams['postal_mailing_export']['temp_columns'] = array();
     if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) {
         $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
         foreach ($postalColumns as $column) {
             if (!array_key_exists($column, $returnProperties)) {
                 $returnProperties[$column] = 1;
                 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
             }
         }
     }
     // rectify params to what proximity search expects if there is a value for prox_distance
     // CRM-7021
     if (!empty($params)) {
         CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
         }
         //also merge Head of Household
         $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKeyMOH][$key] = $value;
                 $returnProperties[$relationKeyHOH][$key] = $value;
             }
         }
         unset($returnProperties[$relationKeyMOH]['location_type']);
         unset($returnProperties[$relationKeyMOH]['im_provider']);
         unset($returnProperties[$relationKeyHOH]['location_type']);
         unset($returnProperties[$relationKeyHOH]['im_provider']);
     }
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
                 $query = "SELECT contact_id FROM civicrm_activity_contact\n                              WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n                              record_type_id = {$sourceID}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 while ($dao->fetch()) {
                     $relIDs[] = $dao->contact_id;
                 }
             } else {
                 $component = self::exportComponent($exportMode);
                 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                     $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
                 } else {
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if (!$selectAll && $componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } elseif (!empty($relIDs)) {
                 $relID = implode(',', $relIDs);
                 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
             }
             $relationFrom = " {$relationFrom}\n                INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n                {$relationshipJoin} ";
             //check for active relationship status only
             $today = date('Ymd');
             $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}";
             $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
             while ($allRelContactDAO->fetch()) {
                 //FIX Me: Migrate this to table rather than array
                 // build the array of all related contacts
                 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO;
             }
             $allRelContactDAO->free();
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (!empty($returnProperties['groups'])) {
         $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
         $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if (!$selectAll && $componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     // CRM-13982 - check if is deleted
     $excludeTrashed = TRUE;
     foreach ($params as $value) {
         if ($value[0] == 'contact_is_deleted') {
             $excludeTrashed = FALSE;
         }
     }
     $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )";
     if (empty($where)) {
         $where = "WHERE {$trashClause}";
     } else {
         $where .= " AND {$trashClause}";
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $groupBy = 'GROUP BY civicrm_contribution.id';
             if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
                 // especial group by  when soft credit columns are included
                 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
             }
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $groupBy = 'GROUP BY civicrm_participant.id';
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $groupBy = " GROUP BY civicrm_membership.id";
             break;
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     // always add contact_a.id to the ORDER clause
     // so the order is deterministic
     //CRM-15301
     if (strpos('contact_a.id', $order) === FALSE) {
         $order .= ", contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $addPaymentHeader = FALSE;
     $paymentDetails = array();
     if ($paymentFields || $selectedPaymentFields) {
         // get payment related in for event and members
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
         //get all payment headers.
         // If we haven't selected specific payment fields, load in all the
         // payment headers.
         if (!$selectedPaymentFields) {
             $paymentHeaders = self::componentPaymentFields();
             if (!empty($paymentDetails)) {
                 $addPaymentHeader = TRUE;
             }
         } else {
             $paymentHeaders = array();
         }
         $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = TRUE;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     // we write to temp table often to avoid using too much memory
     $tempRowCount = 100;
     $count = -1;
     // for CRM-3157 purposes
     $i18n = CRM_Core_I18n::singleton();
     $outputColumns = array();
     //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
     // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
     foreach ($returnProperties as $key => $value) {
         $outputColumns[$key] = $value;
     }
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $row = array();
             //convert the pseudo constants
             // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
             // temporary iterationDAO object to get around it.
             // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
             // these additional properties are NOT reset when the $dao cycles through the while loop
             // nor are they overwritten as they are not in the loop
             // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
             // relevant property is set.
             // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
             // export class before tackling a better architectural fix
             $iterationDAO = clone $dao;
             $query->convertToPseudoNames($iterationDAO);
             //first loop through output columns so that we return what is required, and in same order.
             $relationshipField = 0;
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     // Split campaign into 2 fields for id and title
                     if (substr($field, -14) == 'campaign_title') {
                         $headerRows[] = ts('Campaign Title');
                     } elseif (substr($field, -11) == 'campaign_id') {
                         $headerRows[] = ts('Campaign ID');
                     } elseif (isset($query->_fields[$field]['title'])) {
                         $headerRows[] = $query->_fields[$field]['title'];
                     } elseif ($field == 'phone_type_id') {
                         $headerRows[] = ts('Phone Type');
                     } elseif ($field == 'provider_id') {
                         $headerRows[] = ts('IM Service Provider');
                     } elseif (is_array($value) && $field == 'location') {
                         // fix header for location type case
                         foreach ($value as $ltype => $val) {
                             foreach (array_keys($val) as $fld) {
                                 $type = explode('-', $fld);
                                 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                 if (!empty($type[1])) {
                                     if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                     } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                     }
                                 }
                                 $headerRows[] = $hdr;
                                 self::sqlColumnDefn($query, $sqlColumns, $hdr);
                             }
                             $sqlDone = TRUE;
                         }
                     } elseif (substr($field, 0, 5) == 'case_') {
                         if ($query->_fields['case'][$field]['title']) {
                             $headerRows[] = $query->_fields['case'][$field]['title'];
                         } elseif ($query->_fields['activity'][$field]['title']) {
                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                         }
                     } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                         $relName = $field;
                         foreach ($value as $relationField => $relationValue) {
                             // below block is same as primary block (duplicate)
                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
                                     $headerName = $field . '-' . $relationField;
                                 } else {
                                     if ($relationField == 'current_employer') {
                                         $headerName = $field . '-' . 'current_employer';
                                     } else {
                                         $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
                                     }
                                 }
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'phone_type_id') {
                                 $headerName = $field . '-' . 'Phone Type';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'provider_id') {
                                 $headerName = $field . '-' . 'Im Service Provider';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif ($relationField == 'state_province_id') {
                                 $headerName = $field . '-' . 'state_province_id';
                                 $headerRows[] = $headerName;
                                 self::sqlColumnDefn($query, $sqlColumns, $headerName);
                             } elseif (is_array($relationValue) && $relationField == 'location') {
                                 // fix header for location type case
                                 foreach ($relationValue as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                         if (!empty($type[1])) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } elseif (CRM_Utils_Array::value(0, $type) == 'im') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                             }
                                         }
                                         $headerName = $field . '-' . $hdr;
                                         $headerRows[] = $headerName;
                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                     }
                                 }
                             }
                         }
                     } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                         $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
                     } else {
                         $headerRows[] = $field;
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 // add im_provider to $dao object
                 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
                     $iterationDAO->im_provider = $iterationDAO->provider_id;
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                     // to get phone type from phone type id
                     if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
                         $fieldValue = $phoneTypes[$fieldValue];
                     } elseif ($field == 'provider_id' || $field == 'im_provider') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     } elseif ($field == 'master_id') {
                         $masterAddressId = NULL;
                         if (isset($iterationDAO->master_id)) {
                             $masterAddressId = $iterationDAO->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id);
                     }
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->contact_id;
                     // special case for calculated field
                 } elseif ($field == 'source_contact_id') {
                     $row[$field] = $iterationDAO->contact_id;
                 } elseif ($field == 'pledge_balance_amount') {
                     $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
                     // special case for calculated field
                 } elseif ($field == 'pledge_next_pay_amount') {
                     $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
                 } elseif (is_array($value) && $field == 'location') {
                     // fix header for location type case
                     foreach ($value as $ltype => $val) {
                         foreach (array_keys($val) as $fld) {
                             $type = explode('-', $fld);
                             $fldValue = "{$ltype}-" . $type[0];
                             // CRM-14076 - fix label to work as the query object expects
                             // FIXME: We should not be using labels as keys!
                             $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
                             if (!empty($type[1])) {
                                 $fldValue .= "-" . $type[1];
                                 $daoField .= "-" . $type[1];
                             }
                             // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                             switch ($fld) {
                                 case 'country':
                                 case 'world_region':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country'));
                                     break;
                                 case 'state_province':
                                     $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province'));
                                     break;
                                 case 'im_provider':
                                     $imFieldvalue = $daoField . "-provider_id";
                                     $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders);
                                     break;
                                 default:
                                     $row[$fldValue] = $iterationDAO->{$daoField};
                                     break;
                             }
                         }
                     }
                 } elseif (array_key_exists($field, $contactRelationshipTypes)) {
                     $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
                     $relationQuery[$field]->convertToPseudoNames($relDAO);
                     foreach ($value as $relationField => $relationValue) {
                         if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                             $fieldValue = $relDAO->{$relationField};
                             if ($relationField == 'phone_type_id') {
                                 $fieldValue = $phoneTypes[$relationValue];
                             } elseif ($relationField == 'provider_id') {
                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                             } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                 //special case for greeting replacement
                                 $fldValue = "{$relationField}_display";
                                 $fieldValue = $relDAO->{$fldValue};
                             }
                         } elseif (is_object($relDAO) && $relationField == 'state_province') {
                             $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
                         } elseif (is_object($relDAO) && $relationField == 'country') {
                             $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
                         } else {
                             $fieldValue = '';
                         }
                         $field = $field . '_';
                         if (array_key_exists($relationField, $multipleSelectFields)) {
                             $param = array($relationField => $fieldValue);
                             $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
                             CRM_Core_OptionGroup::lookupValues($param, $names, FALSE);
                             $fieldValue = $param[$relationField];
                         }
                         if (is_object($relDAO) && $relationField == 'id') {
                             $row[$field . $relationField] = $relDAO->contact_id;
                         } elseif (is_array($relationValue) && $relationField == 'location') {
                             foreach ($relationValue as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (!empty($type[1])) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     // CRM-3157: localise country, region (both have ‘country’ context)
                                     // and state_province (‘province’ context)
                                     switch (TRUE) {
                                         case !is_object($relDAO):
                                             $row[$field . '_' . $fldValue] = '';
                                             break;
                                         case in_array('country', $type):
                                         case in_array('world_region', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country'));
                                             break;
                                         case in_array('state_province', $type):
                                             $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province'));
                                             break;
                                         default:
                                             $row[$field . '_' . $fldValue] = $relDAO->{$fldValue};
                                             break;
                                     }
                                 }
                             }
                         } elseif (isset($fieldValue) && $fieldValue != '') {
                             //check for custom data
                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                             } else {
                                 //normal relationship fields
                                 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                 switch ($relationField) {
                                     case 'country':
                                     case 'world_region':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                         break;
                                     case 'state_province':
                                         $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                         break;
                                     default:
                                         $row[$field . $relationField] = $fieldValue;
                                         break;
                                 }
                             }
                         } else {
                             // if relation field is empty or null
                             $row[$field . $relationField] = '';
                         }
                     }
                 } elseif (isset($fieldValue) && $fieldValue != '') {
                     //check for custom data
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                     } elseif (array_key_exists($field, $multipleSelectFields)) {
                         //option group fixes
                         $paramsNew = array($field => $fieldValue);
                         if ($field == 'test_tutoring') {
                             $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                             // for  readers group
                         } elseif (substr($field, 0, 4) == 'cmr_') {
                             $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                         } else {
                             $name = array($field => array('newName' => $field, 'groupName' => $field));
                         }
                         CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                         $row[$field] = $paramsNew[$field];
                     } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                         //special case for greeting replacement
                         $fldValue = "{$field}_display";
                         $row[$field] = $iterationDAO->{$fldValue};
                     } else {
                         //normal fields with a touch of CRM-3157
                         switch ($field) {
                             case 'country':
                             case 'world_region':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                 break;
                             case 'state_province':
                                 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                 break;
                             case 'gender':
                             case 'preferred_communication_method':
                             case 'preferred_mail_format':
                             case 'communication_style':
                                 $row[$field] = $i18n->crm_translate($fieldValue);
                                 break;
                             default:
                                 $row[$field] = $fieldValue;
                                 break;
                         }
                     }
                 } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
                     $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails);
                     $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date');
                     $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach (array_keys($paymentHeaders) as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // If specific payment fields have been selected for export, payment
             // data will already be in $row. Otherwise, add payment related
             // information, if appropriate.
             if ($addPaymentHeader) {
                 if (!$selectedPaymentFields) {
                     if ($paymentFields) {
                         $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
                         if (!is_array($paymentData) || empty($paymentData)) {
                             $paymentData = $nullContributionDetails;
                         }
                         $row = array_merge($row, $paymentData);
                     } elseif (!empty($paymentDetails)) {
                         $row = array_merge($row, $nullContributionDetails);
                     }
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) {
                 $row['organization_name'] = '';
             }
             // add component info
             // write the row to a file
             $componentDetails[] = $row;
             // output every $tempRowCount rows
             if ($count % $tempRowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     if ($exportTempTable) {
         self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
         // do merge same address and merge same household processing
         if ($mergeSameAddress) {
             self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
         }
         // merge the records if they have corresponding households
         if ($mergeSameHousehold) {
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
             self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
         }
         // fix the headers for rows with relationship type
         if (!empty($relName)) {
             self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
         }
         // if postalMailing option is checked, exclude contacts who are deceased, have
         // "Do not mail" privacy setting, or have no street address
         if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) {
             self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         }
         // call export hook
         CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // now write the CSV file
         self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
         // delete the export temp table and component table
         $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
         CRM_Core_DAO::executeQuery($sql);
         CRM_Utils_System::civiExit();
     } else {
         CRM_Core_Error::fatal(ts('No records to export'));
     }
 }
Beispiel #24
0
 /**
  * called to delete the relationship of a contact.
  *
  */
 public function delete()
 {
     // calls a function to delete relationship
     CRM_Contact_BAO_Relationship::del($this->_id);
 }
Beispiel #25
0
 /**
  * Clear cached current employer name.
  *
  * @param int $contactId
  *   Contact id ( mostly individual contact id).
  * @param int $employerId
  *   Contact id ( mostly organization contact id).
  */
 public static function clearCurrentEmployer($contactId, $employerId = NULL)
 {
     $query = "UPDATE civicrm_contact\nSET organization_name=NULL, employer_id = NULL\nWHERE id={$contactId}; ";
     $dao = CRM_Core_DAO::executeQuery($query);
     // need to handle related meberships. CRM-3792
     if ($employerId) {
         //1. disable corresponding relationship.
         //2. delete related membership.
         //get the relationship type id of "Employee of"
         $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
         if (!$relTypeId) {
             CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
         }
         $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
         $relMembershipParams['contact_check'][$employerId] = 1;
         //get relationship id.
         if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) {
             $relationship = new CRM_Contact_DAO_Relationship();
             $relationship->contact_id_a = $contactId;
             $relationship->contact_id_b = $employerId;
             $relationship->relationship_type_id = $relTypeId;
             if ($relationship->find(TRUE)) {
                 CRM_Contact_BAO_Relationship::setIsActive($relationship->id, FALSE);
                 CRM_Contact_BAO_Relationship::relatedMemberships($contactId, $relMembershipParams, $ids = array(), CRM_Core_Action::DELETE);
             }
             $relationship->free();
         }
     }
 }
Beispiel #26
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     //to save the current mappings
     if (!$this->get('savedMapping')) {
         $saveDetailsName = ts('Save this field mapping');
         $this->applyFilter('saveMappingName', 'trim');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     } else {
         $savedMapping = $this->get('savedMapping');
         list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
         //get loaded Mapping Fields
         $mappingName = CRM_Utils_Array::value(1, $mappingName);
         $mappingContactType = CRM_Utils_Array::value(1, $mappingContactType);
         $mappingLocation = CRM_Utils_Array::value(1, $mappingLocation);
         $mappingPhoneType = CRM_Utils_Array::value(1, $mappingPhoneType);
         $mappingImProvider = CRM_Utils_Array::value(1, $mappingImProvider);
         $mappingRelation = CRM_Utils_Array::value(1, $mappingRelation);
         $mappingWebsiteType = CRM_Utils_Array::value(1, $mappingWebsiteType);
         $this->assign('loadedMapping', $savedMapping);
         $this->set('loadedMapping', $savedMapping);
         $params = array('id' => $savedMapping);
         $temp = array();
         $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
         $this->assign('savedName', $mappingDetails->name);
         $this->add('hidden', 'mappingId', $savedMapping);
         $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
         $saveDetailsName = ts('Save as a new field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     }
     $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
     $this->addFormRule(array('CRM_Contact_Import_Form_MapField', 'formRule'));
     //-------- end of saved mapping stuff ---------
     $defaults = array();
     $mapperKeys = array_keys($this->_mapperFields);
     $hasColumnNames = !empty($this->_columnNames);
     $columnPatterns = $this->get('columnPatterns');
     $dataPatterns = $this->get('dataPatterns');
     $hasLocationTypes = $this->get('fieldTypes');
     $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
     // Pass default location to js
     if ($defaultLocationType) {
         $this->assign('defaultLocationType', $defaultLocationType->id);
         $this->assign('defaultLocationTypeLabel', $this->_location_types[$defaultLocationType->id]);
     }
     /* Initialize all field usages to false */
     foreach ($mapperKeys as $key) {
         $this->_fieldUsed[$key] = FALSE;
     }
     $sel1 = $this->_mapperFields;
     $sel2[''] = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
     foreach ($this->_location_types as $key => $value) {
         $sel3['phone'][$key] =& $phoneTypes;
         //build array for IM service provider type for contact
         $sel3['im'][$key] =& $imProviders;
     }
     $sel4 = NULL;
     // store and cache all relationship types
     $contactRelation = new CRM_Contact_DAO_RelationshipType();
     $contactRelation->find();
     while ($contactRelation->fetch()) {
         $contactRelationCache[$contactRelation->id] = array();
         $contactRelationCache[$contactRelation->id]['contact_type_a'] = $contactRelation->contact_type_a;
         $contactRelationCache[$contactRelation->id]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a;
         $contactRelationCache[$contactRelation->id]['contact_type_b'] = $contactRelation->contact_type_b;
         $contactRelationCache[$contactRelation->id]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b;
     }
     $highlightedFields = $highlightedRelFields = array();
     $highlightedFields['email'] = 'All';
     $highlightedFields['external_identifier'] = 'All';
     $highlightedFields['first_name'] = 'Individual';
     $highlightedFields['last_name'] = 'Individual';
     $highlightedFields['household_name'] = 'Household';
     $highlightedFields['organization_name'] = 'Organization';
     foreach ($mapperKeys as $key) {
         // check if there is a _a_b or _b_a in the key
         if (strpos($key, '_a_b') || strpos($key, '_b_a')) {
             list($id, $first, $second) = explode('_', $key);
         } else {
             $id = $first = $second = NULL;
         }
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $cType = $contactRelationCache[$id]["contact_type_{$second}"];
             //CRM-5125 for contact subtype specific relationshiptypes
             $cSubType = NULL;
             if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) {
                 $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"];
             }
             if (!$cType) {
                 $cType = 'All';
             }
             $relatedFields = array();
             $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType);
             unset($relatedFields['']);
             $values = array();
             foreach ($relatedFields as $name => $field) {
                 $values[$name] = $field['title'];
                 if (isset($hasLocationTypes[$name])) {
                     $sel3[$key][$name] = $this->_location_types;
                 } elseif ($name == 'url') {
                     $sel3[$key][$name] = $websiteTypes;
                 } else {
                     $sel3[$name] = NULL;
                 }
             }
             //fix to append custom group name to field name, CRM-2676
             if (empty($this->_formattedFieldNames[$cType]) || $cType == $this->_contactType) {
                 $this->_formattedFieldNames[$cType] = $this->formatCustomFieldName($values);
             }
             $this->_formattedFieldNames[$cType] = array_merge($values, $this->_formattedFieldNames[$cType]);
             //Modified the Relationship fields if the fields are
             //present in dedupe rule
             if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) && is_array($this->_dedupeFields[$cType])) {
                 static $cTypeArray = array();
                 if ($cType != $this->_contactType && !in_array($cType, $cTypeArray)) {
                     foreach ($this->_dedupeFields[$cType] as $val) {
                         if ($valTitle = CRM_Utils_Array::value($val, $this->_formattedFieldNames[$cType])) {
                             $this->_formattedFieldNames[$cType][$val] = $valTitle . ' (match to contact)';
                         }
                     }
                     $cTypeArray[] = $cType;
                 }
             }
             foreach ($highlightedFields as $k => $v) {
                 if ($v == $cType || $v == 'All') {
                     $highlightedRelFields[$key][] = $k;
                 }
             }
             $this->assign('highlightedRelFields', $highlightedRelFields);
             $sel2[$key] = $this->_formattedFieldNames[$cType];
             if (!empty($cSubType)) {
                 //custom fields for sub type
                 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($cSubType);
                 if (!empty($subTypeFields)) {
                     $subType = NULL;
                     foreach ($subTypeFields as $customSubTypeField => $details) {
                         $subType[$customSubTypeField] = $details['title'];
                         $sel2[$key] = array_merge($sel2[$key], $this->formatCustomFieldName($subType));
                     }
                 }
             }
             foreach ($this->_location_types as $k => $value) {
                 $sel4[$key]['phone'][$k] =& $phoneTypes;
                 //build array of IM service provider for related contact
                 $sel4[$key]['im'][$k] =& $imProviders;
             }
         } else {
             $options = NULL;
             if (!empty($hasLocationTypes[$key])) {
                 $options = $this->_location_types;
             } elseif ($key == 'url') {
                 $options = $websiteTypes;
             }
             $sel2[$key] = $options;
         }
     }
     $js = "<script type='text/javascript'>\n";
     $formName = 'document.forms.' . $this->_name;
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL);
         $jsSet = FALSE;
         if ($this->get('savedMapping')) {
             if (isset($mappingName[$i])) {
                 if ($mappingName[$i] != ts('- do not import -')) {
                     if (isset($mappingRelation[$i])) {
                         // relationship mapping
                         switch ($this->get('contactType')) {
                             case CRM_Import_Parser::CONTACT_INDIVIDUAL:
                                 $contactType = 'Individual';
                                 break;
                             case CRM_Import_Parser::CONTACT_HOUSEHOLD:
                                 $contactType = 'Household';
                                 break;
                             case CRM_Import_Parser::CONTACT_ORGANIZATION:
                                 $contactType = 'Organization';
                         }
                         //CRM-5125
                         $contactSubType = NULL;
                         if ($this->get('contactSubType')) {
                             $contactSubType = $this->get('contactSubType');
                         }
                         $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType, FALSE, 'label', TRUE, $contactSubType);
                         foreach ($relations as $key => $var) {
                             if ($key == $mappingRelation[$i]) {
                                 $relation = $key;
                                 break;
                             }
                         }
                         $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i]));
                         $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
                         $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
                         $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
                         //get provider id from saved mappings
                         $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
                         if ($websiteTypeId) {
                             $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $websiteTypeId);
                             if (!$websiteTypeId) {
                                 $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                             }
                         } else {
                             // default for IM/phone when mapping with relation is true
                             $typeId = NULL;
                             if (isset($phoneType)) {
                                 $typeId = $phoneType;
                             } elseif (isset($imProvider)) {
                                 $typeId = $imProvider;
                             }
                             $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $locationId, $typeId);
                             if (!$locationId) {
                                 $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                             }
                         }
                         // fix for edge cases, CRM-4954
                         if ($contactDetails == 'image_url') {
                             $contactDetails = str_replace('url', 'URL', $contactDetails);
                         }
                         if (!$contactDetails) {
                             $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                         }
                         if (!$phoneType && !$imProvider) {
                             $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                         }
                         //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
                         $jsSet = TRUE;
                     } else {
                         $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
                         $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
                         $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
                         $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
                         // get IM service provider id
                         $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
                         if ($websiteTypeId) {
                             if (!$websiteTypeId) {
                                 $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                             }
                             $defaults["mapper[{$i}]"] = array($mappingHeader[0], $websiteTypeId);
                         } else {
                             if (!$locationId) {
                                 $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                             }
                             //default for IM/phone without related contact
                             $typeId = NULL;
                             if (isset($phoneType)) {
                                 $typeId = $phoneType;
                             } elseif (isset($imProvider)) {
                                 $typeId = $imProvider;
                             }
                             $defaults["mapper[{$i}]"] = array($mappingHeader[0], $locationId, $typeId);
                         }
                         if (!$phoneType && !$imProvider) {
                             $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                         }
                         $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                         $jsSet = TRUE;
                     }
                 } else {
                     $defaults["mapper[{$i}]"] = array();
                 }
                 if (!$jsSet) {
                     for ($k = 1; $k < 4; $k++) {
                         $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                     }
                 }
             } else {
                 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
                 $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n";
                 if ($hasColumnNames) {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns));
                 } else {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i));
                 }
             }
             //end of load mapping
         } else {
             $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n";
             if ($hasColumnNames) {
                 // do array search first to see if has mapped key
                 $columnKey = '';
                 $columnKey = array_search($this->_columnNames[$i], $this->_mapperFields);
                 if (isset($this->_fieldUsed[$columnKey])) {
                     $defaults["mapper[{$i}]"] = $columnKey;
                     $this->_fieldUsed[$key] = TRUE;
                 } else {
                     // Infer the default from the column names if we have them
                     $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns), 0);
                 }
             } else {
                 // Otherwise guess the default from the form of the data
                 $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0);
             }
         }
         $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     }
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     //set warning if mismatch in more than
     if (isset($mappingName) && $this->_columnCount != count($mappingName)) {
         $warning++;
     }
     if ($warning != 0 && $this->get('savedMapping')) {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
     } else {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(NULL);
     }
     $this->setDefaults($defaults);
     $this->addButtons(array(array('type' => 'back', 'name' => ts('Previous')), array('type' => 'next', 'name' => ts('Continue'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
function civicrm_api3_pcpteams_checkTeamAdmin($params)
{
    $teamRelTypeName = CRM_Pcpteams_Constant::C_TEAM_ADMIN_REL_TYPE;
    $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $teamRelTypeName, 'id', 'name_a_b');
    $reltionships = CRM_Contact_BAO_Relationship::getRelationship($params['user_id'], CRM_Contact_BAO_Relationship::CURRENT);
    $result['user_id'] = $params['user_id'];
    $result['is_team_admin'] = 0;
    $result['team_contact_id'] = $params['team_contact_id'];
    foreach ($reltionships as $relId => $relValue) {
        if ($relTypeId == $relValue['relationship_type_id'] && $params['team_contact_id'] == $relValue['contact_id_b'] && $relValue['is_active']) {
            $result['relationship_id'] = $relValue['id'];
            $result['is_team_admin'] = 1;
        }
    }
    return $result;
}
 /**
  * function for validation
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return mixed true or array of errors
  * @access public
  * @static
  */
 function formRule(&$params)
 {
     // hack, no error check for refresh
     if (CRM_Utils_Array::value('_qf_Relationship_refresh', $_POST)) {
         return true;
     }
     $ids = array();
     $session =& CRM_Core_Session::singleton();
     $ids['contact'] = $session->get('contactId', 'CRM_Contact_Form_Relationship');
     $ids['relationship'] = $session->get('relationshipId', 'CRM_Contact_Form_Relationship');
     $errors = array();
     if (CRM_Utils_Array::value('contact_check', $params) && is_array($params['contact_check'])) {
         foreach ($params['contact_check'] as $cid => $dontCare) {
             $message = CRM_Contact_BAO_Relationship::checkValidRelationship($params, $ids, $cid);
             if ($message) {
                 $errors['relationship_type_id'] = $message;
                 break;
             }
         }
     } else {
         $errors['contact_check'] = ts('Please select at least one contact.');
     }
     return empty($errors) ? true : $errors;
 }
Beispiel #29
0
 /**
  * Check the membership extended through relationship.
  *
  * @param int $membershipId
  *   Membership id.
  * @param int $contactId
  *   Contact id.
  *
  * @param int $action
  *
  * @return array
  *   array of contact_id of all related contacts.
  */
 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action::ADD)
 {
     $contacts = array();
     $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
     $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
     $relationships = array();
     if (isset($membershipType['relationship_type_id'])) {
         $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::CURRENT);
         if ($action & CRM_Core_Action::UPDATE) {
             $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::PAST);
             $relationships = array_merge($relationships, $pastRelationships);
         }
     }
     if (!empty($relationships)) {
         // check for each contact relationships
         foreach ($relationships as $values) {
             //get details of the relationship type
             $relType = array('id' => $values['civicrm_relationship_type_id']);
             $relValues = array();
             CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues);
             // Check if contact's relationship type exists in membership type
             $relTypeDirs = array();
             $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
             $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
             $bidirectional = FALSE;
             foreach ($relTypeIds as $key => $value) {
                 $relTypeDirs[] = $value . '_' . $relDirections[$key];
                 if (in_array($value, $relType) && $relValues['name_a_b'] == $relValues['name_b_a']) {
                     $bidirectional = TRUE;
                     break;
                 }
             }
             $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
             if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) {
                 // $values['status'] is going to have value for
                 // current or past relationships.
                 $contacts[$values['cid']] = $values['status'];
             }
         }
     }
     // Sort by contact_id ascending
     ksort($contacts);
     return $contacts;
 }
 /**
  * Wrapper for contact relationship selector.
  *
  * @param array $params
  *   Associated array for params record id.
  *
  * @return array
  *   associated array of contact relationships
  */
 public static function getContactRelationshipSelector(&$params)
 {
     // format the params
     $params['offset'] = ($params['page'] - 1) * $params['rp'];
     $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
     if ($params['context'] == 'past') {
         $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
     } elseif ($params['context'] == 'all') {
         $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
     } else {
         $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
     }
     // check logged in user for permission
     $page = new CRM_Core_Page();
     CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
     $permissions = array($page->_permission);
     if ($page->_permission == CRM_Core_Permission::EDIT) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $permissionedContacts = TRUE;
     if ($params['context'] != 'user') {
         $links = CRM_Contact_Page_View_Relationship::links();
     } else {
         $links = CRM_Contact_Page_View_UserDashBoard::links();
         $mask = NULL;
     }
     // get contact relationships
     $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], $relationshipStatus, $params['rp'], 0, 0, $links, $mask, $permissionedContacts, $params);
     $contactRelationships = array();
     $params['total'] = 0;
     if (!empty($relationships)) {
         // FIXME: we cannot directly determine total permissioned relationship, hence re-fire query
         $permissionedRelationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], $relationshipStatus, 0, 0, 0, NULL, NULL, $permissionedContacts);
         $params['total'] = count($permissionedRelationships);
         // format params
         foreach ($relationships as $relationshipId => $values) {
             $relationship = array();
             $relationship['DT_RowId'] = $values['id'];
             $relationship['DT_RowClass'] = 'crm-entity';
             if ($values['is_active'] == 0) {
                 $relationship['DT_RowClass'] .= ' disabled';
             }
             $relationship['DT_RowAttr'] = array();
             $relationship['DT_RowAttr']['data-entity'] = 'relationship';
             $relationship['DT_RowAttr']['data-id'] = $values['id'];
             //Add image icon for related contacts: CRM-14919
             $icon = CRM_Contact_BAO_Contact_Utils::getImage($values['contact_type'], FALSE, $values['cid']);
             $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System::href($values['name'], 'civicrm/contact/view', "reset=1&cid={$values['cid']}");
             $relationship['relation'] = CRM_Utils_System::href($values['relation'], 'civicrm/contact/view/rel', "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
             if ($params['context'] == 'current') {
                 if ($params['contact_id'] == $values['contact_id_a'] and $values['is_permission_a_b'] == 1 or $params['contact_id'] == $values['contact_id_b'] and $values['is_permission_b_a'] == 1) {
                     $relationship['sort_name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
                 }
                 if ($values['cid'] == $values['contact_id_a'] and $values['is_permission_a_b'] == 1 or $values['cid'] == $values['contact_id_b'] and $values['is_permission_b_a'] == 1) {
                     $relationship['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
                 }
             }
             if (!empty($values['description'])) {
                 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
             }
             $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
             $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
             $relationship['city'] = $values['city'];
             $relationship['state'] = $values['state'];
             $relationship['email'] = $values['email'];
             $relationship['phone'] = $values['phone'];
             $relationship['links'] = $values['action'];
             array_push($contactRelationships, $relationship);
         }
     }
     $relationshipsDT = array();
     $relationshipsDT['data'] = $contactRelationships;
     $relationshipsDT['recordsTotal'] = $params['total'];
     $relationshipsDT['recordsFiltered'] = $params['total'];
     return $relationshipsDT;
 }