/** * Attempts to retrieve the API entity name from any calling class. * * @param string|object $classNameOrObject * * @return string * @throws CRM_Core_Exception */ static function getEntityName($classNameOrObject) { require_once 'api/api.php'; $className = is_string($classNameOrObject) ? $classNameOrObject : get_class($classNameOrObject); // First try the obvious replacements $daoName = str_replace(array('_BAO_', '_Form_', '_Page_'), '_DAO_', $className); $shortName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); // If that didn't work, try a different pattern if (!$shortName) { list(, $parent, , $child) = explode('_', $className); $daoName = "CRM_{$parent}_DAO_{$child}"; $shortName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } // If that didn't work, try a different pattern if (!$shortName) { $daoName = "CRM_{$parent}_DAO_{$parent}"; $shortName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } // If that didn't work, try a different pattern if (!$shortName) { $daoName = "CRM_Core_DAO_{$child}"; $shortName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } if (!$shortName) { throw new CRM_Core_Exception('Could not find api name for supplied class'); } return _civicrm_api_get_entity_name_from_camel($shortName); }
/** * Attempts to retrieve the API entity name from any calling class. * FIXME: This is a bit hackish but the naming convention for forms is not very strict * * @param string|object $classNameOrObject * * @return string * @throws CRM_Core_Exception */ public static function getEntityName($classNameOrObject) { require_once 'api/api.php'; $className = is_string($classNameOrObject) ? $classNameOrObject : get_class($classNameOrObject); // First try the obvious replacements $daoName = str_replace(array('_BAO_', '_Form_', '_Page_'), '_DAO_', $className); $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); // If that didn't work, try a different pattern if (!$entityName) { list(, $parent, , $child) = explode('_', $className); $daoName = "CRM_{$parent}_DAO_{$child}"; $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } // If that didn't work, try a different pattern if (!$entityName) { $daoName = "CRM_{$parent}_DAO_{$parent}"; $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } // If that didn't work, try a different pattern if (!$entityName) { $daoName = "CRM_Core_DAO_{$child}"; $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($daoName); } // If that didn't work, try using just the trailing name if (!$entityName) { $entityName = CRM_Core_DAO_AllCoreTables::getFullName($child) ? $child : NULL; } // If that didn't work, try using just the leading name if (!$entityName) { $entityName = CRM_Core_DAO_AllCoreTables::getFullName($parent) ? $parent : NULL; } if (!$entityName) { throw new CRM_Core_Exception('Could not find api name for supplied class'); } return $entityName; }
/** * Apply common settings to entityRef fields. * * @param array $field * @param string $table */ private function setEntityRefDefaults(&$field, $table) { $field['attributes'] = $field['attributes'] ? $field['attributes'] : array(); $field['attributes'] += array('entity' => CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)), 'multiple' => TRUE, 'placeholder' => ts('- select -')); }
/** * Having a DAO object find the entity name * @param object $bao DAO being passed in * @return string */ function _civicrm_api_get_entity_name_from_dao($bao) { $daoName = str_replace("BAO", "DAO", get_class($bao)); return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables::getBriefName($daoName)); }
/** * @param $entityTable */ public static function preProcess($entityTable) { self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive'); self::$_entityTable = $entityTable; if (self::$_entityId && $entityTable) { $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable); if ($checkParentExistsForThisId) { self::$_hasParent = TRUE; self::$_parentEntityId = $checkParentExistsForThisId; self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable); } else { self::$_parentEntityId = self::$_entityId; self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable); } if (property_exists(self::$_scheduleReminderDetails, 'id')) { self::$_scheduleReminderID = self::$_scheduleReminderDetails->id; } } CRM_Core_OptionValue::getValues(array('name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId), $optionValue); $excludeOptionValues = array(); if (!empty($optionValue)) { foreach ($optionValue as $key => $val) { $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10); } self::$_excludeDateInfo = $excludeOptionValues; } // Assign variables $entityType = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable)); $tpl = CRM_Core_Smarty::singleton(); $tpl->assign('recurringEntityType', ts($entityType)); $tpl->assign('currentEntityId', self::$_entityId); $tpl->assign('entityTable', self::$_entityTable); $tpl->assign('scheduleReminderId', self::$_scheduleReminderID); $tpl->assign('hasParent', self::$_hasParent); }
/** * Returns fields allowable by api. * * @param $entity * String Entity to query. * @param bool $unique * Index by unique fields?. * @param array $params * * @return array */ function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) { $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import'); $dao = _civicrm_api3_get_DAO($entity); if (empty($dao)) { return array(); } $d = new $dao(); $fields = $d->fields(); // replace uniqueNames by the normal names as the key if (empty($unique)) { foreach ($fields as $name => &$field) { //getting rid of unused attributes foreach ($unsetIfEmpty as $attr) { if (empty($field[$attr])) { unset($field[$attr]); } } if ($name == $field['name']) { continue; } if (array_key_exists($field['name'], $fields)) { $field['error'] = 'name conflict'; // it should never happen, but better safe than sorry continue; } $fields[$field['name']] = $field; $fields[$field['name']]['uniqueName'] = $name; unset($fields[$name]); } } // Translate FKClassName to the corresponding api foreach ($fields as $name => &$field) { if (!empty($field['FKClassName'])) { $FKApi = CRM_Core_DAO_AllCoreTables::getBriefName($field['FKClassName']); if ($FKApi) { $field['FKApiName'] = $FKApi; } } } $fields += _civicrm_api_get_custom_fields($entity, $params); return $fields; }
/** * 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; }
/** * For BAO's which don't have a create() or add() functions, use this fallback implementation. * * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class * structure. In practice, that requires a fair amount of refactoring and/or kludgery. * * @param string $bao_name * @param array $params * * @throws API_Exception * @return CRM_Core_DAO|NULL an instance of the BAO */ function _civicrm_api3_basic_create_fallback($bao_name, &$params) { $dao_name = get_parent_class($bao_name); if ($dao_name === 'CRM_Core_DAO' || !$dao_name) { $dao_name = $bao_name; } $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($dao_name); if (empty($entityName)) { throw new API_Exception("Class \"{$bao_name}\" does not map to an entity name", "unmapped_class_to_entity", array('class_name' => $bao_name)); } $hook = empty($params['id']) ? 'create' : 'edit'; CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params); $instance = new $dao_name(); $instance->copyValues($params); $instance->save(); CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance); return $instance; }
/** * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity * * Return format is in the form of fieldname => clauses starting with an operator. e.g.: * @code * array( * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)') * ) * @endcode * * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values. * * @return array */ public function addSelectWhereClause() { $clauses = array(); $fields = $this->fields(); foreach ($fields as $fieldName => $field) { // Clause for contact-related entities like Email, Relationship, etc. if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') { $clauses[$fieldName] = CRM_Utils_SQL::mergeSubquery('Contact'); } // Clause for an entity_table/entity_id combo if ($fieldName == 'entity_id' && isset($fields['entity_table'])) { $relatedClauses = array(); $relatedEntities = $this->buildOptions('entity_table', 'get'); foreach ((array) $relatedEntities as $table => $ent) { if (!empty($ent)) { $ent = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)); $subquery = CRM_Utils_SQL::mergeSubquery($ent); if ($subquery) { $relatedClauses[] = "(entity_table = '{$table}' AND entity_id " . implode(' AND entity_id ', $subquery) . ")"; } else { $relatedClauses[] = "(entity_table = '{$table}')"; } } } if ($relatedClauses) { $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))'; } } } CRM_Utils_Hook::selectWhereClause($this, $clauses); return $clauses; }
/** * @param string $entityTable * The target entity table (e.g. "civicrm_mailing" or "civicrm_activity"). * @return string|NULL * The target entity name (e.g. "Mailing" or "Activity"). */ public function getDelegatedEntityName($entityTable) { if ($this->allowedDelegates === NULL || in_array($entityTable, $this->allowedDelegates)) { $className = \CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable); if ($className) { $entityName = \CRM_Core_DAO_AllCoreTables::getBriefName($className); if ($entityName) { return $entityName; } } } return NULL; }