Merge pull request #21681 from MegaphoneJon/core-2881
[civicrm-core.git] / CRM / Core / EntityTokens.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 +--------------------------------------------------------------------+
11 */
12
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
20 /**
21 * Class CRM_Core_EntityTokens
22 *
23 * Parent class for generic entity token functionality.
24 *
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.
29 */
30 class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
31
32 /**
33 * @var array
34 */
35 protected $prefetch = [];
36
37 /**
38 * Register the declared tokens.
39 *
40 * @param \Civi\Token\Event\TokenRegisterEvent $e
41 * The registration event. Add new tokens using register().
42 */
43 public function registerTokens(TokenRegisterEvent $e) {
44 if (!$this->checkActive($e->getTokenProcessor())) {
45 return;
46 }
47 foreach ($this->getAllTokens() as $name => $label) {
48 if (!in_array($name, $this->getHiddenTokens(), TRUE)) {
49 $e->register([
50 'entity' => $this->entity,
51 'field' => $name,
52 'label' => $label,
53 ]);
54 }
55 }
56 }
57
58 /**
59 * @inheritDoc
60 * @throws \CRM_Core_Exception
61 */
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);
68 }
69
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);
74 }
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])));
79 }
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);
84 }
85 return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id'));
86 }
87 if ($this->isMoneyField($field)) {
88 return $row->format('text/plain')->tokens($entity, $field,
89 \CRM_Utils_Money::format($fieldValue, $this->getCurrency($row)));
90 }
91 if ($this->isDateField($field)) {
92 try {
93 return $row->format('text/plain')
94 ->tokens($entity, $field, new DateTime($fieldValue));
95 }
96 catch (Exception $e) {
97 Civi::log()->info('invalid date token');
98 }
99 }
100 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
101 }
102
103 /**
104 * Metadata about the entity fields.
105 *
106 * @var array
107 */
108 protected $fieldMetadata = [];
109
110 /**
111 * Get the entity name for api v4 calls.
112 *
113 * @return string
114 */
115 protected function getApiEntityName(): string {
116 return '';
117 }
118
119 /**
120 * Get the entity alias to use within queries.
121 *
122 * The default has a double underscore which should prevent any
123 * ambiguity with an existing table name.
124 *
125 * @return string
126 */
127 protected function getEntityAlias(): string {
128 return $this->getApiEntityName() . '__';
129 }
130
131 /**
132 * Get the name of the table this token class can extend.
133 *
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.
137 */
138 public function getExtendableTableName(): string {
139 return CRM_Core_DAO_AllCoreTables::getTableForEntityName($this->getApiEntityName());
140 }
141
142 /**
143 * Get the relevant bao name.
144 */
145 public function getBAOName(): string {
146 return CRM_Core_DAO_AllCoreTables::getFullName($this->getApiEntityName());
147 }
148
149 /**
150 * Get an array of fields to be requested.
151 *
152 * @return string[]
153 */
154 public function getReturnFields(): array {
155 return array_keys($this->getBasicTokens());
156 }
157
158 /**
159 * Get all the tokens supported by this processor.
160 *
161 * @return array|string[]
162 * @throws \API_Exception
163 */
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]);
175 }
176 }
177 return array_merge($basicTokens, $this->getPseudoTokens(), $this->getBespokeTokens(), CRM_Utils_Token::getCustomFieldTokens($this->getApiEntityName()));
178 }
179
180 /**
181 * Is the given field a boolean field.
182 *
183 * @param string $fieldName
184 *
185 * @return bool
186 */
187 public function isBooleanField(string $fieldName): bool {
188 return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Boolean';
189 }
190
191 /**
192 * Is the given field a date field.
193 *
194 * @param string $fieldName
195 *
196 * @return bool
197 */
198 public function isDateField(string $fieldName): bool {
199 return in_array($this->getFieldMetadata()[$fieldName]['data_type'], ['Timestamp', 'Date'], TRUE);
200 }
201
202 /**
203 * Is the given field a pseudo field.
204 *
205 * @param string $fieldName
206 *
207 * @return bool
208 */
209 public function isPseudoField(string $fieldName): bool {
210 return strpos($fieldName, ':') !== FALSE;
211 }
212
213 /**
214 * Is the given field a custom field.
215 *
216 * @param string $fieldName
217 *
218 * @return bool
219 */
220 public function isCustomField(string $fieldName) : bool {
221 return (bool) \CRM_Core_BAO_CustomField::getKeyID($fieldName);
222 }
223
224 /**
225 * Is the given field a date field.
226 *
227 * @param string $fieldName
228 *
229 * @return bool
230 */
231 public function isMoneyField(string $fieldName): bool {
232 return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Money';
233 }
234
235 /**
236 * Get the metadata for the available fields.
237 *
238 * @return array
239 */
240 protected function getFieldMetadata(): array {
241 if (empty($this->fieldMetadata)) {
242 try {
243 // Tests fail without checkPermissions = FALSE
244 $this->fieldMetadata = (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name');
245 }
246 catch (API_Exception $e) {
247 $this->fieldMetadata = [];
248 }
249 }
250 return $this->fieldMetadata;
251 }
252
253 /**
254 * Get pseudoTokens - it tokens that reflect the name or label of a pseudoconstant.
255 *
256 * @internal - this function will likely be made protected soon.
257 *
258 * @return array
259 */
260 public function getPseudoTokens(): array {
261 $return = [];
262 foreach (array_keys($this->getBasicTokens()) as $fieldName) {
263 if ($this->isAddPseudoTokens($fieldName)) {
264 $fieldLabel = $this->fieldMetadata[$fieldName]['input_attrs']['label'] ?? $this->fieldMetadata[$fieldName]['label'];
265 $return[$fieldName . ':label'] = $fieldLabel;
266 $return[$fieldName . ':name'] = ts('Machine name') . ': ' . $fieldLabel;
267 }
268 if ($this->isBooleanField($fieldName)) {
269 $return[$fieldName . ':label'] = $this->getFieldMetadata()[$fieldName]['title'];
270 }
271 }
272 return $return;
273 }
274
275 /**
276 * Get any tokens with custom calculation.
277 */
278 public function getBespokeTokens(): array {
279 return [];
280 }
281
282 /**
283 * Is this a field we should add pseudo-tokens to?
284 *
285 * Pseudo-tokens allow access to name and label fields - e.g
286 *
287 * {contribution.contribution_status_id:name} might resolve to 'Completed'
288 *
289 * @param string $fieldName
290 */
291 public function isAddPseudoTokens($fieldName): bool {
292 if (in_array($fieldName, $this->getCurrencyFieldName())) {
293 // 'currency' is manually added to the skip list as an anomaly.
294 // name & label aren't that suitable for 'currency' (symbol, which
295 // possibly maps to 'abbr' would be) and we can't gather that
296 // from the metadata as yet.
297 return FALSE;
298 }
299 if ($this->getFieldMetadata()[$fieldName]['type'] === 'Custom') {
300 // If we remove this early return then we get that extra nuanced goodness
301 // and support for the more portable v4 style field names
302 // on custom fields - where labels or names can be returned.
303 // At present the gap is that the metadata for the label is not accessed
304 // and tests failed on the enotice and we don't have a clear plan about
305 // v4 style custom tokens - but medium term this IF will probably go.
306 return FALSE;
307 }
308 return (bool) ($this->getFieldMetadata()[$fieldName]['options'] || !empty($this->getFieldMetadata()[$fieldName]['suffixes']));
309 }
310
311 /**
312 * Get the value for the relevant pseudo field.
313 *
314 * @param string $realField e.g contribution_status_id
315 * @param string $pseudoKey e.g name
316 * @param int|string $fieldValue e.g 1
317 *
318 * @return string
319 * Eg. 'Completed' in the example above.
320 *
321 * @internal function will likely be protected soon.
322 */
323 public function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
324 if ($pseudoKey === 'name') {
325 $fieldValue = (string) CRM_Core_PseudoConstant::getName($this->getBAOName(), $realField, $fieldValue);
326 }
327 if ($pseudoKey === 'label') {
328 $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($this->getBAOName(), $realField, $fieldValue);
329 }
330 return (string) $fieldValue;
331 }
332
333 /**
334 * @param \Civi\Token\TokenRow $row
335 * @param string $field
336 * @return string|int
337 */
338 protected function getFieldValue(TokenRow $row, string $field) {
339 $entityName = $this->getEntityName();
340 if (isset($row->context[$entityName][$field])) {
341 return $row->context[$entityName][$field];
342 }
343
344 $actionSearchResult = $row->context['actionSearchResult'];
345 $aliasedField = $this->getEntityAlias() . $field;
346 if (isset($actionSearchResult->{$aliasedField})) {
347 return $actionSearchResult->{$aliasedField};
348 }
349 $entityID = $row->context[$this->getEntityIDField()];
350 if ($field === 'id') {
351 return $entityID;
352 }
353 return $this->prefetch[$entityID][$field] ?? '';
354 }
355
356 /**
357 * Class constructor.
358 */
359 public function __construct() {
360 $tokens = $this->getAllTokens();
361 parent::__construct($this->getEntityName(), $tokens);
362 }
363
364 /**
365 * Check if the token processor is active.
366 *
367 * @param \Civi\Token\TokenProcessor $processor
368 *
369 * @return bool
370 */
371 public function checkActive(TokenProcessor $processor) {
372 return (!empty($processor->context['actionMapping'])
373 // This makes the 'schema context compulsory - which feels accidental
374 // since recent discu
375 && $processor->context['actionMapping']->getEntity()) || in_array($this->getEntityIDField(), $processor->context['schema']);
376 }
377
378 /**
379 * Alter action schedule query.
380 *
381 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
382 */
383 public function alterActionScheduleQuery(MailingQueryEvent $e): void {
384 if ($e->mapping->getEntity() !== $this->getExtendableTableName()) {
385 return;
386 }
387 foreach ($this->getReturnFields() as $token) {
388 $e->query->select('e.' . $token . ' AS ' . $this->getEntityAlias() . $token);
389 }
390 }
391
392 /**
393 * Get tokens to be suppressed from the widget.
394 *
395 * Note this is expected to be an interim function. Now we are no
396 * longer working around the parent function we can just define them once...
397 * with metadata, in a future refactor.
398 */
399 protected function getHiddenTokens(): array {
400 return [];
401 }
402
403 /**
404 * Get tokens supporting the syntax we are migrating to.
405 *
406 * In general these are tokens that were not previously supported
407 * so we can add them in the preferred way or that we have
408 * undertaken some, as yet to be written, db update.
409 *
410 * See https://lab.civicrm.org/dev/core/-/issues/2650
411 *
412 * @return string[]
413 * @throws \API_Exception
414 */
415 public function getBasicTokens(): array {
416 $return = [];
417 foreach ($this->getExposedFields() as $fieldName) {
418 // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
419 // for now to allow us to consider how to handle names vs labels vs values
420 // and other raw vs not raw options.
421 if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') {
422 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
423 }
424 }
425 return $return;
426 }
427
428 /**
429 * Get entity fields that should be exposed as tokens.
430 *
431 * @return string[]
432 *
433 */
434 public function getExposedFields(): array {
435 $return = [];
436 foreach ($this->getFieldMetadata() as $field) {
437 if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) {
438 $return[] = $field['name'];
439 }
440 }
441 return $return;
442 }
443
444 /**
445 * Get entity fields that should not be exposed as tokens.
446 *
447 * @return string[]
448 */
449 public function getSkippedFields(): array {
450 // tags is offered in 'case' & is one of the only fields that is
451 // 'not a real field' offered up by case - seems like an oddity
452 // we should skip at the top level for now.
453 $fields = ['contact_id', 'tags'];
454 if (!CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
455 $fields[] = 'campaign_id';
456 }
457 return $fields;
458 }
459
460 /**
461 * @return string
462 */
463 protected function getEntityName(): string {
464 return CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($this->getApiEntityName());
465 }
466
467 public function getEntityIDField(): string {
468 return $this->getEntityName() . 'Id';
469 }
470
471 public function prefetch(TokenValueEvent $e): ?array {
472 $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField());
473 if (empty($entityIDs)) {
474 return [];
475 }
476 $select = $this->getPrefetchFields($e);
477 $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [
478 'checkPermissions' => FALSE,
479 // Note custom fields are not yet added - I need to
480 // re-do the unit tests to support custom fields first.
481 'select' => $select,
482 'where' => [['id', 'IN', $entityIDs]],
483 ], 'id');
484 return $result;
485 }
486
487 public function getCurrencyFieldName() {
488 return [];
489 }
490
491 /**
492 * Get the currency to use for formatting money.
493 * @param $row
494 *
495 * @return string
496 */
497 public function getCurrency($row): string {
498 if (!empty($this->getCurrencyFieldName())) {
499 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
500 }
501 return CRM_Core_Config::singleton()->defaultCurrency;
502 }
503
504 /**
505 * Get the fields required to prefetch the entity.
506 *
507 * @param \Civi\Token\Event\TokenValueEvent $e
508 *
509 * @return array
510 * @throws \API_Exception
511 */
512 public function getPrefetchFields(TokenValueEvent $e): array {
513 $allTokens = array_keys($this->getAllTokens());
514 $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens);
515 if (empty($requiredFields)) {
516 return [];
517 }
518 $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName())));
519 foreach ($this->getDependencies() as $field => $required) {
520 if (in_array($field, $this->getActiveTokens($e), TRUE)) {
521 foreach ((array) $required as $key) {
522 $requiredFields[] = $key;
523 }
524 }
525 }
526 return $requiredFields;
527 }
528
529 /**
530 * Get fields which need to be returned to render another token.
531 *
532 * @return array
533 */
534 public function getDependencies(): array {
535 return [];
536 }
537
538 /**
539 * Get the apiv4 style custom field name.
540 *
541 * @param int $id
542 *
543 * @return string
544 */
545 protected function getCustomFieldName(int $id): string {
546 foreach ($this->getFieldMetadata() as $key => $field) {
547 if (($field['custom_field_id'] ?? NULL) === $id) {
548 return $key;
549 }
550 }
551 }
552
553 /**
554 * @param $entityID
555 * @param string $field eg. 'custom_1'
556 *
557 * @return array|string|void|null $mixed
558 *
559 * @throws \CRM_Core_Exception
560 */
561 protected function getCustomFieldValue($entityID, string $field) {
562 $id = str_replace('custom_', '', $field);
563 $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? NULL;
564 if ($value !== NULL) {
565 return CRM_Core_BAO_CustomField::displayValue($value, $id);
566 }
567 }
568
569 }