Merge pull request #23742 from eileenmcnaughton/import_remove
[civicrm-core.git] / CRM / Core / EntityTokens.php
index 5514b6dc032a7cff5ed4ed736d9b75ef5dd00b4a..8f7866971b5a5230c43acc062d5b08bea1896aa5 100644 (file)
@@ -16,6 +16,7 @@ use Civi\Token\Event\TokenValueEvent;
 use Civi\Token\TokenRow;
 use Civi\ActionSchedule\Event\MailingQueryEvent;
 use Civi\Token\TokenProcessor;
+use Brick\Money\Money;
 
 /**
  * Class CRM_Core_EntityTokens
@@ -57,11 +58,11 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     if (!$this->checkActive($e->getTokenProcessor())) {
       return;
     }
-    foreach ($this->getTokenMetadata() as $field) {
+    foreach ($this->getTokenMetadata() as $tokenName => $field) {
       if ($field['audience'] === 'user') {
         $e->register([
           'entity' => $this->entity,
-          'field' => $field['name'],
+          'field' => $tokenName,
           'label' => $field['title'],
         ]);
       }
@@ -74,69 +75,18 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    * @return array
    */
   protected function getTokenMetadata(): array {
-    if (empty($this->tokensMetadata)) {
-      $cacheKey = __CLASS__ . 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config::domainID() . '_' . CRM_Core_I18n::getLocale();
-      if ($this->checkPermissions) {
-        $cacheKey .= '__' . CRM_Core_Session::getLoggedInContactID();
+    $cacheKey = $this->getCacheKey();
+    if (!Civi::cache('metadata')->has($cacheKey)) {
+      $tokensMetadata = $this->getBespokeTokens();
+      foreach ($this->getFieldMetadata() as $field) {
+        $this->addFieldToTokenMetadata($tokensMetadata, $field, $this->getExposedFields());
       }
-      if (Civi::cache('metadata')->has($cacheKey)) {
-        $this->tokensMetadata = Civi::cache('metadata')->get($cacheKey);
-      }
-      else {
-        foreach (array_merge($this->getFieldMetadata(), $this->getBespokeTokens()) as $field) {
-          if (
-            $field['type'] === 'Custom'
-            || !empty($this->getBespokeTokens()[$field['name']])
-            || in_array($field['name'], $this->getExposedFields(), TRUE)
-          ) {
-            $field['audience'] = 'user';
-            if ($field['name'] === 'contact_id') {
-              // Since {contact.id} is almost always present don't confuse users
-              // by also adding (e.g {participant.contact_id)
-              $field['audience'] = 'sysadmin';
-            }
-            if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
-              $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
-            }
-            if ($field['type'] === 'Custom') {
-              // Convert to apiv3 style for now. Later we can add v4 with
-              // portable naming & support for labels/ dates etc so let's leave
-              // the space open for that.
-              // Not the existing quickform widget has handling for the custom field
-              // format based on the title using this syntax.
-              $field['name'] = 'custom_' . $field['custom_field_id'];
-              $parts = explode(': ', $field['label']);
-              $field['title'] = "{$parts[1]} :: {$parts[0]}";
-            }
-            if (
-              ($field['options'] || !empty($field['suffixes']))
-              // At the time of writing currency didn't have a label option - this may have changed.
-              && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
-            ) {
-              $this->tokensMetadata[$field['name'] . ':label'] = $this->tokensMetadata[$field['name'] . ':name'] = $field;
-              $fieldLabel = $field['input_attrs']['label'] ?? $field['label'];
-              $this->tokensMetadata[$field['name'] . ':label']['name'] = $field['name'] . ':label';
-              $this->tokensMetadata[$field['name'] . ':name']['name'] = $field['name'] . ':name';
-              $this->tokensMetadata[$field['name'] . ':name']['audience'] = 'sysadmin';
-              $this->tokensMetadata[$field['name'] . ':label']['title'] = $fieldLabel;
-              $this->tokensMetadata[$field['name'] . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
-              $field['audience'] = 'sysadmin';
-            }
-            if ($field['data_type'] === 'Boolean') {
-              $this->tokensMetadata[$field['name'] . ':label'] = $field;
-              $this->tokensMetadata[$field['name'] . ':label']['name'] = $field['name'] . ':label';
-              $field['audience'] = 'sysadmin';
-            }
-            $this->tokensMetadata[$field['name']] = $field;
-          }
-        }
-        foreach ($this->getHiddenTokens() as $name) {
-          $this->tokensMetadata[$name]['audience'] = 'hidden';
-        }
-        Civi::cache('metadata')->set($cacheKey, $this->tokensMetadata);
+      foreach ($this->getHiddenTokens() as $name) {
+        $tokensMetadata[$name]['audience'] = 'hidden';
       }
+      Civi::cache('metadata')->set($cacheKey, $tokensMetadata);
     }
-    return $this->tokensMetadata;
+    return Civi::cache('metadata')->get($cacheKey);
   }
 
   /**
@@ -169,8 +119,18 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
       return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id'));
     }
     if ($this->isMoneyField($field)) {
+      $currency = $this->getCurrency($row);
+      if (empty($fieldValue) && !is_numeric($fieldValue)) {
+        $fieldValue = 0;
+      }
+      if (!$currency) {
+        // too hard basket for now - just do what we always did.
+        return $row->format('text/plain')->tokens($entity, $field,
+          \CRM_Utils_Money::format($fieldValue, $currency));
+      }
       return $row->format('text/plain')->tokens($entity, $field,
-        \CRM_Utils_Money::format($fieldValue, $this->getCurrency($row)));
+        Money::of($fieldValue, $currency));
+
     }
     if ($this->isDateField($field)) {
       try {
@@ -223,19 +183,15 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     return CRM_Core_DAO_AllCoreTables::getTableForEntityName($this->getApiEntityName());
   }
 
-  /**
-   * Get the relevant bao name.
-   */
-  public function getBAOName(): string {
-    return CRM_Core_DAO_AllCoreTables::getFullName($this->getApiEntityName());
-  }
-
   /**
    * Get an array of fields to be requested.
    *
+   * @todo this function should look up tokenMetadata that
+   * is already loaded.
+   *
    * @return string[]
    */
-  public function getReturnFields(): array {
+  protected function getReturnFields(): array {
     return array_keys($this->getBasicTokens());
   }
 
@@ -246,8 +202,8 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return bool
    */
-  public function isBooleanField(string $fieldName): bool {
-    return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Boolean';
+  protected function isBooleanField(string $fieldName): bool {
+    return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
   }
 
   /**
@@ -257,8 +213,8 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return bool
    */
-  public function isDateField(string $fieldName): bool {
-    return in_array($this->getFieldMetadata()[$fieldName]['data_type'], ['Timestamp', 'Date'], TRUE);
+  protected function isDateField(string $fieldName): bool {
+    return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
   }
 
   /**
@@ -268,7 +224,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return bool
    */
-  public function isPseudoField(string $fieldName): bool {
+  protected function isPseudoField(string $fieldName): bool {
     return strpos($fieldName, ':') !== FALSE;
   }
 
@@ -279,7 +235,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return bool
    */
-  public function isCustomField(string $fieldName) : bool {
+  protected function isCustomField(string $fieldName) : bool {
     return (bool) \CRM_Core_BAO_CustomField::getKeyID($fieldName);
   }
 
@@ -290,8 +246,8 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return bool
    */
-  public function isMoneyField(string $fieldName): bool {
-    return $this->getFieldMetadata()[$fieldName]['data_type'] === 'Money';
+  protected function isMoneyField(string $fieldName): bool {
+    return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
   }
 
   /**
@@ -332,11 +288,16 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    * @internal function will likely be protected soon.
    */
   protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
+    $bao = CRM_Core_DAO_AllCoreTables::getFullName($this->getMetadataForField($realField)['entity']);
     if ($pseudoKey === 'name') {
-      $fieldValue = (string) CRM_Core_PseudoConstant::getName($this->getBAOName(), $realField, $fieldValue);
+      $fieldValue = (string) CRM_Core_PseudoConstant::getName($bao, $realField, $fieldValue);
     }
     if ($pseudoKey === 'label') {
-      $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($this->getBAOName(), $realField, $fieldValue);
+      $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($bao, $realField, $fieldValue);
+    }
+    if ($pseudoKey === 'abbr' && $realField === 'state_province_id') {
+      // hack alert - currently only supported for state.
+      $fieldValue = (string) CRM_Core_PseudoConstant::stateProvinceAbbreviation($fieldValue);
     }
     return (string) $fieldValue;
   }
@@ -352,11 +313,6 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
       return $row->context[$entityName][$field];
     }
 
-    $actionSearchResult = $row->context['actionSearchResult'];
-    $aliasedField = $this->getEntityAlias() . $field;
-    if (isset($actionSearchResult->{$aliasedField})) {
-      return $actionSearchResult->{$aliasedField};
-    }
     $entityID = $row->context[$this->getEntityIDField()];
     if ($field === 'id') {
       return $entityID;
@@ -394,9 +350,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     if ($e->mapping->getEntity() !== $this->getExtendableTableName()) {
       return;
     }
-    foreach ($this->getReturnFields() as $token) {
-      $e->query->select('e.' . $token . ' AS ' . $this->getEntityAlias() . $token);
-    }
+    $e->query->select('e.id AS tokenContext_' . $this->getEntityIDField());
   }
 
   /**
@@ -411,18 +365,12 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
   }
 
   /**
-   * Get tokens supporting the syntax we are migrating to.
-   *
-   * In general these are tokens that were not previously supported
-   * so we can add them in the preferred way or that we have
-   * undertaken some, as yet to be written, db update.
-   *
-   * See https://lab.civicrm.org/dev/core/-/issues/2650
+   * @todo remove this function & use the metadata that is loaded.
    *
    * @return string[]
    * @throws \API_Exception
    */
-  public function getBasicTokens(): array {
+  protected function getBasicTokens(): array {
     $return = [];
     foreach ($this->getExposedFields() as $fieldName) {
       // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
@@ -474,7 +422,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     return CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($this->getApiEntityName());
   }
 
-  public function getEntityIDField(): string {
+  protected function getEntityIDField(): string {
     return $this->getEntityName() . 'Id';
   }
 
@@ -494,7 +442,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     return $result;
   }
 
-  public function getCurrencyFieldName() {
+  protected function getCurrencyFieldName() {
     return [];
   }
 
@@ -504,7 +452,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return string
    */
-  public function getCurrency($row): string {
+  protected function getCurrency($row): string {
     if (!empty($this->getCurrencyFieldName())) {
       return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
     }
@@ -541,7 +489,7 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    *
    * @return array
    */
-  public function getDependencies(): array {
+  protected function getDependencies(): array {
     return [];
   }
 
@@ -551,13 +499,18 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    * @param int $id
    *
    * @return string
+   *
+   * @throws \CRM_Core_Exception
    */
   protected function getCustomFieldName(int $id): string {
-    foreach ($this->getFieldMetadata() as $key => $field) {
+    foreach ($this->getTokenMetadata() as $key => $field) {
       if (($field['custom_field_id'] ?? NULL) === $id) {
         return $key;
       }
     }
+    throw new CRM_Core_Exception(
+      "A custom field with the ID {$id} does not exist"
+    );
   }
 
   /**
@@ -570,12 +523,58 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
    */
   protected function getCustomFieldValue($entityID, string $field) {
     $id = str_replace('custom_', '', $field);
-    $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? NULL;
-    if ($value !== NULL) {
-      return CRM_Core_BAO_CustomField::displayValue($value, $id);
+    try {
+      $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? '';
+      if ($value !== NULL) {
+        return CRM_Core_BAO_CustomField::displayValue($value, $id);
+      }
+    }
+    catch (CRM_Core_Exception $exception) {
+      return NULL;
     }
   }
 
+  /**
+   * Get the metadata for the field.
+   *
+   * @param string $fieldName
+   *
+   * @return array
+   */
+  protected function getMetadataForField($fieldName): array {
+    if (isset($this->getTokenMetadata()[$fieldName])) {
+      return $this->getTokenMetadata()[$fieldName];
+    }
+    if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
+      return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
+    }
+    return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ?? [];
+  }
+
+  /**
+   * Get token mappings for related entities - specifically the contact entity.
+   *
+   * This function exists to help manage the way contact tokens is structured
+   * of an query-object style result set that needs to be mapped to apiv4.
+   *
+   * The end goal is likely to be to advertised tokens that better map to api
+   * v4 and deprecate the existing ones but that is a long-term migration.
+   *
+   * @return array
+   */
+  protected function getTokenMappingsForRelatedEntities(): array {
+    return [];
+  }
+
+  /**
+   * Get array of deprecated tokens and the new token they map to.
+   *
+   * @return array
+   */
+  protected function getDeprecatedTokens(): array {
+    return [];
+  }
+
   /**
    * Get any overrides for token metadata.
    *
@@ -603,4 +602,75 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
     return array_intersect($messageTokens[$this->entity], array_keys($this->getTokenMetadata()));
   }
 
+  /**
+   * Add the token to the metadata based on the field spec.
+   *
+   * @param array $tokensMetadata
+   * @param array $field
+   * @param array $exposedFields
+   * @param string $prefix
+   */
+  protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void {
+    if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
+      return;
+    }
+    $field['audience'] = 'user';
+    if ($field['name'] === 'contact_id') {
+      // Since {contact.id} is almost always present don't confuse users
+      // by also adding (e.g {participant.contact_id)
+      $field['audience'] = 'sysadmin';
+    }
+    if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
+      $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
+    }
+    if ($field['type'] === 'Custom') {
+      // Convert to apiv3 style for now. Later we can add v4 with
+      // portable naming & support for labels/ dates etc so let's leave
+      // the space open for that.
+      // Not the existing quickform widget has handling for the custom field
+      // format based on the title using this syntax.
+      $parts = explode(': ', $field['label']);
+      $field['title'] = "{$parts[1]} :: {$parts[0]}";
+      $tokenName = 'custom_' . $field['custom_field_id'];
+      $tokensMetadata[$tokenName] = $field;
+      return;
+    }
+    $tokenName = $prefix ? ($prefix . '.' . $field['name']) : $field['name'];
+    if (in_array($field['name'], $exposedFields, TRUE)) {
+      if (
+        ($field['options'] || !empty($field['suffixes']))
+        // At the time of writing currency didn't have a label option - this may have changed.
+        && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
+      ) {
+        $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
+        $fieldLabel = $field['input_attrs']['label'] ?? $field['label'];
+        $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
+        $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
+        $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
+        $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
+        $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
+        $field['audience'] = 'sysadmin';
+      }
+      if ($field['data_type'] === 'Boolean') {
+        $tokensMetadata[$tokenName . ':label'] = $field;
+        $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
+        $field['audience'] = 'sysadmin';
+      }
+      $tokensMetadata[$tokenName] = $field;
+    }
+  }
+
+  /**
+   * Get a cache key appropriate to the current usage.
+   *
+   * @return string
+   */
+  protected function getCacheKey(): string {
+    $cacheKey = __CLASS__ . 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config::domainID() . '_' . CRM_Core_I18n::getLocale();
+    if ($this->checkPermissions) {
+      $cacheKey .= '__' . CRM_Core_Session::getLoggedInContactID();
+    }
+    return $cacheKey;
+  }
+
 }