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
{
35 protected $prefetch = [];
38 * Register the declared tokens.
40 * @param \Civi\Token\Event\TokenRegisterEvent $e
41 * The registration event. Add new tokens using register().
43 public function registerTokens(TokenRegisterEvent
$e) {
44 if (!$this->checkActive($e->getTokenProcessor())) {
47 foreach ($this->getAllTokens() as $name => $label) {
48 if (!in_array($name, $this->getHiddenTokens(), TRUE)) {
50 'entity' => $this->entity
,
60 * @throws \CRM_Core_Exception
62 public function evaluateToken(TokenRow
$row, $entity, $field, $prefetch = NULL) {
63 $this->prefetch
= (array) $prefetch;
64 $fieldValue = $this->getFieldValue($row, $field);
65 if (is_array($fieldValue)) {
66 // eg. role_id for participant would be an array here.
67 $fieldValue = implode(',', $fieldValue);
70 if ($this->isPseudoField($field)) {
71 if (!empty($fieldValue)) {
72 // If it's set here it has already been loaded in pre-fetch.
73 return $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
75 // Once prefetch is fully standardised we can remove this - as long
76 // as tests pass we should be fine as tests cover this.
77 $split = explode(':', $field);
78 return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0])));
80 if ($this->isCustomField($field)) {
81 $prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field);
82 if ($prefetchedValue) {
83 return $row->format('text/html')->tokens($entity, $field, $prefetchedValue);
85 return $row->customToken($entity, \CRM_Core_BAO_CustomField
::getKeyID($field), $this->getFieldValue($row, 'id'));
87 if ($this->isMoneyField($field)) {
88 return $row->format('text/plain')->tokens($entity, $field,
89 \CRM_Utils_Money
::format($fieldValue, $this->getCurrency($row)));
91 if ($this->isDateField($field)) {
93 return $row->format('text/plain')
94 ->tokens($entity, $field, new DateTime($fieldValue));
96 catch (Exception
$e) {
97 Civi
::log()->info('invalid date token');
100 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
104 * Metadata about the entity fields.
108 protected $fieldMetadata = [];
111 * Get the entity name for api v4 calls.
115 protected function getApiEntityName(): string {
120 * Get the entity alias to use within queries.
122 * The default has a double underscore which should prevent any
123 * ambiguity with an existing table name.
127 protected function getEntityAlias(): string {
128 return $this->getApiEntityName() . '__';
132 * Get the name of the table this token class can extend.
134 * The default is based on the entity but some token classes,
135 * specifically the event class, latch on to other tables - ie
136 * the participant table.
138 public function getExtendableTableName(): string {
139 return CRM_Core_DAO_AllCoreTables
::getTableForEntityName($this->getApiEntityName());
143 * Get the relevant bao name.
145 public function getBAOName(): string {
146 return CRM_Core_DAO_AllCoreTables
::getFullName($this->getApiEntityName());
150 * Get an array of fields to be requested.
154 public function getReturnFields(): array {
155 return array_keys($this->getBasicTokens());
159 * Get all the tokens supported by this processor.
161 * @return array|string[]
162 * @throws \API_Exception
164 protected function getAllTokens(): array {
165 $basicTokens = $this->getBasicTokens();
166 foreach (array_keys($basicTokens) as $fieldName) {
167 // The goal is to be able to render more complete tokens
168 // (eg. actual booleans, field names, raw ids) for a more
169 // advanced audiences - ie those using conditionals
170 // and to specify that audience in the api that retrieves.
171 // But, for now, let's not advertise, given that most of these fields
172 // aren't really needed even once...
173 if ($this->isBooleanField($fieldName)) {
174 unset($basicTokens[$fieldName]);
177 foreach ($this->getBespokeTokens() as $token) {
178 $basicTokens[$token['name']] = $token['title'];
180 return array_merge($basicTokens, $this->getPseudoTokens(), CRM_Utils_Token
::getCustomFieldTokens($this->getApiEntityName()));
184 * Is the given field a boolean field.
186 * @param string $fieldName
190 public function isBooleanField(string $fieldName): bool {
191 return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Boolean';
195 * Is the given field a date field.
197 * @param string $fieldName
201 public function isDateField(string $fieldName): bool {
202 return in_array($this->getFieldMetadata()[$fieldName]['data_type'], ['Timestamp', 'Date'], TRUE);
206 * Is the given field a pseudo field.
208 * @param string $fieldName
212 public function isPseudoField(string $fieldName): bool {
213 return strpos($fieldName, ':') !== FALSE;
217 * Is the given field a custom field.
219 * @param string $fieldName
223 public function isCustomField(string $fieldName) : bool {
224 return (bool) \CRM_Core_BAO_CustomField
::getKeyID($fieldName);
228 * Is the given field a date field.
230 * @param string $fieldName
234 public function isMoneyField(string $fieldName): bool {
235 return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Money';
239 * Get the metadata for the available fields.
243 protected function getFieldMetadata(): array {
244 if (empty($this->fieldMetadata
)) {
246 // Tests fail without checkPermissions = FALSE
247 $this->fieldMetadata
= (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name');
249 catch (API_Exception
$e) {
250 $this->fieldMetadata
= [];
253 return $this->fieldMetadata
;
257 * Get pseudoTokens - it tokens that reflect the name or label of a pseudoconstant.
259 * @internal - this function will likely be made protected soon.
263 public function getPseudoTokens(): array {
265 foreach (array_keys($this->getBasicTokens()) as $fieldName) {
266 if ($this->isAddPseudoTokens($fieldName)) {
267 $fieldLabel = $this->fieldMetadata
[$fieldName]['input_attrs']['label'] ??
$this->fieldMetadata
[$fieldName]['label'];
268 $return[$fieldName . ':label'] = $fieldLabel;
269 $return[$fieldName . ':name'] = ts('Machine name') . ': ' . $fieldLabel;
271 if ($this->isBooleanField($fieldName)) {
272 $return[$fieldName . ':label'] = $this->getFieldMetadata()[$fieldName]['title'];
279 * Get any tokens with custom calculation.
281 protected function getBespokeTokens(): array {
286 * Is this a field we should add pseudo-tokens to?
288 * Pseudo-tokens allow access to name and label fields - e.g
290 * {contribution.contribution_status_id:name} might resolve to 'Completed'
292 * @param string $fieldName
294 public function isAddPseudoTokens($fieldName): bool {
295 if (in_array($fieldName, $this->getCurrencyFieldName())) {
296 // 'currency' is manually added to the skip list as an anomaly.
297 // name & label aren't that suitable for 'currency' (symbol, which
298 // possibly maps to 'abbr' would be) and we can't gather that
299 // from the metadata as yet.
302 if ($this->getFieldMetadata()[$fieldName]['type'] === 'Custom') {
303 // If we remove this early return then we get that extra nuanced goodness
304 // and support for the more portable v4 style field names
305 // on custom fields - where labels or names can be returned.
306 // At present the gap is that the metadata for the label is not accessed
307 // and tests failed on the enotice and we don't have a clear plan about
308 // v4 style custom tokens - but medium term this IF will probably go.
311 return (bool) ($this->getFieldMetadata()[$fieldName]['options'] ||
!empty($this->getFieldMetadata()[$fieldName]['suffixes']));
315 * Get the value for the relevant pseudo field.
317 * @param string $realField e.g contribution_status_id
318 * @param string $pseudoKey e.g name
319 * @param int|string $fieldValue e.g 1
322 * Eg. 'Completed' in the example above.
324 * @internal function will likely be protected soon.
326 public function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
327 if ($pseudoKey === 'name') {
328 $fieldValue = (string) CRM_Core_PseudoConstant
::getName($this->getBAOName(), $realField, $fieldValue);
330 if ($pseudoKey === 'label') {
331 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel($this->getBAOName(), $realField, $fieldValue);
333 return (string) $fieldValue;
337 * @param \Civi\Token\TokenRow $row
338 * @param string $field
341 protected function getFieldValue(TokenRow
$row, string $field) {
342 $entityName = $this->getEntityName();
343 if (isset($row->context
[$entityName][$field])) {
344 return $row->context
[$entityName][$field];
347 $actionSearchResult = $row->context
['actionSearchResult'];
348 $aliasedField = $this->getEntityAlias() . $field;
349 if (isset($actionSearchResult->{$aliasedField})) {
350 return $actionSearchResult->{$aliasedField};
352 $entityID = $row->context
[$this->getEntityIDField()];
353 if ($field === 'id') {
356 return $this->prefetch
[$entityID][$field] ??
'';
362 public function __construct() {
363 $tokens = $this->getAllTokens();
364 parent
::__construct($this->getEntityName(), $tokens);
368 * Check if the token processor is active.
370 * @param \Civi\Token\TokenProcessor $processor
374 public function checkActive(TokenProcessor
$processor) {
375 return (!empty($processor->context
['actionMapping'])
376 // This makes the 'schema context compulsory - which feels accidental
377 // since recent discu
378 && $processor->context
['actionMapping']->getEntity()) ||
in_array($this->getEntityIDField(), $processor->context
['schema']);
382 * Alter action schedule query.
384 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
386 public function alterActionScheduleQuery(MailingQueryEvent
$e): void
{
387 if ($e->mapping
->getEntity() !== $this->getExtendableTableName()) {
390 foreach ($this->getReturnFields() as $token) {
391 $e->query
->select('e.' . $token . ' AS ' . $this->getEntityAlias() . $token);
396 * Get tokens to be suppressed from the widget.
398 * Note this is expected to be an interim function. Now we are no
399 * longer working around the parent function we can just define them once...
400 * with metadata, in a future refactor.
402 protected function getHiddenTokens(): array {
407 * Get tokens supporting the syntax we are migrating to.
409 * In general these are tokens that were not previously supported
410 * so we can add them in the preferred way or that we have
411 * undertaken some, as yet to be written, db update.
413 * See https://lab.civicrm.org/dev/core/-/issues/2650
416 * @throws \API_Exception
418 public function getBasicTokens(): array {
420 foreach ($this->getExposedFields() as $fieldName) {
421 // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
422 // for now to allow us to consider how to handle names vs labels vs values
423 // and other raw vs not raw options.
424 if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') {
425 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
432 * Get entity fields that should be exposed as tokens.
437 protected function getExposedFields(): array {
439 foreach ($this->getFieldMetadata() as $field) {
440 if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) {
441 $return[] = $field['name'];
448 * Get entity fields that should not be exposed as tokens.
452 public function getSkippedFields(): array {
453 // tags is offered in 'case' & is one of the only fields that is
454 // 'not a real field' offered up by case - seems like an oddity
455 // we should skip at the top level for now.
456 $fields = ['contact_id', 'tags'];
457 if (!CRM_Campaign_BAO_Campaign
::isCampaignEnable()) {
458 $fields[] = 'campaign_id';
466 protected function getEntityName(): string {
467 return CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($this->getApiEntityName());
470 public function getEntityIDField(): string {
471 return $this->getEntityName() . 'Id';
474 public function prefetch(TokenValueEvent
$e): ?
array {
475 $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField());
476 if (empty($entityIDs)) {
479 $select = $this->getPrefetchFields($e);
480 $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [
481 'checkPermissions' => FALSE,
482 // Note custom fields are not yet added - I need to
483 // re-do the unit tests to support custom fields first.
485 'where' => [['id', 'IN', $entityIDs]],
490 public function getCurrencyFieldName() {
495 * Get the currency to use for formatting money.
500 public function getCurrency($row): string {
501 if (!empty($this->getCurrencyFieldName())) {
502 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
504 return CRM_Core_Config
::singleton()->defaultCurrency
;
508 * Get the fields required to prefetch the entity.
510 * @param \Civi\Token\Event\TokenValueEvent $e
513 * @throws \API_Exception
515 public function getPrefetchFields(TokenValueEvent
$e): array {
516 $allTokens = array_keys($this->getAllTokens());
517 $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens);
518 if (empty($requiredFields)) {
521 $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName())));
522 foreach ($this->getDependencies() as $field => $required) {
523 if (in_array($field, $this->getActiveTokens($e), TRUE)) {
524 foreach ((array) $required as $key) {
525 $requiredFields[] = $key;
529 return $requiredFields;
533 * Get fields which need to be returned to render another token.
537 public function getDependencies(): array {
542 * Get the apiv4 style custom field name.
548 protected function getCustomFieldName(int $id): string {
549 foreach ($this->getFieldMetadata() as $key => $field) {
550 if (($field['custom_field_id'] ??
NULL) === $id) {
558 * @param string $field eg. 'custom_1'
560 * @return array|string|void|null $mixed
562 * @throws \CRM_Core_Exception
564 protected function getCustomFieldValue($entityID, string $field) {
565 $id = str_replace('custom_', '', $field);
566 $value = $this->prefetch
[$entityID][$this->getCustomFieldName($id)] ??
NULL;
567 if ($value !== NULL) {
568 return CRM_Core_BAO_CustomField
::displayValue($value, $id);