/** * Set the default form values * * @access protected * * @return array the default array reference */ function setDefaultValues() { $defaults = array(); $stateCountryMap = array(); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } //CRM-5403 if (substr($name, 0, 14) === 'state_province' || substr($name, 0, 7) === 'country' || substr($name, 0, 6) === 'county') { list($fieldName, $index) = CRM_Utils_System::explode('-', $name, 2); if (!array_key_exists($index, $stateCountryMap)) { $stateCountryMap[$index] = array(); } $stateCountryMap[$index][$fieldName] = $name; } } // also take care of state country widget if (!empty($stateCountryMap)) { CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap, $defaults); } //set default for country. CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $defaults); // now fix all state country selectors CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); return $defaults; }
/** * @inheritDoc */ protected function buildWhereClause() { foreach ($this->where as $key => $value) { $table_name = NULL; $column_name = NULL; $field = $this->getField($key); if (in_array($key, $this->entityFieldNames)) { $table_name = self::MAIN_TABLE_ALIAS; $column_name = $key; } elseif (($cf_id = \CRM_Core_BAO_CustomField::getKeyID($key)) != FALSE) { //list($table_name, $column_name) = $this->addCustomField($this->apiFieldSpec['custom_' . $cf_id], 'INNER'); } elseif (strpos($key, '.')) { $fkInfo = $this->addFkField($key, 'INNER'); if ($fkInfo) { list($table_name, $column_name) = $fkInfo; $this->validateNestedInput($key, $value); } } if (!$table_name || !$column_name || is_null($value)) { throw new \API_Exception("Invalid field '{$key}' in where clause."); } if (!is_array($value)) { $this->query->where(array("`{$table_name}`.`{$column_name}` = @value"), array("@value" => $value)); } elseif (count($value) !== 1) { throw new \API_Exception("Invalid value in where clause for field '{$key}'"); } else { $clause = \CRM_Core_DAO::createSQLFilter("`{$table_name}`.`{$column_name}`", $value); if ($clause === NULL) { throw new \API_Exception("Invalid value in where clause for field '{$key}'"); } $this->query->where($clause); } } }
/** * Function the check whether the field belongs. * to multi-record custom set */ public function checkIsMultiRecord() { $customId = $_GET['customId']; $isMultiple = CRM_Core_BAO_CustomField::isMultiRecordField($customId); $isMultiple = array('is_multi' => $isMultiple); CRM_Utils_JSON::output($isMultiple); }
function setUp() { parent::setUp(); // Create Group For Individual Contact Type $groupIndividual = array('title' => 'TestGroup For Indivi' . substr(sha1(rand()), 0, 5), 'extends' => array('Individual'), 'style' => 'Inline', 'is_active' => 1); $this->CustomGroupIndividual = $this->customGroupCreate($groupIndividual); $this->IndividualField = $this->customFieldCreate(array('custom_group_id' => $this->CustomGroupIndividual['id'])); // Create Group For Individual-Student Contact Sub Type $groupIndiStudent = array('title' => 'Student Test' . substr(sha1(rand()), 0, 5), 'extends' => array('Individual', array('Student')), 'style' => 'Inline', 'is_active' => 1); $this->CustomGroupIndiStudent = $this->customGroupCreate($groupIndiStudent); $this->IndiStudentField = $this->customFieldCreate(array('custom_group_id' => $this->CustomGroupIndiStudent['id'])); $params = array('first_name' => 'Mathev', 'last_name' => 'Adison', 'contact_type' => 'Individual'); $this->individual = $this->individualCreate($params); $params = array('first_name' => 'Steve', 'last_name' => 'Tosun', 'contact_type' => 'Individual', 'contact_sub_type' => 'Student'); $this->individualStudent = $this->individualCreate($params); $params = array('first_name' => 'Mark', 'last_name' => 'Dawson', 'contact_type' => 'Individual', 'contact_sub_type' => 'Parent'); $this->individualParent = $this->individualCreate($params); $params = array('organization_name' => 'Wellspring', 'contact_type' => 'Organization'); $this->organization = $this->organizationCreate($params); $params = array('organization_name' => 'SubUrban', 'contact_type' => 'Organization', 'contact_sub_type' => 'Sponsor'); $this->organizationSponsor = $this->organizationCreate($params); //refresh php cached variables CRM_Core_PseudoConstant::flush(); CRM_Core_BAO_CustomField::getTableColumnGroup($this->IndividualField['id'], True); CRM_Core_BAO_CustomField::getTableColumnGroup($this->IndiStudentField['id'], True); }
function setDefaultValues() { // check if the user is registered and we have a contact ID $session =& CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($contactID) { $options = array(); $fields = array(); foreach ($this->_fields as $name => $dontCare) { $fields[$name] = 1; } $fields['state_province'] = $fields['country'] = $fields['email'] = 1; $contact =& CRM_Contact_BAO_Contact::contactDetails($contactID, $options, $fields); foreach ($fields as $name => $dontCare) { if ($contact->{$name}) { if (substr($name, 0, 7) == 'custom_') { $id = substr($name, 7); $this->_defaults[$name] = CRM_Core_BAO_CustomField::getDefaultValue($contact->{$name}, $id, $options); } else { $this->_defaults[$name] = $contact->{$name}; } } } } // hack to simplify credit card entry for testing /** $this->_defaults['credit_card_type'] = 'Visa'; $this->_defaults['credit_card_number'] = '4807731747657838'; $this->_defaults['cvv2'] = '000'; $this->_defaults['credit_card_exp_date'] = array( 'Y' => '2008', 'M' => '01' ); **/ return $this->_defaults; }
/** * Function the check whether the field belongs * to multi-record custom set */ function checkIsMultiRecord() { $customId = $_GET['customId']; $isMultiple = CRM_Core_BAO_CustomField::isMultiRecordField($customId); $isMultiple = array('is_multi' => $isMultiple); echo json_encode($isMultiple); CRM_Utils_System::civiExit(); }
/** * Process the form when submitted. * * @return void */ public function postProcess() { $field = new CRM_Core_DAO_CustomField(); $field->id = $this->_id; $field->find(TRUE); CRM_Core_BAO_CustomField::deleteField($field); // also delete any profiles associted with this custom field CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', array(1 => $field->label)), '', 'success'); }
function testDeleteCustomfield() { $customGroup = Custom::createGroup(array(), 'Individual'); $fields = array('groupId' => $customGroup->id, 'dataType' => 'Memo', 'htmlType' => 'TextArea'); $customField = Custom::createField(array(), $fields); CRM_Core_BAO_CustomField::deleteField($customField); $this->assertDBNull('CRM_Core_DAO_CustomField', $customGroup->id, 'id', 'custom_group_id', 'Database check for deleted Custom Field.'); Custom::deleteGroup($customGroup); }
/** * Set the default form values. * * * @return array * the default array reference */ public function setDefaultValues() { $defaults = array(); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } } //set default for country. CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $defaults); return $defaults; }
/** * Test setValues() and getValues() methods with custom field YesNo(Boolean) Radio */ public function testSetGetValuesYesNoRadio() { $params = array(); $contactID = Contact::createIndividual(); //create Custom Group $customGroup = Custom::createGroup($params, 'Individual', TRUE); //create Custom Field of type YesNo(Boolean) Radio $fields = array('groupId' => $customGroup->id, 'dataType' => 'Boolean', 'htmlType' => 'Radio'); $customField = Custom::createField($params, $fields); // Retrieve the field ID for sample custom field 'test_Boolean' $params = array('label' => 'test_Boolean'); $field = array(); //get field Id CRM_Core_BAO_CustomField::retrieve($params, $field); $fieldID = $field['id']; // valid boolean value '1' for Boolean Radio $yesNo = '1'; $params = array('entityID' => $contactID, 'custom_' . $fieldID => $yesNo); $result = CRM_Core_BAO_CustomValueTable::setValues($params); $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).'); // Check that the YesNo radio value is stored $values = array(); $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1); $values = CRM_Core_BAO_CustomValueTable::getValues($params); $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).'); $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the boolean value is stored for contact ' . $contactID); // Now set YesNo radio to an invalid boolean value and try to reset $badYesNo = '20'; $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badYesNo); $errorScope = CRM_Core_TemporaryErrorScope::useException(); $message = NULL; try { $result = CRM_Core_BAO_CustomValueTable::setValues($params); } catch (Exception $e) { $message = $e->getMessage(); } $errorScope = NULL; // Check that an exception has been thrown $this->assertNotNull($message, 'Verify than an exception is thrown when bad boolean is passed'); $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1); $values = CRM_Core_BAO_CustomValueTable::getValues($params); $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the date value has NOT been updated for contact ' . $contactID); // Cleanup Custom::deleteField($customField); Custom::deleteGroup($customGroup); Contact::delete($contactID); }
/** * Build the form object. */ public function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } $this->_title = ts('Update multiple contacts') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } } //FIX ME: phone ext field is added at the end and it gets removed because of below code //$this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Contact(s)'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_contactIds); // if below fields are missing we should not reset sort name / display name // CRM-6794 $preserveDefaultsArray = array('first_name', 'last_name', 'middle_name', 'organization_name', 'prefix_id', 'suffix_id', 'household_name'); foreach ($this->_contactIds as $contactId) { $profileFields = $this->_fields; CRM_Core_BAO_Address::checkContactSharedAddressFields($profileFields, $contactId); foreach ($profileFields as $name => $field) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId); if (in_array($field['name'], $preserveDefaultsArray)) { $this->_preserveDefault = FALSE; } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields && $buttonName != '_qf_BatchUpdateProfile_next') { CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple contacts."), ts('Some Fields Excluded'), 'info'); } $this->addDefaultButtons(ts('Update Contacts')); $this->addFormRule(array('CRM_Contact_Form_Task_Batch', 'formRule')); }
/** * File for the CiviCRM APIv3 group functions * * @package CiviCRM_APIv3 * @subpackage API_pcpteams * @copyright CiviCRM LLC (c) 2004-2014 */ function civicrm_api3_pcpteams_create($params) { // since we are allowing html input from the user // we also need to purify it, so lets clean it up // $params['pcp_title'] = $pcp['title']; // $params['pcp_contact_id'] = $pcp['contact_id']; $htmlFields = array('intro_text', 'page_text', 'title'); foreach ($htmlFields as $field) { if (!empty($params[$field])) { $params[$field] = CRM_Utils_String::purifyHTML($params[$field]); } } $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']); $pcpBlock = new CRM_PCP_DAO_PCPBlock(); $pcpBlock->entity_table = $entity_table; $pcpBlock->entity_id = $params['page_id']; $pcpBlock->find(TRUE); $params['pcp_block_id'] = $pcpBlock->id; $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']); // 1 -> waiting review // 2 -> active / approved (default for now) $params['status_id'] = CRM_Utils_Array::value('status_id', $params, 2); // active by default for now $params['is_active'] = CRM_Utils_Array::value('is_active', $params, 1); $pcp = CRM_Pcpteams_BAO_PCP::create($params, FALSE); //Custom Set $customFields = CRM_Core_BAO_CustomField::getFields('PCP', FALSE, FALSE, NULL, NULL, TRUE); $isCustomValueSet = FALSE; foreach ($customFields as $fieldID => $fieldValue) { list($tableName, $columnName, $cgId) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID); if (!empty($params[$columnName]) || !empty($params["custom_{$fieldID}"])) { $isCustomValueSet = TRUE; //FIXME: to find out the custom value exists, set -1 as default now $params["custom_{$fieldID}_-1"] = !empty($params[$columnName]) ? $params[$columnName] : $params["custom_{$fieldID}"]; } } if ($isCustomValueSet) { $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $pcp->id, 'PCP'); CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pcp', $pcp->id); } //end custom set $values = array(); @_civicrm_api3_object_to_array_unique_fields($pcp, $values[$pcp->id]); return civicrm_api3_create_success($values, $params, 'Pcpteams', 'create'); }
static function registerInterview() { $fields = array('result', 'voter_id', 'survey_id', 'activity_id', 'surveyTitle', 'interviewer_id', 'activity_type_id'); $params = array(); foreach ($fields as $fld) { $params[$fld] = CRM_Utils_Array::value($fld, $_POST); } $params['details'] = CRM_Utils_Array::value('note', $_POST); $voterId = $params['voter_id']; $activityId = $params['activity_id']; $customKey = "field_{$voterId}_custom"; foreach ($_POST as $key => $value) { if (strpos($key, $customKey) !== FALSE) { $customFieldKey = str_replace(str_replace(substr($customKey, -6), '', $customKey), '', $key); $params[$customFieldKey] = $value; } } if (isset($_POST['field']) && !empty($_POST['field'][$voterId]) && is_array($_POST['field'][$voterId])) { foreach ($_POST['field'][$voterId] as $fieldKey => $value) { $params[$fieldKey] = $value; } } //lets pickup contat related fields. foreach ($_POST as $key => $value) { if (strpos($key, "field_{$voterId}_") !== FALSE && strpos($key, "field_{$voterId}_custom") === FALSE) { $key = substr($key, strlen("field_{$voterId}_")); $params[$key] = $value; } } $result = array('status' => 'fail', 'voter_id' => $voterId, 'activity_id' => $params['interviewer_id']); //time to validate custom data. $errors = CRM_Core_BAO_CustomField::validateCustomData($params); if (is_array($errors) && !empty($errors)) { $result['errors'] = $errors; echo json_encode($result); CRM_Utils_System::civiExit(); } //process the response/interview data. $activityId = CRM_Campaign_Form_Task_Interview::registerInterview($params); if ($activityId) { $result['status'] = 'success'; } echo json_encode($result); CRM_Utils_System::civiExit(); }
/** * Create() method with custom data. */ public function testCreateWithCustomData() { $contactId = $this->individualCreate(); //create custom data $customGroup = $this->customGroupCreate(array('extends' => 'Contribution')); $customGroupID = $customGroup['id']; $customGroup = $customGroup['values'][$customGroupID]; $fields = array('label' => 'testFld', 'data_type' => 'String', 'html_type' => 'Text', 'is_active' => 1, 'custom_group_id' => $customGroupID); $customField = CRM_Core_BAO_CustomField::create($fields); $params = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 1, 'contribution_status_id' => 1, 'payment_instrument_id' => 1, 'source' => 'STUDENT', 'receive_date' => '20080522000000', 'receipt_date' => '20080522000000', 'id' => NULL, 'non_deductible_amount' => 0.0, 'total_amount' => 200.0, 'fee_amount' => 5, 'net_amount' => 195, 'trxn_id' => '22ereerwww322323', 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70', 'thankyou_date' => '20080522'); $params['custom'] = array($customField->id => array(-1 => array('value' => 'Test custom value', 'type' => 'String', 'custom_field_id' => $customField->id, 'custom_group_id' => $customGroupID, 'table_name' => $customGroup['table_name'], 'column_name' => $customField->column_name, 'file_id' => NULL))); $contribution = CRM_Contribute_BAO_Contribution::create($params); // Check that the custom field value is saved $customValueParams = array('entityID' => $contribution->id, 'custom_' . $customField->id => 1); $values = CRM_Core_BAO_CustomValueTable::getValues($customValueParams); $this->assertEquals('Test custom value', $values['custom_' . $customField->id], 'Check the custom field value'); $this->assertEquals($params['trxn_id'], $contribution->trxn_id, 'Check for transcation id creation.'); $this->assertEquals($contactId, $contribution->contact_id, 'Check for contact id for Conribution.'); }
static function registerInterview() { $fields = array('result', 'voter_id', 'ufGroupId', 'activity_id', 'surveyTitle', 'interviewer_id', 'activity_type_id'); $params = array(); foreach ($fields as $fld) { $params[$fld] = CRM_Utils_Array::value($fld, $_POST); } $params['details'] = CRM_Utils_Array::value('note', $_POST); $voterId = $params['voter_id']; $activityId = $params['activity_id']; $customKey = "field_{$voterId}_custom"; foreach ($_POST as $key => $value) { if (strpos($key, $customKey) !== false) { $customFieldKey = str_replace(str_replace(substr($customKey, -6), '', $customKey), '', $key); $params[$customFieldKey] = $value; } } if (isset($_POST['field']) && CRM_Utils_Array::value($voterId, $_POST['field']) && is_array($_POST['field'][$voterId])) { foreach ($_POST['field'][$voterId] as $fieldKey => $value) { $params[$fieldKey] = $value; } } require_once "CRM/Utils/JSON.php"; $result = array('status' => 'fail', 'voter_id' => $voterId, 'activity_id' => $params['interviewer_id']); //time to validate custom data. require_once 'CRM/Core/BAO/CustomField.php'; $errors = CRM_Core_BAO_CustomField::validateCustomData($params); if (is_array($errors) && !empty($errors)) { $result['errors'] = $errors; echo json_encode($result); CRM_Utils_System::civiExit(); } //process the response/interview data. require_once 'CRM/Campaign/Form/Task/Interview.php'; $activityId = CRM_Campaign_Form_Task_Interview::registerInterview($params); if ($activityId) { $result['status'] = 'success'; } require_once "CRM/Utils/JSON.php"; echo json_encode($result); CRM_Utils_System::civiExit(); }
function setDefaultValues() { if (!$this->_donorID) { return; } foreach ($this->_fields as $name => $dontcare) { $fields[$name] = 1; } require_once "CRM/Core/BAO/UFGroup.php"; CRM_Core_BAO_UFGroup::setProfileDefaults($this->_donorID, $fields, $this->_defaults); //set custom field defaults require_once "CRM/Core/BAO/CustomField.php"; foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { if (!isset($this->_defaults[$name])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } } } return $this->_defaults; }
function addColumns() { // add all the fields for chosen groups $this->_tables = $this->_options = array(); foreach ($this->_groupTree as $groupID => $group) { if (!CRM_Utils_Array::value($groupID, $this->_customGroupIDs)) { continue; } // now handle all the fields foreach ($group['fields'] as $fieldID => $field) { $this->_columns[$field['label']] = "custom_{$field['id']}"; if (!array_key_exists($group['table_name'], $this->_tables)) { $this->_tables[$group['table_name']] = array(); } $this->_tables[$group['table_name']][$field['id']] = $field['column_name']; // also build the option array $this->_options[$field['id']] = array(); CRM_Core_BAO_CustomField::buildOption($field, $this->_options[$field['id']]); } } }
function hrui_civicrm_buildForm($formName, &$form) { CRM_Core_Resources::singleton()->addStyleFile('org.civicrm.hrui', 'css/hrui.css')->addScriptFile('org.civicrm.hrui', 'js/hrui.js'); if ($form instanceof CRM_Contact_Form_Contact) { CRM_Core_Resources::singleton()->addSetting(array('formName' => 'contactForm')); //HR-358 - Set default values //set default value to phone location and type $locationId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Main', 'id', 'name'); $result = civicrm_api3('LocationType', 'create', array('id' => $locationId, 'is_default' => 1, 'is_active' => 1)); if ($form->elementExists('phone[2][phone_type_id]') && $form->elementExists('phone[2][phone_type_id]')) { $phoneType = $form->getElement('phone[2][phone_type_id]'); $phoneValue = CRM_Core_OptionGroup::values('phone_type'); $phoneKey = CRM_Utils_Array::key('Mobile', $phoneValue); $phoneType->setSelected($phoneKey); $phoneLocation = $form->getElement('phone[2][location_type_id]'); $phoneLocation->setSelected($locationId); } } $ogID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'type_20130502144049', 'id', 'name'); //HR-355 -- Add Government ID if ($formName == 'CRM_Contact_Form_Contact' && $ogID && $form->_contactType == 'Individual') { //add government fields $contactID = CRM_Utils_Request::retrieve('cid', 'Integer', $form); $templatePath = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('org.civicrm.hrui') . '/templates'; $form->add('text', 'GovernmentId', ts('Government ID')); $form->addElement('select', "govTypeOptions", '', CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($ogID)); CRM_Core_Region::instance('page-body')->add(array('template' => "{$templatePath}/CRM/HRUI/Form/contactField.tpl")); $action = CRM_Utils_Request::retrieve('action', 'String', $form); $govVal = CRM_HRIdent_Page_HRIdent::retreiveContactFieldValue($contactID); //set default to government type option $default = array(); $default['govTypeOptions'] = CRM_Core_BAO_CustomField::getOptionGroupDefault($ogID, 'select'); if ($action == CRM_Core_Action::UPDATE && !empty($govVal)) { //set key for updating specific record of contact id in custom value table $default['govTypeOptions'] = CRM_Utils_Array::value('type', $govVal); $default['GovernmentId'] = CRM_Utils_Array::value('typeNumber', $govVal); } $form->setDefaults($default); } }
/** * Form submission of new/edit contact is processed. */ public function postProcess() { // check if dedupe button, if so return. $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->_dedupeButtonName) { return; } //get the submitted values in an array $params = $this->controller->exportValues($this->_name); $group = CRM_Utils_Array::value('group', $params); if (!empty($group) && is_array($group)) { unset($params['group']); foreach ($group as $key => $value) { $params['group'][$value] = 1; } } CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues); if (!empty($params['image_URL'])) { CRM_Contact_BAO_Contact::processImageParams($params); } if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) { $params['current_employer'] = $params['current_employer_id']; } // don't carry current_employer_id field, // since we don't want to directly update DAO object without // handling related business logic ( eg related membership ) if (isset($params['current_employer_id'])) { unset($params['current_employer_id']); } $params['contact_type'] = $this->_contactType; if (empty($params['contact_sub_type']) && $this->_isContactSubType) { $params['contact_sub_type'] = array($this->_contactSubType); } if ($this->_contactId) { $params['contact_id'] = $this->_contactId; } //make deceased date null when is_deceased = false if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) { $params['is_deceased'] = FALSE; $params['deceased_date'] = NULL; } if (isset($params['contact_id'])) { // process membership status for deceased contact $deceasedParams = array('contact_id' => CRM_Utils_Array::value('contact_id', $params), 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE), 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL)); $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams); } // action is taken depending upon the mode if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params); } else { CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params); } $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE); //CRM-5143 //if subtype is set, send subtype as extend to validate subtype customfield $customFieldExtends = CRM_Utils_Array::value('contact_sub_type', $params) ? $params['contact_sub_type'] : $params['contact_type']; $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_contactId, $customFieldExtends, TRUE); if ($this->_contactId && !empty($this->_oldSubtypes)) { CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId, $params['contact_type'], $this->_oldSubtypes, $params['contact_sub_type']); } if (array_key_exists('CommunicationPreferences', $this->_editOptions)) { // this is a chekbox, so mark false if we dont get a POST value $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE); } // process shared contact address. CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']); if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) { unset($params['group']); } if (!empty($params['contact_id']) && $this->_action & CRM_Core_Action::UPDATE && !empty($params['group'])) { // figure out which all groups are intended to be removed $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added'); if (is_array($contactGroupList)) { foreach ($contactGroupList as $key) { if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) { $params['group'][$key['group_id']] = -1; } } } } // parse street address, CRM-5450 $parseStatusMsg = NULL; if ($this->_parseStreetAddress) { $parseResult = self::parseAddress($params); $parseStatusMsg = self::parseAddressStatusMsg($parseResult); } // Allow un-setting of location info, CRM-5969 $params['updateBlankLocInfo'] = TRUE; $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE); // status message if ($this->_contactId) { $message = ts('%1 has been updated.', array(1 => $contact->display_name)); } else { $message = ts('%1 has been created.', array(1 => $contact->display_name)); } // set the contact ID $this->_contactId = $contact->id; if (array_key_exists('TagsAndGroups', $this->_editOptions)) { //add contact to tags CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']); //save free tags if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) { CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this); } } if (!empty($parseStatusMsg)) { $message .= "<br />{$parseStatusMsg}"; } if (!empty($updateMembershipMsg)) { $message .= "<br />{$updateMembershipMsg}"; } $session = CRM_Core_Session::singleton(); $session->setStatus($message, ts('Contact Saved'), 'success'); // add the recently viewed contact $recentOther = array(); if ($session->get('userID') == $contact->id || CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id); } if ($session->get('userID') != $this->_contactId && CRM_Core_Permission::check('delete contacts')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id); } CRM_Utils_Recent::add($contact->display_name, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $contact->display_name, $recentOther); // here we replace the user context with the url to view this contact $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->getButtonName('upload', 'new')) { $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType)); $resetStr = "reset=1&ct={$contact->contact_type}"; $resetStr .= count($contactSubTypes) == 1 ? "&cst=" . array_pop($contactSubTypes) : ''; $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr)); } else { $context = CRM_Utils_Request::retrieve('context', 'String', $this); $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this); //validate the qfKey $urlParams = 'reset=1&cid=' . $contact->id; if ($context) { $urlParams .= "&context={$context}"; } if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&key={$qfKey}"; } $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams)); } // now invoke the post hook if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact); } else { CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact); } }
/** * @param string $fileName * @param string $seperator * @param $mapper * @param bool $skipColumnHeader * @param int $mode * @param int $contactType * @param int $onDuplicate * * @return mixed * @throws Exception */ public function run($fileName, $seperator = ',', &$mapper, $skipColumnHeader = FALSE, $mode = self::MODE_PREVIEW, $contactType = self::CONTACT_INDIVIDUAL, $onDuplicate = self::DUPLICATE_SKIP) { if (!is_array($fileName)) { CRM_Core_Error::fatal(); } $fileName = $fileName['name']; switch ($contactType) { case self::CONTACT_INDIVIDUAL: $this->_contactType = 'Individual'; break; case self::CONTACT_HOUSEHOLD: $this->_contactType = 'Household'; break; case self::CONTACT_ORGANIZATION: $this->_contactType = 'Organization'; } $this->init(); $this->_haveColumnHeader = $skipColumnHeader; $this->_seperator = $seperator; $fd = fopen($fileName, "r"); if (!$fd) { return FALSE; } $this->_lineCount = $this->_warningCount = 0; $this->_invalidRowCount = $this->_validCount = 0; $this->_totalCount = $this->_conflictCount = 0; $this->_errors = array(); $this->_warnings = array(); $this->_conflicts = array(); $this->_fileSize = number_format(filesize($fileName) / 1024.0, 2); if ($mode == self::MODE_MAPFIELD) { $this->_rows = array(); } else { $this->_activeFieldCount = count($this->_activeFields); } while (!feof($fd)) { $this->_lineCount++; $values = fgetcsv($fd, 8192, $seperator); if (!$values) { continue; } self::encloseScrub($values); // skip column header if we're not in mapfield mode if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) { $skipColumnHeader = FALSE; continue; } /* trim whitespace around the values */ $empty = TRUE; foreach ($values as $k => $v) { $values[$k] = trim($v, " \t\r\n"); } if (CRM_Utils_System::isNull($values)) { continue; } $this->_totalCount++; if ($mode == self::MODE_MAPFIELD) { $returnCode = $this->mapField($values); } elseif ($mode == self::MODE_PREVIEW) { $returnCode = $this->preview($values); } elseif ($mode == self::MODE_SUMMARY) { $returnCode = $this->summary($values); } elseif ($mode == self::MODE_IMPORT) { $returnCode = $this->import($onDuplicate, $values); } else { $returnCode = self::ERROR; } // note that a line could be valid but still produce a warning if ($returnCode & self::VALID) { $this->_validCount++; if ($mode == self::MODE_MAPFIELD) { $this->_rows[] = $values; $this->_activeFieldCount = max($this->_activeFieldCount, count($values)); } } if ($returnCode & self::WARNING) { $this->_warningCount++; if ($this->_warningCount < $this->_maxWarningCount) { $this->_warningCount[] = $line; } } if ($returnCode & self::ERROR) { $this->_invalidRowCount++; if ($this->_invalidRowCount < $this->_maxErrorCount) { $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_errors[] = $values; } } if ($returnCode & self::CONFLICT) { $this->_conflictCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_conflicts[] = $values; } if ($returnCode & self::DUPLICATE) { if ($returnCode & self::MULTIPLE_DUPE) { /* TODO: multi-dupes should be counted apart from singles * on non-skip action */ } $this->_duplicateCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_duplicates[] = $values; if ($onDuplicate != self::DUPLICATE_SKIP) { $this->_validCount++; } } // we give the derived class a way of aborting the process // note that the return code could be multiple code or'ed together if ($returnCode & self::STOP) { break; } // if we are done processing the maxNumber of lines, break if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) { break; } } fclose($fd); if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) { $customHeaders = $mapper; $customfields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($customHeaders as $key => $value) { if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) { $customHeaders[$key] = $customfields[$id][0]; } } if ($this->_invalidRowCount) { // removed view url for invlaid contacts $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_errorFileName = self::errorFileName(self::ERROR); self::exportCSV($this->_errorFileName, $headers, $this->_errors); } if ($this->_conflictCount) { $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_conflictFileName = self::errorFileName(self::CONFLICT); self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts); } if ($this->_duplicateCount) { $headers = array_merge(array(ts('Line Number'), ts('View Membership URL')), $customHeaders); $this->_duplicateFileName = self::errorFileName(self::DUPLICATE); self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates); } } return $this->fini(); }
/** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $config = CRM_Core_Config::singleton(); if (($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) && $this->_formValues['radio_ts'] == 'ts_sel') { $includeContactIds = TRUE; } else { $includeContactIds = FALSE; } // note the formvalues were given by CRM_Contact_Form_Search to us // and contain the search criteria (parameters) // note that the default action is basic if ($rowCount) { $cacheKey = $this->buildPrevNextCache($sort); $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds); } else { $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds); } // process the result of the query $rows = array(); $permissions = array(CRM_Core_Permission::getPermission()); if (CRM_Core_Permission::check('delete contacts')) { $permissions[] = CRM_Core_Permission::DELETE; } $mask = CRM_Core_Action::mask($permissions); // mask value to hide map link if there are not lat/long $mapMask = $mask & 4095; if ($this->_searchContext == 'smog') { $gc = CRM_Core_SelectValues::groupContactStatus(); } if ($this->_ufGroupID) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $names = array(); static $skipFields = array('group', 'tag'); foreach ($this->_fields as $key => $field) { if (!empty($field['in_selector']) && !in_array($key, $skipFields)) { if (strpos($key, '-') !== FALSE) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3); if ($id == 'Primary') { $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); if (!$locationTypeName) { continue; } } $locationTypeName = str_replace(' ', '_', $locationTypeName); if (in_array($fieldName, array('phone', 'im', 'email'))) { if ($type) { $names[] = "{$locationTypeName}-{$fieldName}-{$type}"; } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = $field['name']; } } } $names[] = "status"; } elseif (!empty($this->_returnProperties)) { $names = self::makeProperties($this->_returnProperties); } else { $names = self::$_properties; } $multipleSelectFields = array('preferred_communication_method' => 1); $links = self::links($this->_context, $this->_contextMenu, $this->_key); //check explicitly added contact to a Smart Group. $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']); $pseudoconstants = array(); // for CRM-3157 purposes if (in_array('world_region', $names)) { $pseudoconstants['world_region'] = array('dbName' => 'world_region_id', 'values' => CRM_Core_PseudoConstant::worldRegion()); } $seenIDs = array(); while ($result->fetch()) { $row = array(); $this->_query->convertToPseudoNames($result); // the columns we are interested in foreach ($names as $property) { if ($property == 'status') { continue; } if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) { $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$property}, $cfID, $this->_options, $result->contact_id); } elseif ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) { $key = $property; $paramsNew = array($key => $result->{$property}); $name = array($key => array('newName' => $key, 'groupName' => $key)); CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$key] = $paramsNew[$key]; } elseif (strpos($property, '-im')) { $row[$property] = $result->{$property}; if (!empty($result->{$property})) { $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $providerId = $property . "-provider_id"; $providerName = $imProviders[$result->{$providerId}]; $row[$property] = $result->{$property} . " ({$providerName})"; } } elseif (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) { $greeting = $property . '_display'; $row[$property] = $result->{$greeting}; } elseif (isset($pseudoconstants[$property])) { $row[$property] = CRM_Utils_Array::value($result->{$pseudoconstants[$property]['dbName']}, $pseudoconstants[$property]['values']); } elseif (strpos($property, '-url') !== FALSE) { $websiteUrl = ''; $websiteKey = 'website-1'; $propertyArray = explode('-', $property); $websiteFld = $websiteKey . '-' . array_pop($propertyArray); if (!empty($result->{$websiteFld})) { $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $websiteType = $websiteTypes[$result->{"{$websiteKey}-website_type_id"}]; $websiteValue = $result->{$websiteFld}; $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>"; } $row[$property] = $websiteUrl; } else { $row[$property] = isset($result->{$property}) ? $result->{$property} : NULL; } } if (!empty($result->postal_code_suffix)) { $row['postal_code'] .= "-" . $result->postal_code_suffix; } if ($output != CRM_Core_Selector_Controller::EXPORT && $this->_searchContext == 'smog') { if (empty($result->status) && $groupID) { $contactID = $result->contact_id; if ($contactID) { $gcParams = array('contact_id' => $contactID, 'group_id' => $groupID); $gcDefaults = array(); CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults); if (empty($gcDefaults)) { $row['status'] = ts('Smart'); } else { $row['status'] = $gc[$gcDefaults['status']]; } } else { $row['status'] = NULL; } } else { $row['status'] = $gc[$result->status]; } } if ($output != CRM_Core_Selector_Controller::EXPORT) { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id; if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')) { $links = array(array('name' => ts('View'), 'url' => 'civicrm/contact/view', 'qs' => 'reset=1&cid=%%id%%', 'class' => 'no-popup', 'title' => ts('View Contact Details')), array('name' => ts('Restore'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&restore=1', 'title' => ts('Restore Contact'))); if (CRM_Core_Permission::check('delete contacts')) { $links[] = array('name' => ts('Delete Permanently'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1', 'title' => ts('Permanently Delete Contact')); } $row['action'] = CRM_Core_Action::formLink($links, NULL, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } elseif (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && !empty($row['city']) && CRM_Utils_Array::value('state_province', $row)) { $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } else { $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } // allow components to add more actions CRM_Core_Component::searchAction($row, $result->contact_id); $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type; $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type; $row['contact_id'] = $result->contact_id; $row['sort_name'] = $result->sort_name; if (array_key_exists('id', $row)) { $row['id'] = $result->contact_id; } } // Dedupe contacts if (in_array($row['contact_id'], $seenIDs) === FALSE) { $seenIDs[] = $row['contact_id']; $rows[] = $row; } } return $rows; }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $params = $this->exportValues(); if (isset($params['field'])) { foreach ($params['field'] as $key => $value) { $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Activity'); $value['id'] = $key; if ($value['activity_date_time']) { $value['activity_date_time'] = CRM_Utils_Date::processDate($value['activity_date_time'], $value['activity_date_time_time']); } if (!empty($value['activity_status_id'])) { $value['status_id'] = $value['activity_status_id']; } if (!empty($value['activity_details'])) { $value['details'] = $value['activity_details']; } if (!empty($value['activity_duration'])) { $value['duration'] = $value['activity_duration']; } if (!empty($value['activity_location'])) { $value['location'] = $value['activity_location']; } if (!empty($value['activity_subject'])) { $value['subject'] = $value['activity_subject']; } $query = "\nSELECT a.activity_type_id, ac.contact_id\nFROM civicrm_activity a\nJOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id\nAND ac.record_type_id = %2 )\nWHERE a.id = %1 "; $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $params = array(1 => array($key, 'Integer'), 2 => array($sourceID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); $dao->fetch(); // Get Activity Type ID $value['activity_type_id'] = $dao->activity_type_id; // Get Conatct ID $value['source_contact_id'] = $dao->contact_id; // make call use API 3 $value['version'] = 3; $activityId = civicrm_api('activity', 'update', $value); // add custom field values if (!empty($value['custom']) && is_array($value['custom'])) { CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_activity', $activityId['id']); } } CRM_Core_Session::setStatus("", ts("Updates Saved"), "success"); } else { CRM_Core_Session::setStatus("", ts("No Updates Saved"), "info"); } }
/** * Combine all the exportable fields from the lower level objects. * * @param bool $checkPermission * * @return array * array of exportable Fields */ public static function &exportableFields($checkPermission = TRUE) { if (!self::$_exportableFields) { if (!self::$_exportableFields) { self::$_exportableFields = array(); } $participantFields = CRM_Event_DAO_Participant::export(); $eventFields = CRM_Event_DAO_Event::export(); $noteField = array('participant_note' => array('title' => 'Participant Note', 'name' => 'participant_note', 'type' => CRM_Utils_Type::T_STRING)); $participantStatus = array('participant_status' => array('title' => 'Participant Status', 'name' => 'participant_status', 'type' => CRM_Utils_Type::T_STRING)); $participantRole = array('participant_role' => array('title' => 'Participant Role', 'name' => 'participant_role', 'type' => CRM_Utils_Type::T_STRING)); $discountFields = CRM_Core_DAO_Discount::export(); $fields = array_merge($participantFields, $participantStatus, $participantRole, $eventFields, $noteField, $discountFields); // add custom data $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission)); self::$_exportableFields = $fields; } return self::$_exportableFields; }
/** * Returns the option label for a custom field with a specific value. Handles all * custom field data and html types * * @param $fieldId int the custom field ID * @pram $value string the value (typically from the DB) of this custom field * @param $htmlType string the html type of the field (optional) * @param $dataType string the data type of the field (optional) * * @return string the label to display for this custom field * @static * @access public */ static function getOptionLabel($fieldId, $value, $htmlType = NULL, $dataType = NULL) { if (!$fieldId) { return NULL; } if (!$htmlType || !$dataType) { $sql = "\nSELECT html_type, data_type\nFROM civicrm_custom_field\nWHERE id = %1\n"; $params = array(1 => array($fieldId, 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $htmlType = $dao->html_type; $dataType = $dao->data_type; } else { CRM_Core_Error::fatal(); } } $options = NULL; switch ($htmlType) { case 'CheckBox': case 'Multi-Select': case 'AdvMulti-Select': case 'Select': case 'Radio': case 'Autocomplete-Select': if (!in_array($dataType, array('Boolean', 'ContactReference'))) { $options = self::valuesByID($fieldId); } } return CRM_Core_BAO_CustomField::getDisplayValueCommon($value, $options, $htmlType, $dataType); }
/** * Get list of membership fields for profile. * * For now we only allow custom membership fields to be in * profile * * @param null $mode * FIXME: This param is ignored * * @return array * the list of membership fields */ public static function getMembershipFields($mode = NULL) { $fields = CRM_Member_DAO_Membership::export(); unset($fields['membership_contact_id']); $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership')); $membershipType = CRM_Member_DAO_MembershipType::export(); $membershipStatus = CRM_Member_DAO_MembershipStatus::export(); $fields = array_merge($fields, $membershipType, $membershipStatus); return $fields; }
/** * @return bool */ public function validate() { if (CRM_Utils_System::isNull($this->_value)) { return TRUE; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); case 'register_date': return CRM_Utils_Rule::date($this->_value); /* @codingStandardsIgnoreStart case 'event_id': static $events = null; if (!$events) { $events = CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; @codingStandardsIgnoreEnd */ /* @codingStandardsIgnoreStart case 'event_id': static $events = null; if (!$events) { $events = CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; @codingStandardsIgnoreEnd */ default: break; } // check whether that's a valid custom field id // and if so, check the contents' validity if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) { static $customFields = NULL; if (!$customFields) { $customFields = CRM_Core_BAO_CustomField::getFields('Participant'); } if (!array_key_exists($customFieldID, $customFields)) { return FALSE; } return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value); } return TRUE; }
/** * 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')); } }
/** * Build the search form. * * @param CRM_Core_Form $form */ public static function buildSearchForm(&$form) { $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(); $form->add('select', 'membership_status_id', ts('Membership Status(s)'), $membershipStatus, FALSE, array('id' => 'membership_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2')); $form->addEntityRef('membership_type_id', ts('Membership Type(s)'), array('entity' => 'MembershipType', 'multiple' => TRUE, 'placeholder' => ts('- any -'), 'select' => array('minimumInputLength' => 0))); $form->addElement('text', 'member_source', ts('Source')); CRM_Core_Form_Date::buildDateRange($form, 'member_join_date', 1, '_low', '_high', ts('From'), FALSE); CRM_Core_Form_Date::buildDateRange($form, 'member_start_date', 1, '_low', '_high', ts('From'), FALSE); CRM_Core_Form_Date::buildDateRange($form, 'member_end_date', 1, '_low', '_high', ts('From'), FALSE); $form->addYesNo('member_is_primary', ts('Primary Member?'), TRUE); $form->addYesNo('member_pay_later', ts('Pay Later?'), TRUE); $form->addYesNo('member_auto_renew', ts('Auto-Renew?'), TRUE); $form->addYesNo('member_test', ts('Membership is a Test?'), TRUE); $form->addYesNo('member_is_override', ts('Membership Status Is Override?'), TRUE); // add all the custom searchable fields $extends = array('Membership'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends); if ($groupDetails) { $form->assign('membershipGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, FALSE, TRUE); } } } CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'member_campaign_id'); $form->assign('validCiviMember', TRUE); $form->setDefaults(array('member_test' => 0)); }
/** * @param CRM_Core_Form $form */ public static function buildSearchForm(&$form) { $dataURLEventFee = CRM_Utils_System::url('civicrm/ajax/eventFee', "reset=1", FALSE, NULL, FALSE); $form->assign('dataURLEventFee', $dataURLEventFee); $form->addEntityRef('event_id', ts('Event Name'), array('entity' => 'event', 'placeholder' => ts('- any -'), 'multiple' => 1, 'select' => array('minimumInputLength' => 0))); $form->addEntityRef('event_type_id', ts('Event Type'), array('entity' => 'option_value', 'placeholder' => ts('- any -'), 'select' => array('minimumInputLength' => 0), 'api' => array('params' => array('option_group_id' => 'event_type')))); $obj = new CRM_Report_Form_Event_ParticipantListing(); $form->add('select', 'participant_fee_id', ts('Fee Level'), $obj->getPriceLevels(), FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))); CRM_Core_Form_Date::buildDateRange($form, 'event', 1, '_start_date_low', '_end_date_high', ts('From'), FALSE); CRM_Core_Form_Date::buildDateRange($form, 'participant', 1, '_register_date_low', '_register_date_high', ts('From'), FALSE); $form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', array(1 => '<em>%1</em>'))); $form->addSelect('participant_status_id', array('entity' => 'participant', 'label' => ts('Participant Status'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))); $form->addSelect('participant_role_id', array('entity' => 'participant', 'label' => ts('Participant Role'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))); $form->addYesNo('participant_test', ts('Participant is a Test?'), TRUE); $form->addYesNo('participant_is_pay_later', ts('Participant is Pay Later?'), TRUE); $form->addElement('text', 'participant_fee_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8)); $form->addElement('text', 'participant_fee_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8)); $form->addRule('participant_fee_amount_low', ts('Please enter a valid money value.'), 'money'); $form->addRule('participant_fee_amount_high', ts('Please enter a valid money value.'), 'money'); // add all the custom searchable fields $extends = array('Participant', 'Event'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends); if ($groupDetails) { $form->assign('participantGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE); } } } CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'participant_campaign_id'); $form->assign('validCiviEvent', TRUE); $form->setDefaults(array('participant_test' => 0)); }
/** * process membership records * * @param array $params associated array of submitted values * * @access public * * @return bool */ private function processMembership(&$params) { $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate'); $dates = array('join_date', 'start_date', 'end_date', 'reminder_date'); // get the price set associated with offline memebership $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name'); $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); if (isset($params['field'])) { $customFields = array(); foreach ($params['field'] as $key => $value) { // if contact is not selected we should skip the row if (empty($params['primary_contact_id'][$key])) { continue; } $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']); // update contact information $this->updateContactInfo($value); $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1]; foreach ($dateTypes as $dateField => $dateVariable) { ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]); } $calcDates = array(); $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate); foreach ($calcDates as $memType => $calcDate) { foreach ($dates as $d) { //first give priority to form values then calDates. $date = CRM_Utils_Array::value($d, $value); if (!$date) { $date = CRM_Utils_Array::value($d, $calcDate); } $value[$d] = CRM_Utils_Date::processDate($date); } } if (!empty($value['send_receipt'])) { $value['receipt_date'] = date('Y-m-d His'); } if (!empty($value['membership_source'])) { $value['source'] = $value['membership_source']; } unset($value['membership_source']); //Get the membership status if (!empty($value['membership_status'])) { $value['status_id'] = $value['membership_status']; unset($value['membership_status']); } if (empty($customFields)) { // membership type custom data $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId); $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE)); } //check for custom data $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId); if (!empty($value['financial_type'])) { $value['financial_type_id'] = $value['financial_type']; } if (!empty($value['payment_instrument'])) { $value['payment_instrument_id'] = $value['payment_instrument']; } // handle soft credit if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) { $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key]; $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]); } if (!empty($value['receive_date'])) { $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE); } $params['actualBatchTotal'] += $value['total_amount']; unset($value['financial_type']); unset($value['payment_instrument']); $value['batch_id'] = $this->_batchId; $value['skipRecentView'] = TRUE; // make entry in line item for contribution $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]); $editedResults = array(); CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults); if (!empty($editedResults)) { unset($this->_priceSet['fields']); $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']]; unset($this->_priceSet['fields'][$editedResults['id']]['options']); $fid = $editedResults['id']; $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']); $editedResults = array(); CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults); $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']]; if (!empty($value['total_amount'])) { $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount']; } $fieldID = key($this->_priceSet['fields']); $value['price_' . $fieldID] = $editedResults['id']; $lineItem = array(); CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]); //CRM-11529 for backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) { foreach ($lineItem[$priceSetId] as &$values) { $values['financial_type_id'] = $value['financial_type_id']; } } $value['lineItems'] = $lineItem; $value['processPriceSet'] = TRUE; } // end of contribution related section unset($value['membership_type']); unset($value['membership_start_date']); unset($value['membership_end_date']); $value['is_renew'] = false; if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) { $this->_params = $params; $value['is_renew'] = true; $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']); // make contribution entry CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id))); } else { $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray); } //process premiums if (!empty($value['product_name'])) { if ($value['product_name'][0] > 0) { list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); $value['hidden_Premium'] = 1; $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]); $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1); CRM_Contribute_BAO_Contribution::addPremium($premiumParams); } } // end of premium //send receipt mail. if ($membership->id && !empty($value['send_receipt'])) { // add the domain email id $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail(); $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>"; $value['from_email_address'] = $domainEmail; $value['membership_id'] = $membership->id; CRM_Member_Form_Membership::emailReceipt($this, $value, $membership); } } } return TRUE; }