11 * A TokenRow is a helper/stub providing simplified access to the TokenProcessor.
12 * There are two common cases for using the TokenRow stub:
14 * (1) When setting up a job, you may specify general/baseline info.
15 * This is called the "context" data. Here, we create two rows:
18 * $proc->addRow()->context('contact_id', 123);
19 * $proc->addRow()->context('contact_id', 456);
22 * (2) When defining a token (eg `{profile.viewUrl}`), you might read the
23 * context-data (`contact_id`) and set the token-data (`profile => viewUrl`):
26 * foreach ($proc->getRows() as $row) {
27 * $row->tokens('profile', [
28 * 'viewUrl' => 'http://example.com/profile?cid=' . urlencode($row->context['contact_id'];
33 * The context and tokens can be accessed using either methods or attributes.
36 * # Setting context data
37 * $row->context('contact_id', 123);
38 * $row->context(['contact_id' => 123]);
40 * # Setting token data
41 * $row->tokens('profile', ['viewUrl' => 'http://example.com/profile?cid=123']);
42 * $row->tokens('profile', 'viewUrl, 'http://example.com/profile?cid=123');
44 * # Reading context data
45 * echo $row->context['contact_id'];
47 * # Reading token data
48 * echo $row->tokens['profile']['viewUrl'];
51 * Note: The methods encourage a "fluent" style. They were written for PHP 5.3
52 * (eg before short-array syntax was supported) and are fairly flexible about
53 * input notations (e.g. `context(string $key, mixed $value)` vs `context(array $keyValuePairs)`).
55 * Note: An instance of `TokenRow` is a stub which only contains references to the
56 * main data in `TokenProcessor`. There may be several `TokenRow` stubs
57 * referencing the same `TokenProcessor`. You can think of `TokenRow` objects as
58 * lightweight and disposable.
63 * The token-processor is where most data is actually stored.
65 * Note: Not intended for public usage. However, this is marked public to allow
66 * interaction classes in this package (`TokenProcessor`<=>`TokenRow`<=>`TokenRowContext`).
70 public $tokenProcessor;
73 * Row ID - the record within TokenProcessor that we're accessing.
80 * The MIME type associated with new token-values.
82 * This is generally manipulated as part of a fluent chain, eg
84 * $row->format('text/plain')->token(['display_name', 'Alice Bobdaughter']);
91 * @var array|\ArrayAccess
92 * List of token values.
93 * This is a facade for the TokenProcessor::$rowValues.
94 * Ex: ['contact' => ['display_name' => 'Alice']]
99 * @var array|\ArrayAccess
100 * List of context values.
101 * This is a facade for the TokenProcessor::$rowContexts.
102 * Ex: ['controller' => 'CRM_Foo_Bar']
106 public function __construct(TokenProcessor
$tokenProcessor, $key) {
107 $this->tokenProcessor
= $tokenProcessor;
108 $this->tokenRow
= $key;
110 $this->format('text/plain');
111 $this->context
= new TokenRowContext($tokenProcessor, $key);
115 * @param string $format
118 public function format($format) {
119 $this->format
= $format;
120 $this->tokens
= &$this->tokenProcessor
->rowValues
[$this->tokenRow
][$format];
125 * Update the value of a context element.
127 * @param string|array $a
131 public function context($a = NULL, $b = NULL) {
133 \CRM_Utils_Array
::extend($this->tokenProcessor
->rowContexts
[$this->tokenRow
], $a);
135 elseif (is_array($b)) {
136 \CRM_Utils_Array
::extend($this->tokenProcessor
->rowContexts
[$this->tokenRow
][$a], $b);
139 $this->tokenProcessor
->rowContexts
[$this->tokenRow
][$a] = $b;
145 * Update the value of a token.
147 * If you are reading this it probably means you can't follow this function.
148 * Don't worry - I've stared at it & all I see is a bunch of letters. However,
149 * the answer to your problem is almost certainly that you are passing in null
150 * rather than an empty string for 'c'.
152 * @param string|array $a
153 * @param string|array $b
157 public function tokens($a = NULL, $b = NULL, $c = NULL) {
159 \CRM_Utils_Array
::extend($this->tokens
, $a);
161 elseif (is_array($b)) {
162 \CRM_Utils_Array
::extend($this->tokens
[$a], $b);
164 elseif (is_array($c)) {
165 \CRM_Utils_Array
::extend($this->tokens
[$a][$b], $c);
167 elseif ($c === NULL) {
168 $this->tokens
[$a] = $b;
171 $this->tokens
[$a][$b] = $c;
177 * Update the value of a custom field token.
179 * @param string $entity
180 * @param int $customFieldID
181 * @param int $entityID
184 public function customToken($entity, $customFieldID, $entityID) {
185 $customFieldName = 'custom_' . $customFieldID;
186 $record = civicrm_api3($entity, 'getSingle', [
187 'return' => $customFieldName,
190 $fieldValue = \CRM_Utils_Array
::value($customFieldName, $record, '');
192 // format the raw custom field value into proper display value
193 if (isset($fieldValue)) {
194 $fieldValue = (string) \CRM_Core_BAO_CustomField
::displayValue($fieldValue, $customFieldID);
197 return $this->format('text/html')->tokens($entity, $customFieldName, $fieldValue);
201 * Update the value of a token. Apply formatting based on DB schema.
203 * @param string $tokenEntity
204 * @param string $tokenField
205 * @param string $baoName
206 * @param string $baoField
207 * @param mixed $fieldValue
209 * @throws \CRM_Core_Exception
211 public function dbToken($tokenEntity, $tokenField, $baoName, $baoField, $fieldValue) {
212 \CRM_Core_Error
::deprecatedFunctionWarning('no alternative');
213 if ($fieldValue === NULL ||
$fieldValue === '') {
214 return $this->tokens($tokenEntity, $tokenField, '');
217 $fields = $baoName::fields();
218 if (!empty($fields[$baoField]['pseudoconstant'])) {
219 $options = $baoName::buildOptions($baoField, 'get');
220 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $options[$fieldValue]);
223 switch ($fields[$baoField]['type']) {
224 case \CRM_Utils_Type
::T_DATE + \CRM_Utils_Type
::T_TIME
:
225 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Date
::customFormat($fieldValue));
227 case \CRM_Utils_Type
::T_MONEY
:
228 // Is this something you should ever use? Seems like you need more context
229 // to know which currency to use.
230 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Money
::format($fieldValue));
232 case \CRM_Utils_Type
::T_STRING
:
233 case \CRM_Utils_Type
::T_BOOLEAN
:
234 case \CRM_Utils_Type
::T_INT
:
235 case \CRM_Utils_Type
::T_TEXT
:
236 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $fieldValue);
240 throw new \
CRM_Core_Exception("Cannot format token for field '$baoField' in '$baoName'");
244 * Auto-convert between different formats
246 * @param string $format
250 public function fill($format = NULL) {
251 if ($format === NULL) {
252 $format = $this->format
;
255 if (!isset($this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/html'])) {
256 $this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/html'] = [];
258 if (!isset($this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/plain'])) {
259 $this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/plain'] = [];
262 $htmlTokens = &$this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/html'];
263 $textTokens = &$this->tokenProcessor
->rowValues
[$this->tokenRow
]['text/plain'];
268 foreach ($textTokens as $entity => $values) {
269 $entityFields = civicrm_api3($entity, "getFields", ['api_action' => 'get']);
270 foreach ($values as $field => $value) {
271 if (!isset($htmlTokens[$entity][$field])) {
272 // CRM-18420 - Activity Details Field are enclosed within <p>,
273 // hence if $body_text is empty, htmlentities will lead to
274 // conversion of these tags resulting in raw HTML.
275 if ($entity == 'activity' && $field == 'details') {
276 $htmlTokens[$entity][$field] = $value;
278 elseif (\CRM_Utils_Array
::value('data_type', \CRM_Utils_Array
::value($field, $entityFields['values'])) == 'Memo') {
279 // Memo fields aka custom fields of type Note are html.
280 $htmlTokens[$entity][$field] = \CRM_Utils_String
::purifyHTML($value);
283 $htmlTokens[$entity][$field] = is_object($value) ?
$value : htmlentities($value, ENT_QUOTES
);
292 foreach ($htmlTokens as $entity => $values) {
293 foreach ($values as $field => $value) {
294 if (!$value instanceof \DateTime
&& !$value instanceof Money
) {
295 $value = html_entity_decode(strip_tags($value));
297 if (!isset($textTokens[$entity][$field])) {
298 $textTokens[$entity][$field] = $value;
305 throw new \
RuntimeException('Invalid format');
314 * @param string $name
315 * The name previously registered with TokenProcessor::addMessage.
317 * Fully rendered message, with tokens merged.
319 public function render($name) {
320 return $this->tokenProcessor
->render($name, $this);
326 * Class TokenRowContext
327 * @package Civi\Token
329 * Combine the row-context and general-context into a single array-like facade.
331 class TokenRowContext
implements \ArrayAccess
, \IteratorAggregate
, \Countable
{
334 * @var TokenProcessor
336 protected $tokenProcessor;
343 * @param array $tokenProcessor
344 * @param array $tokenRow
346 public function __construct($tokenProcessor, $tokenRow) {
347 $this->tokenProcessor
= $tokenProcessor;
348 $this->tokenRow
= $tokenRow;
354 * @param mixed $offset
358 public function offsetExists($offset) {
359 return isset($this->tokenProcessor
->rowContexts
[$this->tokenRow
][$offset])
360 ||
isset($this->tokenProcessor
->context
[$offset]);
366 * @param string $offset
370 public function &offsetGet($offset) {
371 if (isset($this->tokenProcessor
->rowContexts
[$this->tokenRow
][$offset])) {
372 return $this->tokenProcessor
->rowContexts
[$this->tokenRow
][$offset];
374 if (isset($this->tokenProcessor
->context
[$offset])) {
375 return $this->tokenProcessor
->context
[$offset];
384 * @param string $offset
385 * @param mixed $value
387 public function offsetSet($offset, $value) {
388 $this->tokenProcessor
->rowContexts
[$this->tokenRow
][$offset] = $value;
394 * @param mixed $offset
396 public function offsetUnset($offset) {
397 unset($this->tokenProcessor
->rowContexts
[$this->tokenRow
][$offset]);
403 * @return \ArrayIterator
405 public function getIterator() {
406 return new \
ArrayIterator($this->createMergedArray());
414 public function count() {
415 return count($this->createMergedArray());
419 * Create merged array.
423 protected function createMergedArray() {
425 $this->tokenProcessor
->rowContexts
[$this->tokenRow
],
426 $this->tokenProcessor
->context