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
;
21 * Class CRM_Core_EntityTokens
23 * Parent class for generic entity token functionality.
25 * WARNING - this class is highly likely to be temporary and
26 * to be consolidated with the TokenTrait and / or the
27 * AbstractTokenSubscriber in future. It is being used to clarify
28 * functionality but should NOT be used from outside of core tested code.
30 class CRM_Core_EntityTokens
extends AbstractTokenSubscriber
{
33 * Metadata about all tokens.
37 protected $tokensMetadata = [];
41 protected $prefetch = [];
44 * Should permissions be checked when loading tokens.
48 protected $checkPermissions = FALSE;
51 * Register the declared tokens.
53 * @param \Civi\Token\Event\TokenRegisterEvent $e
54 * The registration event. Add new tokens using register().
56 public function registerTokens(TokenRegisterEvent
$e) {
57 if (!$this->checkActive($e->getTokenProcessor())) {
60 foreach ($this->getTokenMetadata() as $tokenName => $field) {
61 if ($field['audience'] === 'user') {
63 'entity' => $this->entity
,
64 'field' => $tokenName,
65 'label' => $field['title'],
72 * Get the metadata about the available tokens
76 protected function getTokenMetadata(): array {
77 if (empty($this->tokensMetadata
)) {
78 $cacheKey = $this->getCacheKey();
79 if (Civi
::cache('metadata')->has($cacheKey)) {
80 $this->tokensMetadata
= Civi
::cache('metadata')->get($cacheKey);
83 $this->tokensMetadata
= $this->getBespokeTokens();
84 foreach ($this->getFieldMetadata() as $field) {
85 $this->addFieldToTokenMetadata($field, $this->getExposedFields());
87 foreach ($this->getHiddenTokens() as $name) {
88 $this->tokensMetadata
[$name]['audience'] = 'hidden';
90 Civi
::cache('metadata')->set($cacheKey, $this->tokensMetadata
);
93 return $this->tokensMetadata
;
98 * @throws \CRM_Core_Exception
100 public function evaluateToken(TokenRow
$row, $entity, $field, $prefetch = NULL) {
101 $this->prefetch
= (array) $prefetch;
102 $fieldValue = $this->getFieldValue($row, $field);
103 if (is_array($fieldValue)) {
104 // eg. role_id for participant would be an array here.
105 $fieldValue = implode(',', $fieldValue);
108 if ($this->isPseudoField($field)) {
109 if (!empty($fieldValue)) {
110 // If it's set here it has already been loaded in pre-fetch.
111 return $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
113 // Once prefetch is fully standardised we can remove this - as long
114 // as tests pass we should be fine as tests cover this.
115 $split = explode(':', $field);
116 return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0])));
118 if ($this->isCustomField($field)) {
119 $prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field);
120 if ($prefetchedValue) {
121 return $row->format('text/html')->tokens($entity, $field, $prefetchedValue);
123 return $row->customToken($entity, \CRM_Core_BAO_CustomField
::getKeyID($field), $this->getFieldValue($row, 'id'));
125 if ($this->isMoneyField($field)) {
126 return $row->format('text/plain')->tokens($entity, $field,
127 \CRM_Utils_Money
::format($fieldValue, $this->getCurrency($row)));
129 if ($this->isDateField($field)) {
131 return $row->format('text/plain')
132 ->tokens($entity, $field, ($fieldValue ?
new DateTime($fieldValue) : $fieldValue));
134 catch (Exception
$e) {
135 Civi
::log()->info('invalid date token');
138 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
142 * Metadata about the entity fields.
146 protected $fieldMetadata = [];
149 * Get the entity name for api v4 calls.
153 protected function getApiEntityName(): string {
158 * Get the entity alias to use within queries.
160 * The default has a double underscore which should prevent any
161 * ambiguity with an existing table name.
165 protected function getEntityAlias(): string {
166 return $this->getApiEntityName() . '__';
170 * Get the name of the table this token class can extend.
172 * The default is based on the entity but some token classes,
173 * specifically the event class, latch on to other tables - ie
174 * the participant table.
176 public function getExtendableTableName(): string {
177 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($this->getApiEntityName());
181 * Get an array of fields to be requested.
183 * @todo this function should look up tokenMetadata that
188 protected function getReturnFields(): array {
189 return array_keys($this->getBasicTokens());
193 * Is the given field a boolean field.
195 * @param string $fieldName
199 protected function isBooleanField(string $fieldName): bool {
200 return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
204 * Is the given field a date field.
206 * @param string $fieldName
210 protected function isDateField(string $fieldName): bool {
211 return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
215 * Is the given field a pseudo field.
217 * @param string $fieldName
221 protected function isPseudoField(string $fieldName): bool {
222 return strpos($fieldName, ':') !== FALSE;
226 * Is the given field a custom field.
228 * @param string $fieldName
232 protected function isCustomField(string $fieldName) : bool {
233 return (bool) \CRM_Core_BAO_CustomField
::getKeyID($fieldName);
237 * Is the given field a date field.
239 * @param string $fieldName
243 protected function isMoneyField(string $fieldName): bool {
244 return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
248 * Get the metadata for the available fields.
252 protected function getFieldMetadata(): array {
253 if (empty($this->fieldMetadata
)) {
255 // Tests fail without checkPermissions = FALSE
256 $this->fieldMetadata
= (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name');
258 catch (API_Exception
$e) {
259 $this->fieldMetadata
= [];
262 return $this->fieldMetadata
;
266 * Get any tokens with custom calculation.
268 protected function getBespokeTokens(): array {
273 * Get the value for the relevant pseudo field.
275 * @param string $realField e.g contribution_status_id
276 * @param string $pseudoKey e.g name
277 * @param int|string $fieldValue e.g 1
280 * Eg. 'Completed' in the example above.
282 * @internal function will likely be protected soon.
284 protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
285 $bao = CRM_Core_DAO_AllCoreTables
::getFullName($this->getMetadataForField($realField)['entity']);
286 if ($pseudoKey === 'name') {
287 $fieldValue = (string) CRM_Core_PseudoConstant
::getName($bao, $realField, $fieldValue);
289 if ($pseudoKey === 'label') {
290 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel($bao, $realField, $fieldValue);
292 if ($pseudoKey === 'abbr' && $realField === 'state_province_id') {
293 // hack alert - currently only supported for state.
294 $fieldValue = (string) CRM_Core_PseudoConstant
::stateProvinceAbbreviation($fieldValue);
296 return (string) $fieldValue;
300 * @param \Civi\Token\TokenRow $row
301 * @param string $field
304 protected function getFieldValue(TokenRow
$row, string $field) {
305 $entityName = $this->getEntityName();
306 if (isset($row->context
[$entityName][$field])) {
307 return $row->context
[$entityName][$field];
310 $entityID = $row->context
[$this->getEntityIDField()];
311 if ($field === 'id') {
314 return $this->prefetch
[$entityID][$field] ??
'';
320 public function __construct() {
321 parent
::__construct($this->getEntityName(), []);
325 * Check if the token processor is active.
327 * @param \Civi\Token\TokenProcessor $processor
331 public function checkActive(TokenProcessor
$processor) {
332 return (!empty($processor->context
['actionMapping'])
333 // This makes the 'schema context compulsory - which feels accidental
334 // since recent discu
335 && $processor->context
['actionMapping']->getEntity()) ||
in_array($this->getEntityIDField(), $processor->context
['schema']);
339 * Alter action schedule query.
341 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
343 public function alterActionScheduleQuery(MailingQueryEvent
$e): void
{
344 if ($e->mapping
->getEntity() !== $this->getExtendableTableName()) {
347 $e->query
->select('e.id AS tokenContext_' . $this->getEntityIDField());
351 * Get tokens to be suppressed from the widget.
353 * Note this is expected to be an interim function. Now we are no
354 * longer working around the parent function we can just define them once...
355 * with metadata, in a future refactor.
357 protected function getHiddenTokens(): array {
362 * @todo remove this function & use the metadata that is loaded.
365 * @throws \API_Exception
367 protected function getBasicTokens(): array {
369 foreach ($this->getExposedFields() as $fieldName) {
370 // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
371 // for now to allow us to consider how to handle names vs labels vs values
372 // and other raw vs not raw options.
373 if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') {
374 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
381 * Get entity fields that should be exposed as tokens.
386 protected function getExposedFields(): array {
388 foreach ($this->getFieldMetadata() as $field) {
389 if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) {
390 $return[] = $field['name'];
397 * Get entity fields that should not be exposed as tokens.
401 protected function getSkippedFields(): array {
402 // tags is offered in 'case' & is one of the only fields that is
403 // 'not a real field' offered up by case - seems like an oddity
404 // we should skip at the top level for now.
406 if (!CRM_Campaign_BAO_Campaign
::isCampaignEnable()) {
407 $fields[] = 'campaign_id';
415 protected function getEntityName(): string {
416 return CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($this->getApiEntityName());
419 protected function getEntityIDField(): string {
420 return $this->getEntityName() . 'Id';
423 public function prefetch(TokenValueEvent
$e): ?
array {
424 $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField());
425 if (empty($entityIDs)) {
428 $select = $this->getPrefetchFields($e);
429 $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [
430 'checkPermissions' => FALSE,
431 // Note custom fields are not yet added - I need to
432 // re-do the unit tests to support custom fields first.
434 'where' => [['id', 'IN', $entityIDs]],
439 protected function getCurrencyFieldName() {
444 * Get the currency to use for formatting money.
449 protected function getCurrency($row): string {
450 if (!empty($this->getCurrencyFieldName())) {
451 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
453 return CRM_Core_Config
::singleton()->defaultCurrency
;
457 * Get the fields required to prefetch the entity.
459 * @param \Civi\Token\Event\TokenValueEvent $e
462 * @throws \API_Exception
464 public function getPrefetchFields(TokenValueEvent
$e): array {
465 $allTokens = array_keys($this->getTokenMetadata());
466 $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens);
467 if (empty($requiredFields)) {
470 $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName())));
471 foreach ($this->getDependencies() as $field => $required) {
472 if (in_array($field, $this->getActiveTokens($e), TRUE)) {
473 foreach ((array) $required as $key) {
474 $requiredFields[] = $key;
478 return $requiredFields;
482 * Get fields which need to be returned to render another token.
486 protected function getDependencies(): array {
491 * Get the apiv4 style custom field name.
497 protected function getCustomFieldName(int $id): string {
498 foreach ($this->getTokenMetadata() as $key => $field) {
499 if (($field['custom_field_id'] ??
NULL) === $id) {
507 * @param string $field eg. 'custom_1'
509 * @return array|string|void|null $mixed
511 * @throws \CRM_Core_Exception
513 protected function getCustomFieldValue($entityID, string $field) {
514 $id = str_replace('custom_', '', $field);
515 $value = $this->prefetch
[$entityID][$this->getCustomFieldName($id)] ??
'';
516 if ($value !== NULL) {
517 return CRM_Core_BAO_CustomField
::displayValue($value, $id);
522 * Get the metadata for the field.
524 * @param string $fieldName
528 protected function getMetadataForField($fieldName): array {
529 if (isset($this->getTokenMetadata()[$fieldName])) {
530 return $this->getTokenMetadata()[$fieldName];
532 if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
533 return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
535 return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]];
539 * Get token mappings for related entities - specifically the contact entity.
541 * This function exists to help manage the way contact tokens is structured
542 * of an query-object style result set that needs to be mapped to apiv4.
544 * The end goal is likely to be to advertised tokens that better map to api
545 * v4 and deprecate the existing ones but that is a long-term migration.
549 protected function getTokenMappingsForRelatedEntities(): array {
554 * Get array of deprecated tokens and the new token they map to.
558 protected function getDeprecatedTokens(): array {
563 * Get any overrides for token metadata.
565 * This is most obviously used for setting the audience, which
566 * will affect widget-presence.
568 * @return \string[][]
570 protected function getTokenMetadataOverrides(): array {
575 * To handle variable tokens, override this function and return the active tokens.
577 * @param \Civi\Token\Event\TokenValueEvent $e
581 public function getActiveTokens(TokenValueEvent
$e) {
582 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
583 if (!isset($messageTokens[$this->entity
])) {
586 return array_intersect($messageTokens[$this->entity
], array_keys($this->getTokenMetadata()));
590 * Add the token to the metadata based on the field spec.
592 * @param array $field
593 * @param array $exposedFields
594 * @param string $prefix
596 protected function addFieldToTokenMetadata(array $field, array $exposedFields, string $prefix = ''): void
{
597 if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
600 $field['audience'] = 'user';
601 if ($field['name'] === 'contact_id') {
602 // Since {contact.id} is almost always present don't confuse users
603 // by also adding (e.g {participant.contact_id)
604 $field['audience'] = 'sysadmin';
606 if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
607 $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
609 if ($field['type'] === 'Custom') {
610 // Convert to apiv3 style for now. Later we can add v4 with
611 // portable naming & support for labels/ dates etc so let's leave
612 // the space open for that.
613 // Not the existing quickform widget has handling for the custom field
614 // format based on the title using this syntax.
615 $parts = explode(': ', $field['label']);
616 $field['title'] = "{$parts[1]} :: {$parts[0]}";
617 $tokenName = 'custom_' . $field['custom_field_id'];
618 $this->tokensMetadata
[$tokenName] = $field;
621 $tokenName = $prefix ?
($prefix . '.' . $field['name']) : $field['name'];
622 if (in_array($field['name'], $exposedFields, TRUE)) {
624 ($field['options'] ||
!empty($field['suffixes']))
625 // At the time of writing currency didn't have a label option - this may have changed.
626 && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
628 $this->tokensMetadata
[$tokenName . ':label'] = $this->tokensMetadata
[$tokenName . ':name'] = $field;
629 $fieldLabel = $field['input_attrs']['label'] ??
$field['label'];
630 $this->tokensMetadata
[$tokenName . ':label']['name'] = $field['name'] . ':label';
631 $this->tokensMetadata
[$tokenName . ':name']['name'] = $field['name'] . ':name';
632 $this->tokensMetadata
[$tokenName . ':name']['audience'] = 'sysadmin';
633 $this->tokensMetadata
[$tokenName . ':label']['title'] = $fieldLabel;
634 $this->tokensMetadata
[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
635 $field['audience'] = 'sysadmin';
637 if ($field['data_type'] === 'Boolean') {
638 $this->tokensMetadata
[$tokenName . ':label'] = $field;
639 $this->tokensMetadata
[$tokenName . ':label']['name'] = $field['name'] . ':label';
640 $field['audience'] = 'sysadmin';
642 $this->tokensMetadata
[$tokenName] = $field;
647 * Get a cache key appropriate to the current usage.
651 protected function getCacheKey(): string {
652 $cacheKey = __CLASS__
. 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config
::domainID() . '_' . CRM_Core_I18n
::getLocale();
653 if ($this->checkPermissions
) {
654 $cacheKey .= '__' . CRM_Core_Session
::getLoggedInContactID();