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);
124 // too hard basket for now - just do what we always did.
125 return $row->format('text/plain')->tokens($entity, $field,
126 \CRM_Utils_Money
::format($fieldValue, $currency));
128 return $row->format('text/plain')->tokens($entity, $field,
129 Money
::of($fieldValue, $currency));
132 if ($this->isDateField($field)) {
134 return $row->format('text/plain')
135 ->tokens($entity, $field, ($fieldValue ?
new DateTime($fieldValue) : $fieldValue));
137 catch (Exception
$e) {
138 Civi
::log()->info('invalid date token');
141 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
145 * Metadata about the entity fields.
149 protected $fieldMetadata = [];
152 * Get the entity name for api v4 calls.
156 protected function getApiEntityName(): string {
161 * Get the entity alias to use within queries.
163 * The default has a double underscore which should prevent any
164 * ambiguity with an existing table name.
168 protected function getEntityAlias(): string {
169 return $this->getApiEntityName() . '__';
173 * Get the name of the table this token class can extend.
175 * The default is based on the entity but some token classes,
176 * specifically the event class, latch on to other tables - ie
177 * the participant table.
179 public function getExtendableTableName(): string {
180 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($this->getApiEntityName());
184 * Get an array of fields to be requested.
186 * @todo this function should look up tokenMetadata that
191 protected function getReturnFields(): array {
192 return array_keys($this->getBasicTokens());
196 * Is the given field a boolean field.
198 * @param string $fieldName
202 protected function isBooleanField(string $fieldName): bool {
203 return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
207 * Is the given field a date field.
209 * @param string $fieldName
213 protected function isDateField(string $fieldName): bool {
214 return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
218 * Is the given field a pseudo field.
220 * @param string $fieldName
224 protected function isPseudoField(string $fieldName): bool {
225 return strpos($fieldName, ':') !== FALSE;
229 * Is the given field a custom field.
231 * @param string $fieldName
235 protected function isCustomField(string $fieldName) : bool {
236 return (bool) \CRM_Core_BAO_CustomField
::getKeyID($fieldName);
240 * Is the given field a date field.
242 * @param string $fieldName
246 protected function isMoneyField(string $fieldName): bool {
247 return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
251 * Get the metadata for the available fields.
255 protected function getFieldMetadata(): array {
256 if (empty($this->fieldMetadata
)) {
258 // Tests fail without checkPermissions = FALSE
259 $this->fieldMetadata
= (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name');
261 catch (API_Exception
$e) {
262 $this->fieldMetadata
= [];
265 return $this->fieldMetadata
;
269 * Get any tokens with custom calculation.
271 protected function getBespokeTokens(): array {
276 * Get the value for the relevant pseudo field.
278 * @param string $realField e.g contribution_status_id
279 * @param string $pseudoKey e.g name
280 * @param int|string $fieldValue e.g 1
283 * Eg. 'Completed' in the example above.
285 * @internal function will likely be protected soon.
287 protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
288 $bao = CRM_Core_DAO_AllCoreTables
::getFullName($this->getMetadataForField($realField)['entity']);
289 if ($pseudoKey === 'name') {
290 $fieldValue = (string) CRM_Core_PseudoConstant
::getName($bao, $realField, $fieldValue);
292 if ($pseudoKey === 'label') {
293 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel($bao, $realField, $fieldValue);
295 if ($pseudoKey === 'abbr' && $realField === 'state_province_id') {
296 // hack alert - currently only supported for state.
297 $fieldValue = (string) CRM_Core_PseudoConstant
::stateProvinceAbbreviation($fieldValue);
299 return (string) $fieldValue;
303 * @param \Civi\Token\TokenRow $row
304 * @param string $field
307 protected function getFieldValue(TokenRow
$row, string $field) {
308 $entityName = $this->getEntityName();
309 if (isset($row->context
[$entityName][$field])) {
310 return $row->context
[$entityName][$field];
313 $entityID = $row->context
[$this->getEntityIDField()];
314 if ($field === 'id') {
317 return $this->prefetch
[$entityID][$field] ??
'';
323 public function __construct() {
324 parent
::__construct($this->getEntityName(), []);
328 * Check if the token processor is active.
330 * @param \Civi\Token\TokenProcessor $processor
334 public function checkActive(TokenProcessor
$processor) {
335 return (!empty($processor->context
['actionMapping'])
336 // This makes the 'schema context compulsory - which feels accidental
337 // since recent discu
338 && $processor->context
['actionMapping']->getEntity()) ||
in_array($this->getEntityIDField(), $processor->context
['schema']);
342 * Alter action schedule query.
344 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
346 public function alterActionScheduleQuery(MailingQueryEvent
$e): void
{
347 if ($e->mapping
->getEntity() !== $this->getExtendableTableName()) {
350 $e->query
->select('e.id AS tokenContext_' . $this->getEntityIDField());
354 * Get tokens to be suppressed from the widget.
356 * Note this is expected to be an interim function. Now we are no
357 * longer working around the parent function we can just define them once...
358 * with metadata, in a future refactor.
360 protected function getHiddenTokens(): array {
365 * @todo remove this function & use the metadata that is loaded.
368 * @throws \API_Exception
370 protected function getBasicTokens(): array {
372 foreach ($this->getExposedFields() as $fieldName) {
373 // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
374 // for now to allow us to consider how to handle names vs labels vs values
375 // and other raw vs not raw options.
376 if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') {
377 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
384 * Get entity fields that should be exposed as tokens.
389 protected function getExposedFields(): array {
391 foreach ($this->getFieldMetadata() as $field) {
392 if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) {
393 $return[] = $field['name'];
400 * Get entity fields that should not be exposed as tokens.
404 protected function getSkippedFields(): array {
405 // tags is offered in 'case' & is one of the only fields that is
406 // 'not a real field' offered up by case - seems like an oddity
407 // we should skip at the top level for now.
409 if (!CRM_Campaign_BAO_Campaign
::isCampaignEnable()) {
410 $fields[] = 'campaign_id';
418 protected function getEntityName(): string {
419 return CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($this->getApiEntityName());
422 protected function getEntityIDField(): string {
423 return $this->getEntityName() . 'Id';
426 public function prefetch(TokenValueEvent
$e): ?
array {
427 $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField());
428 if (empty($entityIDs)) {
431 $select = $this->getPrefetchFields($e);
432 $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [
433 'checkPermissions' => FALSE,
434 // Note custom fields are not yet added - I need to
435 // re-do the unit tests to support custom fields first.
437 'where' => [['id', 'IN', $entityIDs]],
442 protected function getCurrencyFieldName() {
447 * Get the currency to use for formatting money.
452 protected function getCurrency($row): string {
453 if (!empty($this->getCurrencyFieldName())) {
454 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
456 return CRM_Core_Config
::singleton()->defaultCurrency
;
460 * Get the fields required to prefetch the entity.
462 * @param \Civi\Token\Event\TokenValueEvent $e
465 * @throws \API_Exception
467 public function getPrefetchFields(TokenValueEvent
$e): array {
468 $allTokens = array_keys($this->getTokenMetadata());
469 $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens);
470 if (empty($requiredFields)) {
473 $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName())));
474 foreach ($this->getDependencies() as $field => $required) {
475 if (in_array($field, $this->getActiveTokens($e), TRUE)) {
476 foreach ((array) $required as $key) {
477 $requiredFields[] = $key;
481 return $requiredFields;
485 * Get fields which need to be returned to render another token.
489 protected function getDependencies(): array {
494 * Get the apiv4 style custom field name.
500 * @throws \CRM_Core_Exception
502 protected function getCustomFieldName(int $id): string {
503 foreach ($this->getTokenMetadata() as $key => $field) {
504 if (($field['custom_field_id'] ??
NULL) === $id) {
508 throw new CRM_Core_Exception(
509 "A custom field with the ID {$id} does not exist"
515 * @param string $field eg. 'custom_1'
517 * @return array|string|void|null $mixed
519 * @throws \CRM_Core_Exception
521 protected function getCustomFieldValue($entityID, string $field) {
522 $id = str_replace('custom_', '', $field);
524 $value = $this->prefetch
[$entityID][$this->getCustomFieldName($id)] ??
'';
525 if ($value !== NULL) {
526 return CRM_Core_BAO_CustomField
::displayValue($value, $id);
529 catch (CRM_Core_Exception
$exception) {
535 * Get the metadata for the field.
537 * @param string $fieldName
541 protected function getMetadataForField($fieldName): array {
542 if (isset($this->getTokenMetadata()[$fieldName])) {
543 return $this->getTokenMetadata()[$fieldName];
545 if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
546 return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
548 return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ??
[];
552 * Get token mappings for related entities - specifically the contact entity.
554 * This function exists to help manage the way contact tokens is structured
555 * of an query-object style result set that needs to be mapped to apiv4.
557 * The end goal is likely to be to advertised tokens that better map to api
558 * v4 and deprecate the existing ones but that is a long-term migration.
562 protected function getTokenMappingsForRelatedEntities(): array {
567 * Get array of deprecated tokens and the new token they map to.
571 protected function getDeprecatedTokens(): array {
576 * Get any overrides for token metadata.
578 * This is most obviously used for setting the audience, which
579 * will affect widget-presence.
581 * @return \string[][]
583 protected function getTokenMetadataOverrides(): array {
588 * To handle variable tokens, override this function and return the active tokens.
590 * @param \Civi\Token\Event\TokenValueEvent $e
594 public function getActiveTokens(TokenValueEvent
$e) {
595 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
596 if (!isset($messageTokens[$this->entity
])) {
599 return array_intersect($messageTokens[$this->entity
], array_keys($this->getTokenMetadata()));
603 * Add the token to the metadata based on the field spec.
605 * @param array $tokensMetadata
606 * @param array $field
607 * @param array $exposedFields
608 * @param string $prefix
610 protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void
{
611 if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
614 $field['audience'] = 'user';
615 if ($field['name'] === 'contact_id') {
616 // Since {contact.id} is almost always present don't confuse users
617 // by also adding (e.g {participant.contact_id)
618 $field['audience'] = 'sysadmin';
620 if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
621 $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
623 if ($field['type'] === 'Custom') {
624 // Convert to apiv3 style for now. Later we can add v4 with
625 // portable naming & support for labels/ dates etc so let's leave
626 // the space open for that.
627 // Not the existing quickform widget has handling for the custom field
628 // format based on the title using this syntax.
629 $parts = explode(': ', $field['label']);
630 $field['title'] = "{$parts[1]} :: {$parts[0]}";
631 $tokenName = 'custom_' . $field['custom_field_id'];
632 $tokensMetadata[$tokenName] = $field;
635 $tokenName = $prefix ?
($prefix . '.' . $field['name']) : $field['name'];
636 if (in_array($field['name'], $exposedFields, TRUE)) {
638 ($field['options'] ||
!empty($field['suffixes']))
639 // At the time of writing currency didn't have a label option - this may have changed.
640 && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
642 $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
643 $fieldLabel = $field['input_attrs']['label'] ??
$field['label'];
644 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
645 $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
646 $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
647 $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
648 $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
649 $field['audience'] = 'sysadmin';
651 if ($field['data_type'] === 'Boolean') {
652 $tokensMetadata[$tokenName . ':label'] = $field;
653 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
654 $field['audience'] = 'sysadmin';
656 $tokensMetadata[$tokenName] = $field;
661 * Get a cache key appropriate to the current usage.
665 protected function getCacheKey(): string {
666 $cacheKey = __CLASS__
. 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config
::domainID() . '_' . CRM_Core_I18n
::getLocale();
667 if ($this->checkPermissions
) {
668 $cacheKey .= '__' . CRM_Core_Session
::getLoggedInContactID();