/** * @return array (int id => string title) */ public static function getPeriods() { $periods = civicrm_api3('HRAbsencePeriod', 'get', array()); $result = CRM_Utils_Array::collect('title', $periods['values']); asort($result); return $result; }
public function __construct() { $tokens = CRM_Utils_Array::subset(CRM_Utils_Array::collect('title', CRM_Contribute_DAO_Contribution::fields()), $this->getPassthruTokens()); $tokens['id'] = ts('Contribution ID'); $tokens['payment_instrument'] = ts('Payment Instrument'); $tokens['source'] = ts('Contribution Source'); $tokens['status'] = ts('Contribution Status'); $tokens['type'] = ts('Financial Type'); parent::__construct('contribution', $tokens); }
function testCollect() { $arr = array(array('catWord' => 'cat', 'dogWord' => 'dog'), array('catWord' => 'chat', 'dogWord' => 'chien'), array('catWord' => 'gato')); $expected = array('cat', 'chat', 'gato'); $this->assertEquals($expected, CRM_Utils_Array::collect('catWord', $arr)); $arr = array(); $arr['en'] = (object) array('catWord' => 'cat', 'dogWord' => 'dog'); $arr['fr'] = (object) array('catWord' => 'chat', 'dogWord' => 'chien'); $arr['es'] = (object) array('catWord' => 'gato'); $expected = array('en' => 'cat', 'fr' => 'chat', 'es' => 'gato'); $this->assertEquals($expected, CRM_Utils_Array::collect('catWord', $arr)); }
/** * Get a list of managed relationship-types by searching CiviCase XML files. * * @param \CRM_Case_XMLRepository $xmlRepo * @param \CRM_Core_ManagedEntities $me * * @return array * @see CRM_Utils_Hook::managed */ public static function createManagedRelationshipTypes(CRM_Case_XMLRepository $xmlRepo, CRM_Core_ManagedEntities $me) { $result = array(); if (!isset(Civi::$statics[__CLASS__]['reltypes'])) { $relationshipInfo = CRM_Core_PseudoConstant::relationshipType('label', TRUE, NULL); Civi::$statics[__CLASS__]['reltypes'] = CRM_Utils_Array::collect(CRM_Case_XMLProcessor::REL_TYPE_CNAME, $relationshipInfo); } $validRelTypes = Civi::$statics[__CLASS__]['reltypes']; $relTypes = $xmlRepo->getAllDeclaredRelationshipTypes(); foreach ($relTypes as $relType) { $managed = array('module' => 'civicrm', 'name' => "civicase:rel:{$relType}", 'entity' => 'RelationshipType', 'update' => 'never', 'cleanup' => 'unused', 'params' => array('version' => 3, 'name_a_b' => "{$relType} is", 'name_b_a' => $relType, 'label_a_b' => "{$relType} is", 'label_b_a' => $relType, 'description' => $relType, 'contact_type_a' => 'Individual', 'contact_type_b' => 'Individual', 'contact_sub_type_a' => NULL, 'contact_sub_type_b' => NULL)); // We'll create managed-entity if this record doesn't exist yet // or if we previously decided to manage this record. if (!in_array($relType, $validRelTypes)) { $result[] = $managed; } elseif ($me->get($managed['module'], $managed['name'])) { $result[] = $managed; } } return $result; }
/** * Test to check contact reference field */ public function testContactReference() { //create group $groupId1 = $this->groupCreate(); $groupId2 = $this->groupCreate(array('name' => 'Test Group 2', 'domain_id' => 1, 'title' => 'New Test Group2 Created', 'description' => 'New Test Group2 Created', 'is_active' => 1, 'visibility' => 'User and User Admin Only')); $contactIds = array(); foreach (array($groupId1, $groupId2) as $groupId) { $this->groupContactCreate($groupId); $contactIds = array_merge($contactIds, CRM_Contact_BAO_Group::getGroupContacts($groupId)); } $contactIds = CRM_Utils_Array::collect('contact_id', $contactIds); // create custom group with contact reference field $customGroup = $this->customGroupCreate(array('extends' => 'Contact', 'title' => 'select_test_group')); $params = array('custom_group_id' => $customGroup['id'], 'name' => 'Worker_Lookup', 'label' => 'Worker Lookup', 'filter' => "action=lookup&group={$groupId1},{$groupId2}", 'html_type' => 'Autocomplete-Select', 'data_type' => 'ContactReference', 'weight' => 4, 'is_searchable' => 1, 'is_active' => 1); $customField = $this->callAPISuccess('custom_field', 'create', $params); $_GET = array('id' => $customField['id'], 'is_unit_test' => TRUE); $contactList = CRM_Contact_Page_AJAX::contactReference(); $contactList = CRM_Utils_Array::collect('id', $contactList); //assert each returned contact id to be present in group contact foreach ($contactList as $contactId) { $this->assertTrue(in_array($contactId, $contactIds)); } }
/** * Scan for a list of pseudo-constants. A pseudo-constant is recognized by listing * any static properties which have corresponding static methods. * * This may be inefficient and should generally be avoided. * * @param $class * * @return array * Array of string, constant names */ public static function findConstantsByClass($class) { $clazz = new ReflectionClass($class); $classConstants = array_intersect(CRM_Utils_Array::collect('name', $clazz->getProperties(ReflectionProperty::IS_STATIC)), CRM_Utils_Array::collect('name', $clazz->getMethods(ReflectionMethod::IS_STATIC))); return $classConstants; }
/** * Assert that $expectedRecipients (and no else) have received emails * * @param array $expectedRecipients array($msgPos => array($recipPos => $emailAddr)) */ function assertRecipients($expectedRecipients) { $recipients = array(); foreach ($this->getAllMessages('ezc') as $message) { $recipients[] = CRM_Utils_Array::collect('email', $message->to); } sort($recipients); sort($expectedRecipients); $this->_ut->assertEquals($expectedRecipients, $recipients, "Incorrect recipients: " . print_r(array('expected' => $expectedRecipients, 'actual' => $recipients), TRUE)); }
/** * @param $getParams * @param $expectedNames * @dataProvider okGetProvider */ public function testGet($getParams, $expectedNames) { foreach (array(123, 456) as $entity_id) { foreach (array('text/plain' => '.txt', 'text/csv' => '.csv') as $mime => $ext) { $this->callAPISuccess('Attachment', 'create', array('name' => self::getFilePrefix() . 'example_' . $entity_id . $ext, 'mime_type' => $mime, 'description' => 'My test description', 'content' => 'My test content', 'entity_table' => 'civicrm_activity', 'entity_id' => $entity_id)); } } $getResult = $this->callAPISuccess('Attachment', 'get', $getParams); $actualNames = array_values(CRM_Utils_Array::collect('name', $getResult['values'])); sort($actualNames); sort($expectedNames); $this->assertEquals($expectedNames, $actualNames); }
/** * Assert that $expectedRecipients (and no else) have received emails * * @param array $expectedRecipients * Array($msgPos => array($recipPos => $emailAddr)). */ public function assertRecipients($expectedRecipients) { $recipients = array(); foreach ($this->getAllMessages('ezc') as $message) { $recipients[] = CRM_Utils_Array::collect('email', $message->to); } $cmp = function ($a, $b) { if ($a[0] == $b[0]) { return 0; } return $a[0] < $b[0] ? 1 : -1; }; usort($recipients, $cmp); usort($expectedRecipients, $cmp); $this->_ut->assertEquals($expectedRecipients, $recipients, "Incorrect recipients: " . print_r(array('expected' => $expectedRecipients, 'actual' => $recipients), TRUE)); }
/** * Add a widget for selecting/editing/creating/copying a profile form * * @param string $name * HTML form-element name. * @param string $label * Printable label. * @param string $allowCoreTypes * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'. * @param string $allowSubTypes * Only present a UFGroup if its group_type is compatible with $allowSubypes. * @param array $entities * @param bool $default * //CRM-15427. */ public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) { // Output widget // FIXME: Instead of adhoc serialization, use a single json_encode() CRM_UF_Page_ProfileEditor::registerProfileScripts(); CRM_UF_Page_ProfileEditor::registerSchemas(CRM_Utils_Array::collect('entity_type', $entities)); $this->add('text', $name, $label, array('class' => 'crm-profile-selector', 'data-group-type' => CRM_Core_BAO_UFGroup::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'), 'data-entities' => json_encode($entities), 'data-default' => $default, 'data-usedfor' => json_encode($usedFor))); }
/** * Build form for related contacts / on behalf of organization. * * @param CRM_Core_Form $form * */ public static function buildQuickForm(&$form) { $form->assign('fieldSetTitle', ts('Organization Details')); $form->assign('buildOnBehalfForm', TRUE); $contactID = $form->_contactID; if ($contactID && count($form->_employers) >= 1) { $form->add('text', 'organization_id', ts('Select an existing related Organization OR enter a new one')); $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $form->_employers)); $orgOptions = array(0 => ts('Select an existing organization'), 1 => ts('Enter a new organization')); $form->addRadio('org_option', ts('options'), $orgOptions); $form->setDefaults(array('org_option' => 0)); $form->add('checkbox', 'mode', ''); } $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_profileId, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); if (is_array($form->_membershipBlock) && !empty($form->_membershipBlock)) { $fieldTypes = array_merge($fieldTypes, array('Membership')); } else { $fieldTypes = array_merge($fieldTypes, array('Contribution')); } foreach ($profileFields as $name => $field) { if (in_array($field['field_type'], $fieldTypes)) { list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2); if (in_array($prefixName, array('organization_name', 'email')) && empty($field['is_required'])) { $field['is_required'] = 1; } CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf'); } } $form->assign('onBehalfOfFields', $profileFields); $form->addElement('hidden', 'hidden_onbehalf_profile', 1); }
/** * Build form elements based on the above metadata. */ public function buildQuickForm() { CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.insert-shortcode.js'); $components = CRM_Utils_Array::collect('label', $this->components); $data = CRM_Utils_Array::collect('select', $this->components); $this->add('select', 'component', NULL, $components, FALSE, array('class' => 'crm-select2', 'data-key' => 'component', 'data-entities' => json_encode($data))); $this->add('text', 'entity', NULL, array('placeholder' => ts('- select -'))); $options = $defaults = array(); foreach ($this->options as $num => $field) { $this->addRadio("option_{$num}", CRM_Utils_Array::value('label', $field), $field['options'], array('allowClear' => FALSE, 'data-key' => $field['key'])); if ($field['components'] === TRUE) { $field['components'] = array_keys($this->components); } $options["option_{$num}"] = $field; // Select 1st option as default $keys = array_keys($field['options']); $defaults["option_{$num}"] = $keys[0]; } $this->assign('options', $options); $this->assign('selects', array_keys(array_filter($data))); $this->setDefaults($defaults); }
/** * @param int $caseTypeId * * @throws CRM_Core_Exception * @return mixed */ public static function del($caseTypeId) { $caseType = new CRM_Case_DAO_CaseType(); $caseType->id = $caseTypeId; $refCounts = $caseType->getReferenceCounts(); $total = array_sum(CRM_Utils_Array::collect('count', $refCounts)); if ($total) { throw new CRM_Core_Exception(ts("You can not delete this case type -- it is assigned to %1 existing case record(s). If you do not want this case type to be used going forward, consider disabling it instead.", array(1 => $total))); } $result = $caseType->delete(); CRM_Case_XMLRepository::singleton(TRUE); return $result; }
/** * Function to build form for related contacts / on behalf of organization. * * @param $form object invoking Object * @param $contactType string contact type * @param $title string fieldset title * * @static */ static function buildQuickForm(&$form) { $form->assign('fieldSetTitle', ts('Organization Details')); $form->assign('buildOnBehalfForm', TRUE); $contactID = $form->_contactID; if ($contactID && count($form->_employers) >= 1) { $form->add('text', 'organization_id', ts('Select an existing related Organization OR enter a new one')); $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $form->_employers)); $orgOptions = array(0 => ts('Select an existing organization'), 1 => ts('Enter a new organization')); $form->addRadio('org_option', ts('options'), $orgOptions); $form->setDefaults(array('org_option' => 0)); $form->add('checkbox', 'mode', ''); } $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_profileId, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); if (is_array($form->_membershipBlock) && !empty($form->_membershipBlock)) { $fieldTypes = array_merge($fieldTypes, array('Membership')); } else { $fieldTypes = array_merge($fieldTypes, array('Contribution')); } $stateCountryMap = array(); foreach ($profileFields as $name => $field) { if (in_array($field['field_type'], $fieldTypes)) { list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2); if (in_array($prefixName, array('state_province', 'country', 'county'))) { if (!array_key_exists($index, $stateCountryMap)) { $stateCountryMap[$index] = array(); } $stateCountryMap[$index][$prefixName] = 'onbehalf[' . $name . ']'; } elseif (in_array($prefixName, array('organization_name', 'email')) && !CRM_Utils_Array::value('is_required', $field)) { $field['is_required'] = 1; } CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, TRUE); } } if (!empty($stateCountryMap)) { CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap); // now fix all state country selectors CRM_Core_BAO_Address::fixAllStateSelects($form, CRM_Core_DAO::$_nullArray); } $form->assign('onBehalfOfFields', $profileFields); $form->addElement('hidden', 'hidden_onbehalf_profile', 1); }
/** * Execute the default schedule, without any special recipient selections. * * @dataProvider createTestCases * * @param string $targetDate * @param string $setupFuncs * @param array $expectMessages * * @throws \Exception */ public function testDefault($targetDate, $setupFuncs, $expectMessages) { $this->targetDate = $targetDate; foreach (explode(' ', $setupFuncs) as $setupFunc) { $this->{$setupFunc}(); } $this->schedule->save(); $actualMessages = array(); foreach ($this->cronTimes() as $time) { \CRM_Utils_Time::setTime($time); $this->callAPISuccess('job', 'send_reminder', array()); foreach ($this->mut->getAllMessages('ezc') as $message) { /** @var \ezcMail $message */ $simpleMessage = array('time' => $time, 'to' => \CRM_Utils_Array::collect('email', $message->to), 'subject' => $message->subject); sort($simpleMessage['to']); $actualMessages[] = $simpleMessage; $this->mut->clearMessages(); } } $errorText = "Incorrect messages: " . print_r(array('actualMessages' => $actualMessages, 'expectMessages' => $expectMessages), 1); $this->assertEquals(count($expectMessages), count($actualMessages), $errorText); usort($expectMessages, array(__CLASS__, 'compareSimpleMsgs')); usort($actualMessages, array(__CLASS__, 'compareSimpleMsgs')); foreach ($expectMessages as $offset => $expectMessage) { $actualMessage = $actualMessages[$offset]; $this->assertApproxEquals(strtotime($expectMessage['time']), strtotime($actualMessage['time']), $this->dateTolerance, $errorText); if (isset($expectMessage['to'])) { sort($expectMessage['to']); $this->assertEquals($expectMessage['to'], $actualMessage['to'], $errorText); } if (isset($expectMessage['subject'])) { $this->assertRegExp($expectMessage['subject'], $actualMessage['subject'], $errorText); } } }
/** * Add onbehalf/honoree profile fields and native module fields. * * @param int $id * @param CRM_Core_Form $form */ public function buildComponentForm($id, $form) { if (empty($id)) { return; } $contactID = $this->getContactID(); foreach (array('soft_credit', 'on_behalf') as $module) { if ($module == 'soft_credit') { if (empty($form->_values['honoree_profile_id'])) { continue; } if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['honoree_profile_id'], 'is_active')) { CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of honoree and the selected honoree profile is either disabled or not found.')); } $profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']); $requiredProfileFields = array('Individual' => array('first_name', 'last_name'), 'Organization' => array('organization_name', 'email'), 'Household' => array('household_name', 'email')); $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_values['honoree_profile_id'], $requiredProfileFields[$profileContactType]); if (!$validProfile) { CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of honoree and the required fields of the selected honoree profile are disabled or doesn\'t exist.')); } foreach (array('honor_block_title', 'honor_block_text') as $name) { $form->assign($name, $form->_values[$name]); } $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE); // radio button for Honor Type foreach ($form->_values['soft_credit_types'] as $value) { $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value); } $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE); $honoreeProfileFields = CRM_Core_BAO_UFGroup::getFields($this->_values['honoree_profile_id'], FALSE, NULL, NULL, NULL, FALSE, NULL, TRUE, NULL, CRM_Core_Permission::CREATE); $form->assign('honoreeProfileFields', $honoreeProfileFields); // add the form elements foreach ($honoreeProfileFields as $name => $field) { // If soft credit type is not chosen then make omit requiredness from honoree profile fields if (count($form->_submitValues) && empty($form->_submitValues['soft_credit_type_id']) && !empty($field['is_required'])) { $field['is_required'] = FALSE; } CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, NULL, FALSE, FALSE, NULL, 'honor'); } } else { if (empty($form->_values['onbehalf_profile_id'])) { continue; } if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['onbehalf_profile_id'], 'is_active')) { CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.')); } $member = CRM_Member_BAO_Membership::getMembershipBlock($form->_id); if (empty($member['is_active'])) { $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.'); $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($form->_values['onbehalf_profile_id']); foreach (array('Individual', 'Organization', 'Household') as $contactType) { if (in_array($contactType, $onBehalfProfile) && (in_array('Membership', $onBehalfProfile) || in_array('Contribution', $onBehalfProfile))) { CRM_Core_Error::fatal($msg); } } } if ($contactID) { // retrieve all permissioned organizations of contact $contactID $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($contactID, NULL, NULL, 'Organization'); if (count($organizations)) { // Related org url - pass checksum if needed $args = array('ufId' => $form->_values['onbehalf_profile_id'], 'cid' => ''); if (!empty($_GET['cs'])) { $args = array('ufId' => $form->_values['onbehalf_profile_id'], 'uid' => $this->_contactID, 'cs' => $_GET['cs'], 'cid' => ''); } $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE); $form->assign('locDataURL', $locDataURL); } if (count($organizations) > 0) { $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $organizations)); $orgOptions = array(0 => ts('Select an existing organization'), 1 => ts('Enter a new organization')); $form->addRadio('org_option', ts('options'), $orgOptions); $form->setDefaults(array('org_option' => 0)); } } $form->assign('fieldSetTitle', ts('Organization Details')); if (CRM_Utils_Array::value('is_for_organization', $form->_values)) { if ($form->_values['is_for_organization'] == 2) { $form->assign('onBehalfRequired', TRUE); } else { $form->addElement('checkbox', 'is_for_organization', $form->_values['for_organization'], NULL); } } $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_values['onbehalf_profile_id'], FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); $form->assign('onBehalfOfFields', $profileFields); if (!empty($form->_submitValues['onbehalf'])) { if (!empty($form->_submitValues['onbehalfof_id'])) { $form->assign('submittedOnBehalf', $form->_submitValues['onbehalfof_id']); } $form->assign('submittedOnBehalfInfo', json_encode($form->_submitValues['onbehalf'])); } $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); foreach ($profileFields as $name => $field) { if (in_array($field['field_type'], $fieldTypes)) { list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2); if (in_array($prefixName, array('organization_name', 'email')) && empty($field['is_required'])) { $field['is_required'] = 1; } if (count($form->_submitValues) && empty($form->_submitValues['is_for_organization']) && $form->_values['is_for_organization'] == 1 && !empty($field['is_required'])) { $field['is_required'] = FALSE; } CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf'); } } } } }
/** * */ public function testMailerSendTest_group() { // BEGIN SAMPLE DATA $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group')); $contactIDs['alice'] = $this->individualCreate(array('email' => '*****@*****.**', 'first_name' => 'Alice', 'last_name' => 'Person')); $contactIDs['bob'] = $this->individualCreate(array('email' => '*****@*****.**', 'first_name' => 'Bob', 'last_name' => 'Person')); $contactIDs['carol'] = $this->individualCreate(array('email' => '*****@*****.**', 'first_name' => 'Carol', 'last_name' => 'Person')); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['alice'])); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['bob'])); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['carol'])); // END SAMPLE DATA $mail = $this->callAPISuccess('mailing', 'create', $this->_params); $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupIDs['inc'])); $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values'])); $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts); $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values'])); $this->assertEquals(array('*****@*****.**', '*****@*****.**', '*****@*****.**'), $deliveredEmails); }
/** * Get information about fields for a given api request. * * Getfields information is used for documentation, validation, default setting * We first query the scheme using the $dao->fields function & then augment * that information by calling the _spec functions that apply to the relevant function * Note that we use 'unique' field names as described in the xml/schema files * for get requests & just field name for create. This is because some get functions * access multiple objects e.g. contact api accesses is_deleted from the activity * table & from the contact table * * @param array $apiRequest * Api request as an array. Keys are. * - entity: string * - action: string * - version: string * - function: callback (mixed) * - params: array, varies * * @param bool $unique * Determines whether to key by unique field names (only affects get-type) actions * * @return array * API success object */ function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) { static $results = array(); if (CRM_Utils_Array::value('cache_clear', $apiRequest['params'])) { $results = array(); // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes CRM_Core_PseudoConstant::flush(); if (!empty($apiRequest['params']['fieldname'])) { CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']); } if (!empty($apiRequest['params']['option_group_id'])) { $optionGroupName = civicrm_api('option_group', 'getvalue', array('version' => 3, 'id' => $apiRequest['params']['option_group_id'], 'return' => 'name')); if (is_string($optionGroupName)) { CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName)); } } } $entity = $apiRequest['entity']; $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity); $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']); $action = CRM_Utils_Array::value('action', $apiRequest['params']); $sequential = empty($apiRequest['params']['sequential']) ? 0 : 1; $apiRequest['params']['options'] = CRM_Utils_Array::value('options', $apiRequest['params'], array()); $optionsToResolve = (array) CRM_Utils_Array::value('get_options', $apiRequest['params']['options'], array()); if (!$action || $action == 'getvalue' || $action == 'getcount') { $action = 'get'; } // If no options, return results from cache if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity]) && isset($action, $results[$entity . $subentity][$sequential])) { return $results[$entity . $subentity][$action][$sequential]; } // defaults based on data model and API policy switch ($action) { case 'getfields': $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']); return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields'); case 'create': case 'update': case 'replace': $unique = FALSE; case 'get': case 'getsingle': case 'getcount': case 'getstat': $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']); if (empty($metadata['id'])) { // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) { $metadata['id'] = $metadata[$lowercase_entity . '_id']; unset($metadata[$lowercase_entity . '_id']); $metadata['id']['api.aliases'] = array($lowercase_entity . '_id'); } } else { // really the preference would be to set the unique name in the xml // question is which is a less risky fix this close to a release - setting in xml for the known failure // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested // inconsistency $metadata['id']['api.aliases'] = array($lowercase_entity . '_id'); } break; case 'delete': $metadata = array('id' => array('title' => $entity . ' ID', 'api.required' => 1, 'api.aliases' => array($lowercase_entity . '_id'), 'type' => CRM_Utils_Type::T_INT)); break; // Note: adding setvalue case here instead of in a generic spec function because // some APIs override the generic setvalue fn which causes the generic spec to be overlooked. // Note: adding setvalue case here instead of in a generic spec function because // some APIs override the generic setvalue fn which causes the generic spec to be overlooked. case 'setvalue': $metadata = array('field' => array('title' => 'Field name', 'api.required' => 1, 'type' => CRM_Utils_Type::T_STRING), 'id' => array('title' => $entity . ' ID', 'api.required' => 1, 'type' => CRM_Utils_Type::T_INT), 'value' => array('title' => 'Value', 'description' => "Field value to set", 'api.required' => 1)); if (array_intersect(array('all', 'field'), $optionsToResolve)) { $options = civicrm_api3_generic_getfields(array('entity' => $entity, array('params' => array('action' => 'create')))); $metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']); } break; default: // oddballs are on their own $metadata = array(); } // Normalize this for the sake of spec funcions $apiRequest['params']['options']['get_options'] = $optionsToResolve; // find any supplemental information $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']); try { list($apiProvider, $hypApiRequest) = \Civi::service('civi_api_kernel')->resolve($hypApiRequest); if (isset($hypApiRequest['function'])) { $helper = '_' . $hypApiRequest['function'] . '_spec'; } else { // not implemented MagicFunctionProvider $helper = NULL; } } catch (\Civi\API\Exception\NotImplementedException $e) { $helper = NULL; } if (function_exists($helper)) { // alter $helper($metadata, $apiRequest); } foreach ($metadata as $fieldname => $fieldSpec) { // Ensure 'name' is set if (!isset($fieldSpec['name'])) { $metadata[$fieldname]['name'] = $fieldname; } _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec); // Convert options to "sequential" format if ($sequential && !empty($metadata[$fieldname]['options'])) { $metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']); } } $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields'); return $results[$entity][$action][$sequential]; }
/** * Convert IDs to values and format for display. * * @param HTML_QuickForm_element $field */ public static function preProcessEntityRef($field) { $val = $field->getValue(); // Temporarily convert string values to an array if (!is_array($val)) { // Try to auto-detect method of serialization $val = strpos($val, ',') ? explode(',', str_replace(', ', ',', $val)) : (array) CRM_Utils_Array::explodePadded($val); } if ($val) { $entity = $field->getAttribute('data-api-entity'); // Get api params, ensure it is an array $params = $field->getAttribute('data-api-params'); $params = $params ? json_decode($params, TRUE) : array(); $result = civicrm_api3($entity, 'getlist', array('id' => $val) + $params); if ($field->isFrozen()) { // Prevent js from treating frozen entityRef as a "live" field $field->removeAttribute('class'); } if (!empty($result['values'])) { $field->setAttribute('data-entity-value', json_encode($result['values'])); } // CRM-15803 - Remove invalid values $val = array_intersect($val, CRM_Utils_Array::collect('id', $result['values'])); } // Convert array values back to a string $field->setValue(implode(',', $val)); }
/** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; }
/** * Make a basic API (Widget.get) which allows getting data out of a simple in-memory * list of records. * * @param $records * The list of all records. * @param $params * The filter criteria * @param array $resultIds * The records which are expected to match. * @dataProvider basicArrayCases */ public function testBasicArrayGet($records, $params, $resultIds) { $params['version'] = 3; $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher()); $provider = new \Civi\API\Provider\AdhocProvider($params['version'], 'Widget'); $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use($records) { return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', array('snack_id', 'fruit', 'cheese')); }); $kernel->registerApiProvider($provider); $r1 = $kernel->run('Widget', 'get', $params); $this->assertEquals(count($resultIds), $r1['count']); $this->assertEquals($resultIds, array_keys($r1['values'])); $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r1['values']))); $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r1['values']))); $r2 = $kernel->run('Widget', 'get', $params + array('sequential' => 1)); $this->assertEquals(count($resultIds), $r2['count']); $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r2['values']))); $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r2['values']))); $r3 = $kernel->run('Widget', 'get', $params + array('options' => array('offset' => 1, 'limit' => 2))); $slice = array_slice($resultIds, 1, 2); $this->assertEquals(count($slice), $r3['count']); $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('snack_id', $r3['values']))); $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('id', $r3['values']))); }