Merge pull request #9661 from monishdeb/CRM-18141
[civicrm-core.git] / Civi / Token / AbstractTokenSubscriber.php
index 5e5472ba654d7287bcc00dda6af295813d3f7baf..1164032de84c384de0cb3d938fef5fd2c50829f5 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.7                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015                                |
+ | Copyright CiviCRM LLC (c) 2004-2017                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -117,6 +117,22 @@ abstract class AbstractTokenSubscriber implements EventSubscriberInterface {
     }
   }
 
+  /**
+   * Get all custom field tokens of $entity
+   *
+   * @param string $entity
+   * @return array $customTokens
+   *   return custom field tokens in array('custom_N' => 'label') format
+   */
+  public function getCustomTokens($entity) {
+    $customTokens = array();
+    foreach (\CRM_Core_BAO_CustomField::getFields($entity) as $id => $info) {
+      $customTokens["custom_$id"] = $info['label'];
+    }
+
+    return $customTokens;
+  }
+
   /**
    * Alter the query which prepopulates mailing data
    * for scheduled reminders.
@@ -141,10 +157,18 @@ abstract class AbstractTokenSubscriber implements EventSubscriberInterface {
     if (!$this->checkActive($e->getTokenProcessor())) {
       return;
     }
-    // TODO: check if any tokens for $entity are actually used; short-circuit.
+
+    $messageTokens = $e->getTokenProcessor()->getMessageTokens();
+    if (!isset($messageTokens[$this->entity])) {
+      return;
+    }
+
+    $activeTokens = array_intersect($messageTokens[$this->entity], array_keys($this->tokenNames));
+
     $prefetch = $this->prefetch($e);
+
     foreach ($e->getRows() as $row) {
-      foreach ($this->tokenNames as $field => $label) {
+      foreach ((array) $activeTokens as $field) {
         $this->evaluateToken($row, $this->entity, $field, $prefetch);
       }
     }
@@ -154,6 +178,8 @@ abstract class AbstractTokenSubscriber implements EventSubscriberInterface {
    * To perform a bulk lookup before rendering tokens, override this
    * function and return the prefetched data.
    *
+   * @param \Civi\Token\Event\TokenValueEvent $e
+   *
    * @return mixed
    */
   public function prefetch(TokenValueEvent $e) {