4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
13 use Civi\Token\AbstractTokenSubscriber
;
14 use Civi\Token\Event\TokenRegisterEvent
;
15 use Civi\Token\Event\TokenValueEvent
;
16 use Civi\Token\TokenRow
;
17 use Civi\ActionSchedule\Event\MailingQueryEvent
;
18 use Civi\Token\TokenProcessor
;
19 use Brick\Money\Money
;
22 * Class CRM_Core_EntityTokens
24 * Parent class for generic entity token functionality.
26 * WARNING - this class is highly likely to be temporary and
27 * to be consolidated with the TokenTrait and / or the
28 * AbstractTokenSubscriber in future. It is being used to clarify
29 * functionality but should NOT be used from outside of core tested code.
31 class CRM_Core_EntityTokens
extends AbstractTokenSubscriber
{
34 * Metadata about all tokens.
38 protected $tokensMetadata = [];
42 protected $prefetch = [];
45 * Should permissions be checked when loading tokens.
49 protected $checkPermissions = FALSE;
52 * Register the declared tokens.
54 * @param \Civi\Token\Event\TokenRegisterEvent $e
55 * The registration event. Add new tokens using register().
57 public function registerTokens(TokenRegisterEvent
$e) {
58 if (!$this->checkActive($e->getTokenProcessor())) {
61 foreach ($this->getTokenMetadata() as $tokenName => $field) {
62 if ($field['audience'] === 'user') {
64 'entity' => $this->entity
,
65 'field' => $tokenName,
66 'label' => $field['title'],
73 * Get the metadata about the available tokens
77 protected function getTokenMetadata(): array {
78 $cacheKey = $this->getCacheKey();
79 if (!Civi
::cache('metadata')->has($cacheKey)) {
80 $tokensMetadata = $this->getBespokeTokens();
81 foreach ($this->getFieldMetadata() as $field) {
82 $this->addFieldToTokenMetadata($tokensMetadata, $field, $this->getExposedFields());
84 foreach ($this->getHiddenTokens() as $name) {
85 $tokensMetadata[$name]['audience'] = 'hidden';
87 Civi
::cache('metadata')->set($cacheKey, $tokensMetadata);
89 return Civi
::cache('metadata')->get($cacheKey);
94 * @throws \CRM_Core_Exception
96 public function evaluateToken(TokenRow
$row, $entity, $field, $prefetch = NULL) {
97 $this->prefetch
= (array) $prefetch;
98 $fieldValue = $this->getFieldValue($row, $field);
99 if (is_array($fieldValue)) {
100 // eg. role_id for participant would be an array here.
101 $fieldValue = implode(',', $fieldValue);
104 if ($this->isPseudoField($field)) {
105 if (!empty($fieldValue)) {
106 // If it's set here it has already been loaded in pre-fetch.
107 return $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
109 // Once prefetch is fully standardised we can remove this - as long
110 // as tests pass we should be fine as tests cover this.
111 $split = explode(':', $field);
112 return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0])));
114 if ($this->isCustomField($field)) {
115 $prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field);
116 if ($prefetchedValue) {
117 return $row->format('text/html')->tokens($entity, $field, $prefetchedValue);
119 return $row->customToken($entity, \CRM_Core_BAO_CustomField
::getKeyID($field), $this->getFieldValue($row, 'id'));
121 if ($this->isMoneyField($field)) {
122 $currency = $this->getCurrency($row);
123 if (empty($fieldValue) && !is_numeric($fieldValue)) {
127 // too hard basket for now - just do what we always did.
128 return $row->format('text/plain')->tokens($entity, $field,
129 \CRM_Utils_Money
::format($fieldValue, $currency));
131 return $row->format('text/plain')->tokens($entity, $field,
132 Money
::of($fieldValue, $currency));
135 if ($this->isDateField($field)) {
137 return $row->format('text/plain')
138 ->tokens($entity, $field, ($fieldValue ?
new DateTime($fieldValue) : $fieldValue));
140 catch (Exception
$e) {
141 Civi
::log()->info('invalid date token');
144 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
148 * Metadata about the entity fields.
152 protected $fieldMetadata = [];
155 * Get the entity name for api v4 calls.
159 protected function getApiEntityName(): string {
164 * Get the entity alias to use within queries.
166 * The default has a double underscore which should prevent any
167 * ambiguity with an existing table name.
171 protected function getEntityAlias(): string {
172 return $this->getApiEntityName() . '__';
176 * Get the name of the table this token class can extend.
178 * The default is based on the entity but some token classes,
179 * specifically the event class, latch on to other tables - ie
180 * the participant table.
182 public function getExtendableTableName(): string {
183 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($this->getApiEntityName());
187 * Get an array of fields to be requested.
189 * @todo this function should look up tokenMetadata that
194 protected function getReturnFields(): array {
195 return array_keys($this->getBasicTokens());
199 * Is the given field a boolean field.
201 * @param string $fieldName
205 protected function isBooleanField(string $fieldName): bool {
206 return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
210 * Is the given field a date field.
212 * @param string $fieldName
216 protected function isDateField(string $fieldName): bool {
217 return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
221 * Is the given field a pseudo field.
223 * @param string $fieldName
227 protected function isPseudoField(string $fieldName): bool {
228 return strpos($fieldName, ':') !== FALSE;
232 * Is the given field a custom field.
234 * @param string $fieldName
238 protected function isCustomField(string $fieldName) : bool {
239 return (bool) \CRM_Core_BAO_CustomField
::getKeyID($fieldName);
243 * Is the given field a date field.
245 * @param string $fieldName
249 protected function isMoneyField(string $fieldName): bool {
250 return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
254 * Get the metadata for the available fields.
258 protected function getFieldMetadata(): array {
259 if (empty($this->fieldMetadata
)) {
261 // Tests fail without checkPermissions = FALSE
262 $this->fieldMetadata
= (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name');
264 catch (API_Exception
$e) {
265 $this->fieldMetadata
= [];
268 return $this->fieldMetadata
;
272 * Get any tokens with custom calculation.
274 protected function getBespokeTokens(): array {
279 * Get the value for the relevant pseudo field.
281 * @param string $realField e.g contribution_status_id
282 * @param string $pseudoKey e.g name
283 * @param int|string $fieldValue e.g 1
286 * Eg. 'Completed' in the example above.
288 * @internal function will likely be protected soon.
290 protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
291 $bao = CRM_Core_DAO_AllCoreTables
::getFullName($this->getMetadataForField($realField)['entity']);
292 if ($pseudoKey === 'name') {
293 $fieldValue = (string) CRM_Core_PseudoConstant
::getName($bao, $realField, $fieldValue);
295 if ($pseudoKey === 'label') {
296 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel($bao, $realField, $fieldValue);
298 if ($pseudoKey === 'abbr' && $realField === 'state_province_id') {
299 // hack alert - currently only supported for state.
300 $fieldValue = (string) CRM_Core_PseudoConstant
::stateProvinceAbbreviation($fieldValue);
302 return (string) $fieldValue;
306 * @param \Civi\Token\TokenRow $row
307 * @param string $field
310 protected function getFieldValue(TokenRow
$row, string $field) {
311 $entityName = $this->getEntityName();
312 if (isset($row->context
[$entityName][$field])) {
313 return $row->context
[$entityName][$field];
316 $entityID = $row->context
[$this->getEntityIDField()];
317 if ($field === 'id') {
320 return $this->prefetch
[$entityID][$field] ??
'';
326 public function __construct() {
327 parent
::__construct($this->getEntityName(), []);
331 * Check if the token processor is active.
333 * @param \Civi\Token\TokenProcessor $processor
337 public function checkActive(TokenProcessor
$processor) {
338 return (!empty($processor->context
['actionMapping'])
339 // This makes the 'schema context compulsory - which feels accidental
340 // since recent discu
341 && $processor->context
['actionMapping']->getEntity()) ||
in_array($this->getEntityIDField(), $processor->context
['schema']);
345 * Alter action schedule query.
347 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
349 public function alterActionScheduleQuery(MailingQueryEvent
$e): void
{
350 if ($e->mapping
->getEntity() !== $this->getExtendableTableName()) {
353 $e->query
->select('e.id AS tokenContext_' . $this->getEntityIDField());
357 * Get tokens to be suppressed from the widget.
359 * Note this is expected to be an interim function. Now we are no
360 * longer working around the parent function we can just define them once...
361 * with metadata, in a future refactor.
363 protected function getHiddenTokens(): array {
368 * @todo remove this function & use the metadata that is loaded.
371 * @throws \API_Exception
373 protected function getBasicTokens(): array {
375 foreach ($this->getExposedFields() as $fieldName) {
376 // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
377 // for now to allow us to consider how to handle names vs labels vs values
378 // and other raw vs not raw options.
379 if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') {
380 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
387 * Get entity fields that should be exposed as tokens.
392 protected function getExposedFields(): array {
394 foreach ($this->getFieldMetadata() as $field) {
395 if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) {
396 $return[] = $field['name'];
403 * Get entity fields that should not be exposed as tokens.
407 protected function getSkippedFields(): array {
408 // tags is offered in 'case' & is one of the only fields that is
409 // 'not a real field' offered up by case - seems like an oddity
410 // we should skip at the top level for now.
412 if (!CRM_Campaign_BAO_Campaign
::isCampaignEnable()) {
413 $fields[] = 'campaign_id';
421 protected function getEntityName(): string {
422 return CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($this->getApiEntityName());
425 protected function getEntityIDField(): string {
426 return $this->getEntityName() . 'Id';
429 public function prefetch(TokenValueEvent
$e): ?
array {
430 $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField());
431 if (empty($entityIDs)) {
434 $select = $this->getPrefetchFields($e);
435 $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [
436 'checkPermissions' => FALSE,
437 // Note custom fields are not yet added - I need to
438 // re-do the unit tests to support custom fields first.
440 'where' => [['id', 'IN', $entityIDs]],
445 protected function getCurrencyFieldName() {
450 * Get the currency to use for formatting money.
455 protected function getCurrency($row): string {
456 if (!empty($this->getCurrencyFieldName())) {
457 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
459 return CRM_Core_Config
::singleton()->defaultCurrency
;
463 * Get the fields required to prefetch the entity.
465 * @param \Civi\Token\Event\TokenValueEvent $e
468 * @throws \API_Exception
470 public function getPrefetchFields(TokenValueEvent
$e): array {
471 $allTokens = array_keys($this->getTokenMetadata());
472 $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens);
473 if (empty($requiredFields)) {
476 $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName())));
477 foreach ($this->getDependencies() as $field => $required) {
478 if (in_array($field, $this->getActiveTokens($e), TRUE)) {
479 foreach ((array) $required as $key) {
480 $requiredFields[] = $key;
484 return $requiredFields;
488 * Get fields which need to be returned to render another token.
492 protected function getDependencies(): array {
497 * Get the apiv4 style custom field name.
503 * @throws \CRM_Core_Exception
505 protected function getCustomFieldName(int $id): string {
506 foreach ($this->getTokenMetadata() as $key => $field) {
507 if (($field['custom_field_id'] ??
NULL) === $id) {
511 throw new CRM_Core_Exception(
512 "A custom field with the ID {$id} does not exist"
518 * @param string $field eg. 'custom_1'
520 * @return array|string|void|null $mixed
522 * @throws \CRM_Core_Exception
524 protected function getCustomFieldValue($entityID, string $field) {
525 $id = str_replace('custom_', '', $field);
527 $value = $this->prefetch
[$entityID][$this->getCustomFieldName($id)] ??
'';
528 if ($value !== NULL) {
529 return CRM_Core_BAO_CustomField
::displayValue($value, $id);
532 catch (CRM_Core_Exception
$exception) {
538 * Get the metadata for the field.
540 * @param string $fieldName
544 protected function getMetadataForField($fieldName): array {
545 if (isset($this->getTokenMetadata()[$fieldName])) {
546 return $this->getTokenMetadata()[$fieldName];
548 if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
549 return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
551 return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ??
[];
555 * Get token mappings for related entities - specifically the contact entity.
557 * This function exists to help manage the way contact tokens is structured
558 * of an query-object style result set that needs to be mapped to apiv4.
560 * The end goal is likely to be to advertised tokens that better map to api
561 * v4 and deprecate the existing ones but that is a long-term migration.
565 protected function getTokenMappingsForRelatedEntities(): array {
570 * Get array of deprecated tokens and the new token they map to.
574 protected function getDeprecatedTokens(): array {
579 * Get any overrides for token metadata.
581 * This is most obviously used for setting the audience, which
582 * will affect widget-presence.
584 * @return \string[][]
586 protected function getTokenMetadataOverrides(): array {
591 * To handle variable tokens, override this function and return the active tokens.
593 * @param \Civi\Token\Event\TokenValueEvent $e
597 public function getActiveTokens(TokenValueEvent
$e) {
598 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
599 if (!isset($messageTokens[$this->entity
])) {
602 return array_intersect($messageTokens[$this->entity
], array_keys($this->getTokenMetadata()));
606 * Add the token to the metadata based on the field spec.
608 * @param array $tokensMetadata
609 * @param array $field
610 * @param array $exposedFields
611 * @param string $prefix
613 protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void
{
614 if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
617 $field['audience'] = 'user';
618 if ($field['name'] === 'contact_id') {
619 // Since {contact.id} is almost always present don't confuse users
620 // by also adding (e.g {participant.contact_id)
621 $field['audience'] = 'sysadmin';
623 if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
624 $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
626 if ($field['type'] === 'Custom') {
627 // Convert to apiv3 style for now. Later we can add v4 with
628 // portable naming & support for labels/ dates etc so let's leave
629 // the space open for that.
630 // Not the existing quickform widget has handling for the custom field
631 // format based on the title using this syntax.
632 $parts = explode(': ', $field['label']);
633 $field['title'] = "{$parts[1]} :: {$parts[0]}";
634 $tokenName = 'custom_' . $field['custom_field_id'];
635 $tokensMetadata[$tokenName] = $field;
638 $tokenName = $prefix ?
($prefix . '.' . $field['name']) : $field['name'];
639 if (in_array($field['name'], $exposedFields, TRUE)) {
641 ($field['options'] ||
!empty($field['suffixes']))
642 // At the time of writing currency didn't have a label option - this may have changed.
643 && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
645 $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
646 $fieldLabel = $field['input_attrs']['label'] ??
$field['label'];
647 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
648 $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
649 $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
650 $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
651 $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
652 $field['audience'] = 'sysadmin';
654 if ($field['data_type'] === 'Boolean') {
655 $tokensMetadata[$tokenName . ':label'] = $field;
656 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
657 $field['audience'] = 'sysadmin';
659 $tokensMetadata[$tokenName] = $field;
664 * Get a cache key appropriate to the current usage.
668 protected function getCacheKey(): string {
669 $cacheKey = __CLASS__
. 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config
::domainID() . '_' . CRM_Core_I18n
::getLocale();
670 if ($this->checkPermissions
) {
671 $cacheKey .= '__' . CRM_Core_Session
::getLoggedInContactID();