/** * @param $params * @param $smarty * @return string|void */ function smarty_function_crmAPI($params, &$smarty) { if (!array_key_exists('entity', $params)) { $smarty->trigger_error("assign: missing 'entity' parameter"); return "crmAPI: missing 'entity' parameter"; } $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); $entity = $params['entity']; $action = CRM_Utils_Array::value('action', $params, 'get'); $params['sequential'] = CRM_Utils_Array::value('sequential', $params, 1); $var = CRM_Utils_Array::value('var', $params); CRM_Utils_Array::remove($params, 'entity', 'action', 'var'); $params['version'] = 3; require_once 'api/api.php'; $result = civicrm_api($entity, $action, $params); unset($errorScope); if ($result === FALSE) { $smarty->trigger_error("Unknown error"); return; } if (!empty($result['is_error'])) { $smarty->trigger_error("{crmAPI} " . $result["error_message"]); } if (!$var) { return json_encode($result); } if (!empty($params['json'])) { $smarty->assign($var, json_encode($result)); } else { $smarty->assign($var, $result); } }
/** * Generate the html for a button-style link * * @param array $params * Params of the {crmButton} call. * @param string $text * Contents of block. * @param CRM_Core_Smarty $smarty * The Smarty object. * * @return string * The generated html. */ function smarty_block_crmButton($params, $text, &$smarty) { // Generate url (pass 'html' param as false to avoid double-encode by htmlAttributes) if (empty($params['href'])) { $params['href'] = CRM_Utils_System::crmURL($params + array('h' => FALSE)); } // Always add class 'button' - fixme probably should be crm-button $params['class'] = empty($params['class']) ? 'button' : 'button ' . $params['class']; // Any FA icon works $icon = CRM_Utils_Array::value('icon', $params, 'pencil'); // All other params are treated as html attributes CRM_Utils_Array::remove($params, 'icon', 'p', 'q', 'a', 'f', 'h', 'fb', 'fe'); $attributes = CRM_Utils_String::htmlAttributes($params); return "<a {$attributes}><span><i class='crm-i fa-{$icon}'></i> {$text}</span></a>"; }
public function run() { $args = $_REQUEST; if (!empty($args['file']) && strpos($args['file'], '..') === FALSE) { $file = $args['file'] . '.hlp'; $additionalTPLFile = $args['file'] . '.extra.hlp'; $smarty = CRM_Core_Smarty::singleton(); $smarty->assign('id', $args['id']); CRM_Utils_Array::remove($args, 'file', 'class_name', 'type', 'q', 'id'); foreach ($args as &$arg) { $arg = strip_tags($arg); } $smarty->assign('params', $args); $extraoutput = ''; if ($smarty->template_exists($additionalTPLFile)) { //@todo hook has been put here as a conservative approach // but probably should always run. It doesn't run otherwise because of the exit CRM_Utils_Hook::pageRun($this); $extraoutput .= trim($smarty->fetch($additionalTPLFile)); } exit($smarty->fetch($file) . $extraoutput); } }
/** * Get list of batches. * * @param array $params * Associated array for params. * * @return array */ public static function getBatchList(&$params) { $whereClause = self::whereClause($params); if (!empty($params['rowCount']) && is_numeric($params['rowCount']) && is_numeric($params['offset']) && $params['rowCount'] > 0) { $limit = " LIMIT {$params['offset']}, {$params['rowCount']} "; } $orderBy = ' ORDER BY batch.id desc'; if (!empty($params['sort'])) { $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String'); } $query = "\n SELECT batch.*, c.sort_name created_by\n FROM civicrm_batch batch\n INNER JOIN civicrm_contact c ON batch.created_id = c.id\n WHERE {$whereClause}\n {$orderBy}\n {$limit}"; $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Batch_DAO_Batch'); if (!empty($params['context'])) { $links = self::links($params['context']); } else { $links = self::links(); } $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id'); $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id'); $batchStatusByName = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name')); $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $results = array(); while ($object->fetch()) { $values = array(); $newLinks = $links; CRM_Core_DAO::storeValues($object, $values); $action = array_sum(array_keys($newLinks)); if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') { $newLinks = array(); } elseif ($params['context'] == 'financialBatch') { $values['check'] = "<input type='checkbox' id='check_" . $object->id . "' name='check_" . $object->id . "' value='1' data-status_id='" . $values['status_id'] . "' class='select-row'></input>"; switch ($batchStatusByName[$values['status_id']]) { case 'Open': CRM_Utils_Array::remove($newLinks, 'reopen', 'download'); break; case 'Closed': CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'download'); break; case 'Exported': CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'reopen', 'export'); } } if (!empty($values['type_id'])) { $values['batch_type'] = $batchTypes[$values['type_id']]; } $values['batch_status'] = $batchStatus[$values['status_id']]; $values['created_by'] = $object->created_by; $values['payment_instrument'] = ''; if (!empty($object->payment_instrument_id)) { $values['payment_instrument'] = $paymentInstrument[$object->payment_instrument_id]; } $tokens = array('id' => $object->id, 'status' => $values['status_id']); if ($values['status_id'] == array_search('Exported', $batchStatusByName)) { $aid = CRM_Core_OptionGroup::getValue('activity_type', 'Export Accounting Batch'); $activityParams = array('source_record_id' => $object->id, 'activity_type_id' => $aid); $exportActivity = CRM_Activity_BAO_Activity::retrieve($activityParams, $val); $fid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id, 'file_id', 'entity_id'); $tokens = array_merge(array('eid' => $exportActivity->id, 'fid' => $fid), $tokens); } $values['action'] = CRM_Core_Action::formLink($newLinks, $action, $tokens, ts('more'), FALSE, 'batch.selector.row', 'Batch', $object->id); $results[$object->id] = $values; } return $results; }
/** * Get metadata for getfield action. * * @param array $params * @param array $apiRequest * * @throws \CiviCRM_API3_Exception * @throws \Exception */ function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) { $params = array('name' => array('title' => 'Field name', 'description' => 'Name or alias of field to lookup', 'api.required' => 1, 'type' => CRM_Utils_Type::T_STRING), 'action' => array('title' => 'API Action', 'api.required' => 1, 'type' => CRM_Utils_Type::T_STRING, 'api.aliases' => array('api_action')), 'get_options' => array('title' => 'Get Options', 'description' => 'Context for which to get field options, or null to skip fetching options.', 'type' => CRM_Utils_Type::T_STRING, 'options' => CRM_Core_DAO::buildOptionsContext(), 'api.aliases' => array('context'))); // Add available options to these params if requested if (array_intersect(array('all', 'action'), $apiRequest['params']['options']['get_options'])) { $actions = civicrm_api3($apiRequest['entity'], 'getactions'); $actions = array_combine($actions['values'], $actions['values']); // Let's not go meta-crazy CRM_Utils_Array::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update'); $params['action']['options'] = $actions; } }
/** * Create a chain-select target field. All settings are optional; the defaults usually work. * * @param string $elementName * @param array $settings * * @return HTML_QuickForm_Element */ public function addChainSelect($elementName, $settings = array()) { $props = $settings += array('control_field' => str_replace(array('state_province', 'StateProvince', 'county', 'County'), array('country', 'Country', 'state_province', 'StateProvince'), $elementName), 'data-callback' => strpos($elementName, 'rovince') ? 'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty', 'label' => strpos($elementName, 'rovince') ? ts('State/Province') : ts('County'), 'data-empty-prompt' => strpos($elementName, 'rovince') ? ts('Choose country first') : ts('Choose state first'), 'data-none-prompt' => ts('- N/A -'), 'multiple' => FALSE, 'required' => FALSE, 'placeholder' => empty($settings['required']) ? ts('- none -') : ts('- select -')); CRM_Utils_Array::remove($props, 'label', 'required', 'control_field'); $props['class'] = (empty($props['class']) ? '' : "{$props['class']} ") . 'crm-select2'; $props['data-select-prompt'] = $props['placeholder']; $props['data-name'] = $elementName; $this->_chainSelectFields[$settings['control_field']] = $elementName; // Passing NULL instead of an array of options // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected. return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props); }
/** * Get a list of fields which can be added to profiles. * * @param int $gid : UF group ID * @param array $defaults : Form defaults * @return array, multidimensional; e.g. $result['FieldGroup']['field_name']['label'] */ public static function getAvailableFields($gid = NULL, $defaults = array()) { $fields = array('Contact' => array(), 'Individual' => CRM_Contact_BAO_Contact::importableFields('Individual', FALSE, FALSE, TRUE, TRUE, TRUE), 'Household' => CRM_Contact_BAO_Contact::importableFields('Household', FALSE, FALSE, TRUE, TRUE, TRUE), 'Organization' => CRM_Contact_BAO_Contact::importableFields('Organization', FALSE, FALSE, TRUE, TRUE, TRUE)); // include hook injected fields $fields['Contact'] = array_merge($fields['Contact'], CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // add current employer for individuals $fields['Individual']['current_employer'] = array('name' => 'organization_name', 'title' => ts('Current Employer')); $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE); if (!$addressOptions['county']) { unset($fields['Individual']['county'], $fields['Household']['county'], $fields['Organization']['county']); } // break out common contact fields array CRM-3037. // from a UI perspective this makes very little sense foreach ($fields['Individual'] as $key => $value) { if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) { $fields['Contact'][$key] = $value; unset($fields['Individual'][$key], $fields['Household'][$key], $fields['Organization'][$key]); } } // Internal field not exposed to forms unset($fields['Contact']['contact_type']); unset($fields['Contact']['master_id']); // convert phone extension in to psedo-field phone + phone extension //unset extension unset($fields['Contact']['phone_ext']); //add psedo field $fields['Contact']['phone_and_ext'] = array('name' => 'phone_and_ext', 'title' => ts('Phone and Extension'), 'hasLocationType' => 1); // include Subtypes For Profile $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $name => $val) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($name, FALSE, FALSE, FALSE, TRUE, TRUE); if (array_key_exists($val['parent'], $fields)) { $fields[$name] = $fields[$val['parent']] + $subTypeFields; } else { $fields[$name] = $subTypeFields; } } if (CRM_Core_Permission::access('CiviContribute')) { $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields(FALSE); if (!empty($contribFields)) { unset($contribFields['is_test']); unset($contribFields['is_pay_later']); unset($contribFields['contribution_id']); $contribFields['contribution_note'] = array('name' => 'contribution_note', 'title' => ts('Contribution Note')); $fields['Contribution'] = array_merge($contribFields, self::getContribBatchEntryFields()); } } if (CRM_Core_Permission::access('CiviEvent')) { $participantFields = CRM_Event_BAO_Query::getParticipantFields(); if ($participantFields) { // Remove fields not supported by profiles CRM_Utils_Array::remove($participantFields, 'external_identifier', 'event_id', 'participant_contact_id', 'participant_role_id', 'participant_status_id', 'participant_is_test', 'participant_fee_level', 'participant_id', 'participant_is_pay_later', 'participant_campaign'); if (isset($participantFields['participant_campaign_id'])) { $participantFields['participant_campaign_id']['title'] = ts('Campaign'); } $fields['Participant'] = $participantFields; } } if (CRM_Core_Permission::access('CiviMember')) { $membershipFields = CRM_Member_BAO_Membership::getMembershipFields(); // Remove fields not supported by profiles CRM_Utils_Array::remove($membershipFields, 'membership_id', 'membership_type_id', 'member_is_test', 'is_override', 'status_id', 'member_is_pay_later'); if ($gid && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gid, 'name') == 'membership_batch_entry') { $fields['Membership'] = array_merge($membershipFields, self::getMemberBatchEntryFields()); } else { $fields['Membership'] = $membershipFields; } } if (CRM_Core_Permission::access('CiviCase')) { $caseFields = CRM_Case_BAO_Query::getFields(TRUE); $caseFields = array_merge($caseFields, CRM_Core_BAO_CustomField::getFieldsForImport('Case')); if ($caseFields) { // Remove fields not supported by profiles CRM_Utils_Array::remove($caseFields, 'case_id', 'case_type', 'case_start_date', 'case_end_date', 'case_role', 'case_status', 'case_deleted'); } $fields['Case'] = $caseFields; } $activityFields = CRM_Activity_BAO_Activity::getProfileFields(); if ($activityFields) { // campaign related fields. if (isset($activityFields['activity_campaign_id'])) { $activityFields['activity_campaign_id']['title'] = ts('Campaign'); } $fields['Activity'] = $activityFields; } $fields['Formatting']['format_free_html_' . rand(1000, 9999)] = array('name' => 'free_html', 'import' => FALSE, 'export' => FALSE, 'title' => 'Free HTML'); // Sort by title foreach ($fields as &$values) { $values = CRM_Utils_Array::crmArraySortByField($values, 'title'); } //group selected and unwanted fields list $ufFields = $gid ? CRM_Core_BAO_UFGroup::getFields($gid, FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE) : array(); $groupFieldList = array_merge($ufFields, array('note', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'id')); //unset selected fields foreach ($groupFieldList as $key => $value) { if (is_int($key)) { unset($fields['Individual'][$value], $fields['Household'][$value], $fields['Organization'][$value]); continue; } if (!empty($defaults['field_name']) && $defaults['field_name']['0'] == $value['field_type'] && $defaults['field_name']['1'] == $key) { continue; } unset($fields[$value['field_type']][$key]); } return $fields; }
/** * Low-level option getter, rarely accessed directly. * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions() * * @param String $daoName * @param String $fieldName * @param Array $params * - name string name of the option group * - flip boolean results are return in id => label format if false * if true, the results are reversed * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value) * - localize boolean if true, localize the results before returning * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND' * - keyColumn string the column to use for 'id' * - labelColumn string the column to use for 'label' * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn * - onlyActive boolean return only the action option values * - fresh boolean ignore cache entries and go back to DB * @param String $context: Context string * * @return Array on success, FALSE on error. * * @static */ public static function get($daoName, $fieldName, $params = array(), $context = NULL) { CRM_Core_DAO::buildOptionsContext($context); $flip = !empty($params['flip']); // Merge params with defaults $params += array('grouping' => FALSE, 'localize' => FALSE, 'onlyActive' => $context == 'validate' || $context == 'get' ? FALSE : TRUE, 'fresh' => FALSE); // Custom fields are not in the schema if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) { $customField = new CRM_Core_DAO_CustomField(); $customField->id = (int) substr($fieldName, 7); $customField->find(TRUE); $options = FALSE; if (!empty($customField->option_group_id)) { $options = CRM_Core_OptionGroup::valuesByID($customField->option_group_id, $flip, $params['grouping'], $params['localize'], CRM_Utils_Array::value('labelColumn', $params, 'label'), $params['onlyActive'], $params['fresh']); } else { if ($customField->data_type === 'StateProvince') { $options = self::stateProvince(); } elseif ($customField->data_type === 'Country') { $options = $context == 'validate' ? self::countryIsoCode() : self::country(); } elseif ($customField->data_type === 'Boolean') { $options = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No')); } $options = $options && $flip ? array_flip($options) : $options; } if ($options !== FALSE) { CRM_Utils_Hook::customFieldOptions($customField->id, $options, FALSE); } $customField->free(); return $options; } // Core field: load schema $dao = new $daoName(); $fields = $dao->fields(); $fieldKeys = $dao->fieldKeys(); $dao->free(); // Support "unique names" as well as sql names $fieldKey = $fieldName; if (empty($fields[$fieldKey])) { $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys); } // If neither worked then this field doesn't exist. Return false. if (empty($fields[$fieldKey])) { return FALSE; } $fieldSpec = $fields[$fieldKey]; // If the field is an enum, explode the enum definition and return the array. if (isset($fieldSpec['enumValues'])) { // use of a space after the comma is inconsistent in xml $enumStr = str_replace(', ', ',', $fieldSpec['enumValues']); $output = explode(',', $enumStr); return array_combine($output, $output); } elseif (!empty($fieldSpec['pseudoconstant'])) { $pseudoconstant = $fieldSpec['pseudoconstant']; // Merge params with schema defaults $params += array('condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()), 'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant), 'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant)); // Fetch option group from option_value table if (!empty($pseudoconstant['optionGroupName'])) { if ($context == 'validate') { $params['labelColumn'] = 'name'; } // Call our generic fn for retrieving from the option_value table return CRM_Core_OptionGroup::values($pseudoconstant['optionGroupName'], $flip, $params['grouping'], $params['localize'], $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL, $params['labelColumn'] ? $params['labelColumn'] : 'label', $params['onlyActive'], $params['fresh'], $params['keyColumn'] ? $params['keyColumn'] : 'value'); } // Fetch options from other tables if (!empty($pseudoconstant['table'])) { // Normalize params so the serialized cache string will be consistent. CRM_Utils_Array::remove($params, 'flip', 'fresh'); ksort($params); $cacheKey = $daoName . $fieldName . serialize($params); // Retrieve cached options if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) { $output = self::$cache[$cacheKey]; } else { $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']); if (!class_exists($daoName)) { return FALSE; } // Get list of fields for the option table $dao = new $daoName(); $availableFields = array_keys($dao->fieldKeys()); $dao->free(); $select = "SELECT %1 AS id, %2 AS label"; $from = "FROM %3"; $wheres = array(); $order = "ORDER BY %2"; // Use machine name instead of label in validate context if ($context == 'validate') { if (!empty($pseudoconstant['nameColumn'])) { $params['labelColumn'] = $pseudoconstant['nameColumn']; } elseif (in_array('name', $availableFields)) { $params['labelColumn'] = 'name'; } } // Condition param can be passed as an sql clause string or an array of clauses if (!empty($params['condition'])) { $wheres[] = implode(' AND ', (array) $params['condition']); } // onlyActive param will automatically filter on common flags if (!empty($params['onlyActive'])) { foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) { if (in_array($flag, $availableFields)) { $wheres[] = "{$flag} = {$val}"; } } } // Filter domain specific options if (in_array('domain_id', $availableFields)) { $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID(); } $queryParams = array(1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)); // Add orderColumn param if (!empty($params['orderColumn'])) { $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES); $order = "ORDER BY %4"; } elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) { $order = ''; } elseif (in_array('weight', $availableFields)) { $order = "ORDER BY weight"; } $output = array(); $query = "{$select} {$from}"; if ($wheres) { $query .= " WHERE " . implode($wheres, ' AND '); } $query .= ' ' . $order; $dao = CRM_Core_DAO::executeQuery($query, $queryParams); while ($dao->fetch()) { $output[$dao->id] = $dao->label; } $dao->free(); // Localize results if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') { $I18nParams = array(); if ($pseudoconstant['table'] == 'civicrm_country') { $I18nParams['context'] = 'country'; } if ($pseudoconstant['table'] == 'civicrm_state_province') { $I18nParams['context'] = 'province'; } $i18n = CRM_Core_I18n::singleton(); $i18n->localizeArray($output, $I18nParams); // Maintain sort by label if ($order == "ORDER BY %2") { CRM_Utils_Array::asort($output); } } self::$cache[$cacheKey] = $output; } return $flip ? array_flip($output) : $output; } } elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) { $output = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No')); return $flip ? array_flip($output) : $output; } // If we're still here, it's an error. Return FALSE. return FALSE; }
/** * Low-level option getter, rarely accessed directly. * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions() * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference * * NOTE: If someone undertakes a refactoring of this, please consider the use-case of * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling * between $field lookup and the $pseudoconstant evaluation. * * @param string $daoName * @param string $fieldName * @param array $params * - name string name of the option group * - flip boolean results are return in id => label format if false * if true, the results are reversed * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value) * - localize boolean if true, localize the results before returning * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND' * - keyColumn string the column to use for 'id' * - labelColumn string the column to use for 'label' * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn * - onlyActive boolean return only the action option values * - fresh boolean ignore cache entries and go back to DB * @param string $context : Context string * * @return array|bool * array on success, FALSE on error. * */ public static function get($daoName, $fieldName, $params = array(), $context = NULL) { CRM_Core_DAO::buildOptionsContext($context); $flip = !empty($params['flip']); // Merge params with defaults $params += array('grouping' => FALSE, 'localize' => FALSE, 'onlyActive' => $context == 'validate' || $context == 'get' ? FALSE : TRUE, 'fresh' => FALSE, 'context' => $context); $entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getCanonicalClassName($daoName)); // Custom fields are not in the schema if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) { $customField = new CRM_Core_BAO_CustomField(); $customField->id = (int) substr($fieldName, 7); $options = $customField->getOptions(); if ($options && $flip) { $options = array_flip($options); } $customField->free(); return $options; } // Core field: load schema $dao = new $daoName(); $fieldSpec = $dao->getFieldSpec($fieldName); $dao->free(); // Ensure we have the canonical name for this field $fieldName = CRM_Utils_Array::value('name', $fieldSpec, $fieldName); // Return false if field doesn't exist. if (empty($fieldSpec)) { return FALSE; } elseif (!empty($fieldSpec['pseudoconstant'])) { $pseudoconstant = $fieldSpec['pseudoconstant']; // if callback is specified.. if (!empty($pseudoconstant['callback'])) { return call_user_func(Civi\Core\Resolver::singleton()->get($pseudoconstant['callback'])); } // Merge params with schema defaults $params += array('condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()), 'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant), 'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant)); if ($context == 'abbreviate') { switch ($fieldName) { case 'state_province_id': $params['labelColumn'] = 'abbreviation'; break; case 'country_id': $params['labelColumn'] = 'iso_code'; break; default: } } // Fetch option group from option_value table if (!empty($pseudoconstant['optionGroupName'])) { if ($context == 'validate') { $params['labelColumn'] = 'name'; } if ($context == 'match') { $params['keyColumn'] = 'name'; } // Call our generic fn for retrieving from the option_value table $options = CRM_Core_OptionGroup::values($pseudoconstant['optionGroupName'], $flip, $params['grouping'], $params['localize'], $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL, $params['labelColumn'] ? $params['labelColumn'] : 'label', $params['onlyActive'], $params['fresh'], $params['keyColumn'] ? $params['keyColumn'] : 'value'); CRM_Utils_Hook::fieldOptions($entity, $fieldName, $options, $params); return $options; } // Fetch options from other tables if (!empty($pseudoconstant['table'])) { // Normalize params so the serialized cache string will be consistent. CRM_Utils_Array::remove($params, 'flip', 'fresh'); ksort($params); $cacheKey = $daoName . $fieldName . serialize($params); // Retrieve cached options if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) { $output = self::$cache[$cacheKey]; } else { $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']); if (!class_exists($daoName)) { return FALSE; } // Get list of fields for the option table $dao = new $daoName(); $availableFields = array_keys($dao->fieldKeys()); $dao->free(); $select = "SELECT %1 AS id, %2 AS label"; $from = "FROM %3"; $wheres = array(); $order = "ORDER BY %2"; // Use machine name in certain contexts if ($context == 'validate' || $context == 'match') { $nameField = $context == 'validate' ? 'labelColumn' : 'keyColumn'; if (!empty($pseudoconstant['nameColumn'])) { $params[$nameField] = $pseudoconstant['nameColumn']; } elseif (in_array('name', $availableFields)) { $params[$nameField] = 'name'; } } // Condition param can be passed as an sql clause string or an array of clauses if (!empty($params['condition'])) { $wheres[] = implode(' AND ', (array) $params['condition']); } // onlyActive param will automatically filter on common flags if (!empty($params['onlyActive'])) { foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) { if (in_array($flag, $availableFields)) { $wheres[] = "{$flag} = {$val}"; } } } // Filter domain specific options if (in_array('domain_id', $availableFields)) { $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID(); } $queryParams = array(1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)); // Add orderColumn param if (!empty($params['orderColumn'])) { $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES); $order = "ORDER BY %4"; } elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) { $order = ''; } elseif (in_array('weight', $availableFields)) { $order = "ORDER BY weight"; } $output = array(); $query = "{$select} {$from}"; if ($wheres) { $query .= " WHERE " . implode($wheres, ' AND '); } $query .= ' ' . $order; $dao = CRM_Core_DAO::executeQuery($query, $queryParams); while ($dao->fetch()) { $output[$dao->id] = $dao->label; } $dao->free(); // Localize results if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') { $I18nParams = array(); if ($pseudoconstant['table'] == 'civicrm_country') { $I18nParams['context'] = 'country'; } if ($pseudoconstant['table'] == 'civicrm_state_province') { $I18nParams['context'] = 'province'; } $i18n = CRM_Core_I18n::singleton(); $i18n->localizeArray($output, $I18nParams); // Maintain sort by label if ($order == "ORDER BY %2") { CRM_Utils_Array::asort($output); } } CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params); self::$cache[$cacheKey] = $output; } return $flip ? array_flip($output) : $output; } } elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) { $output = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean(); CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params); return $flip ? array_flip($output) : $output; } // If we're still here, it's an error. Return FALSE. return FALSE; }
public function testRemove() { $data = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6); CRM_Utils_Array::remove($data, 'one', 'two', array('three', 'four'), 'five'); $this->assertEquals($data, array('six' => 6)); }
/** * @param $props */ private function formatReferenceFieldAttributes(&$props) { $props['data-select-params'] = json_encode($props['select']); $props['data-api-params'] = $props['api'] ? json_encode($props['api']) : NULL; $props['data-api-entity'] = $props['entity']; CRM_Utils_Array::remove($props, 'multiple', 'select', 'api', 'entity', 'placeholder'); }