Merge pull request #21521 from eileenmcnaughton/member_tokens
[civicrm-core.git] / Civi / Token / TokenRow.php
1 <?php
2 namespace Civi\Token;
3
4 /**
5 * Class TokenRow
6 * @package Civi\Token
7 *
8 * A TokenRow is a helper/stub providing simplified access to the TokenProcessor.
9 * There are two common cases for using the TokenRow stub:
10 *
11 * (1) When setting up a job, you may specify general/baseline info.
12 * This is called the "context" data. Here, we create two rows:
13 *
14 * ```
15 * $proc->addRow()->context('contact_id', 123);
16 * $proc->addRow()->context('contact_id', 456);
17 * ```
18 *
19 * (2) When defining a token (eg `{profile.viewUrl}`), you might read the
20 * context-data (`contact_id`) and set the token-data (`profile => viewUrl`):
21 *
22 * ```
23 * foreach ($proc->getRows() as $row) {
24 * $row->tokens('profile', [
25 * 'viewUrl' => 'http://example.com/profile?cid=' . urlencode($row->context['contact_id'];
26 * ]);
27 * }
28 * ```
29 *
30 * The context and tokens can be accessed using either methods or attributes.
31 *
32 * ```
33 * # Setting context data
34 * $row->context('contact_id', 123);
35 * $row->context(['contact_id' => 123]);
36 *
37 * # Setting token data
38 * $row->tokens('profile', ['viewUrl' => 'http://example.com/profile?cid=123']);
39 * $row->tokens('profile', 'viewUrl, 'http://example.com/profile?cid=123');
40 *
41 * # Reading context data
42 * echo $row->context['contact_id'];
43 *
44 * # Reading token data
45 * echo $row->tokens['profile']['viewUrl'];
46 * ```
47 *
48 * Note: The methods encourage a "fluent" style. They were written for PHP 5.3
49 * (eg before short-array syntax was supported) and are fairly flexible about
50 * input notations (e.g. `context(string $key, mixed $value)` vs `context(array $keyValuePairs)`).
51 *
52 * Note: An instance of `TokenRow` is a stub which only contains references to the
53 * main data in `TokenProcessor`. There may be several `TokenRow` stubs
54 * referencing the same `TokenProcessor`. You can think of `TokenRow` objects as
55 * lightweight and disposable.
56 */
57 class TokenRow {
58
59 /**
60 * The token-processor is where most data is actually stored.
61 *
62 * Note: Not intended for public usage. However, this is marked public to allow
63 * interaction classes in this package (`TokenProcessor`<=>`TokenRow`<=>`TokenRowContext`).
64 *
65 * @var TokenProcessor
66 */
67 public $tokenProcessor;
68
69 /**
70 * Row ID - the record within TokenProcessor that we're accessing.
71 *
72 * @var int
73 */
74 public $tokenRow;
75
76 /**
77 * The MIME type associated with new token-values.
78 *
79 * This is generally manipulated as part of a fluent chain, eg
80 *
81 * $row->format('text/plain')->token(['display_name', 'Alice Bobdaughter']);
82 *
83 * @var string
84 */
85 public $format;
86
87 /**
88 * @var array|\ArrayAccess
89 * List of token values.
90 * This is a facade for the TokenProcessor::$rowValues.
91 * Ex: ['contact' => ['display_name' => 'Alice']]
92 */
93 public $tokens;
94
95 /**
96 * @var array|\ArrayAccess
97 * List of context values.
98 * This is a facade for the TokenProcessor::$rowContexts.
99 * Ex: ['controller' => 'CRM_Foo_Bar']
100 */
101 public $context;
102
103 public function __construct(TokenProcessor $tokenProcessor, $key) {
104 $this->tokenProcessor = $tokenProcessor;
105 $this->tokenRow = $key;
106 // Set a default.
107 $this->format('text/plain');
108 $this->context = new TokenRowContext($tokenProcessor, $key);
109 }
110
111 /**
112 * @param string $format
113 * @return TokenRow
114 */
115 public function format($format) {
116 $this->format = $format;
117 $this->tokens = &$this->tokenProcessor->rowValues[$this->tokenRow][$format];
118 return $this;
119 }
120
121 /**
122 * Update the value of a context element.
123 *
124 * @param string|array $a
125 * @param mixed $b
126 * @return TokenRow
127 */
128 public function context($a = NULL, $b = NULL) {
129 if (is_array($a)) {
130 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow], $a);
131 }
132 elseif (is_array($b)) {
133 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow][$a], $b);
134 }
135 else {
136 $this->tokenProcessor->rowContexts[$this->tokenRow][$a] = $b;
137 }
138 return $this;
139 }
140
141 /**
142 * Update the value of a token.
143 *
144 * @param string|array $a
145 * @param string|array $b
146 * @param mixed $c
147 * @return TokenRow
148 */
149 public function tokens($a = NULL, $b = NULL, $c = NULL) {
150 if (is_array($a)) {
151 \CRM_Utils_Array::extend($this->tokens, $a);
152 }
153 elseif (is_array($b)) {
154 \CRM_Utils_Array::extend($this->tokens[$a], $b);
155 }
156 elseif (is_array($c)) {
157 \CRM_Utils_Array::extend($this->tokens[$a][$b], $c);
158 }
159 elseif ($c === NULL) {
160 $this->tokens[$a] = $b;
161 }
162 else {
163 $this->tokens[$a][$b] = $c;
164 }
165 return $this;
166 }
167
168 /**
169 * Update the value of a custom field token.
170 *
171 * @param string $entity
172 * @param int $customFieldID
173 * @param int $entityID
174 * @return TokenRow
175 */
176 public function customToken($entity, $customFieldID, $entityID) {
177 $customFieldName = "custom_" . $customFieldID;
178 $record = civicrm_api3($entity, "getSingle", [
179 'return' => $customFieldName,
180 'id' => $entityID,
181 ]);
182 $fieldValue = \CRM_Utils_Array::value($customFieldName, $record, '');
183
184 // format the raw custom field value into proper display value
185 if (isset($fieldValue)) {
186 $fieldValue = \CRM_Core_BAO_CustomField::displayValue($fieldValue, $customFieldID);
187 }
188
189 return $this->tokens($entity, $customFieldName, $fieldValue);
190 }
191
192 /**
193 * Update the value of a token. Apply formatting based on DB schema.
194 *
195 * @param string $tokenEntity
196 * @param string $tokenField
197 * @param string $baoName
198 * @param string $baoField
199 * @param mixed $fieldValue
200 * @return TokenRow
201 * @throws \CRM_Core_Exception
202 */
203 public function dbToken($tokenEntity, $tokenField, $baoName, $baoField, $fieldValue) {
204 \CRM_Core_Error::deprecatedFunctionWarning('no alternative');
205 if ($fieldValue === NULL || $fieldValue === '') {
206 return $this->tokens($tokenEntity, $tokenField, '');
207 }
208
209 $fields = $baoName::fields();
210 if (!empty($fields[$baoField]['pseudoconstant'])) {
211 $options = $baoName::buildOptions($baoField, 'get');
212 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $options[$fieldValue]);
213 }
214
215 switch ($fields[$baoField]['type']) {
216 case \CRM_Utils_Type::T_DATE + \CRM_Utils_Type::T_TIME:
217 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Date::customFormat($fieldValue));
218
219 case \CRM_Utils_Type::T_MONEY:
220 // Is this something you should ever use? Seems like you need more context
221 // to know which currency to use.
222 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Money::format($fieldValue));
223
224 case \CRM_Utils_Type::T_STRING:
225 case \CRM_Utils_Type::T_BOOLEAN:
226 case \CRM_Utils_Type::T_INT:
227 case \CRM_Utils_Type::T_TEXT:
228 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $fieldValue);
229
230 }
231
232 throw new \CRM_Core_Exception("Cannot format token for field '$baoField' in '$baoName'");
233 }
234
235 /**
236 * Auto-convert between different formats
237 *
238 * @param string $format
239 *
240 * @return TokenRow
241 */
242 public function fill($format = NULL) {
243 if ($format === NULL) {
244 $format = $this->format;
245 }
246
247 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/html'])) {
248 $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = [];
249 }
250 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'])) {
251 $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = [];
252 }
253
254 $htmlTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/html'];
255 $textTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'];
256
257 switch ($format) {
258 case 'text/html':
259 // Plain => HTML.
260 foreach ($textTokens as $entity => $values) {
261 $entityFields = civicrm_api3($entity, "getFields", ['api_action' => 'get']);
262 foreach ($values as $field => $value) {
263 if (!isset($htmlTokens[$entity][$field])) {
264 // CRM-18420 - Activity Details Field are enclosed within <p>,
265 // hence if $body_text is empty, htmlentities will lead to
266 // conversion of these tags resulting in raw HTML.
267 if ($entity == 'activity' && $field == 'details') {
268 $htmlTokens[$entity][$field] = $value;
269 }
270 elseif (\CRM_Utils_Array::value('data_type', \CRM_Utils_Array::value($field, $entityFields['values'])) == 'Memo') {
271 // Memo fields aka custom fields of type Note are html.
272 $htmlTokens[$entity][$field] = \CRM_Utils_String::purifyHTML($value);
273 }
274 else {
275 $htmlTokens[$entity][$field] = is_object($value) ? $value : htmlentities($value);
276 }
277 }
278 }
279 }
280 break;
281
282 case 'text/plain':
283 // HTML => Plain.
284 foreach ($htmlTokens as $entity => $values) {
285 foreach ($values as $field => $value) {
286 if (!$value instanceof \DateTime) {
287 $value = html_entity_decode(strip_tags($value));
288 }
289 if (!isset($textTokens[$entity][$field])) {
290 $textTokens[$entity][$field] = $value;
291 }
292 }
293 }
294 break;
295
296 default:
297 throw new \RuntimeException('Invalid format');
298 }
299
300 return $this;
301 }
302
303 /**
304 * Render a message.
305 *
306 * @param string $name
307 * The name previously registered with TokenProcessor::addMessage.
308 * @return string
309 * Fully rendered message, with tokens merged.
310 */
311 public function render($name) {
312 return $this->tokenProcessor->render($name, $this);
313 }
314
315 }
316
317 /**
318 * Class TokenRowContext
319 * @package Civi\Token
320 *
321 * Combine the row-context and general-context into a single array-like facade.
322 */
323 class TokenRowContext implements \ArrayAccess, \IteratorAggregate, \Countable {
324
325 /**
326 * @var TokenProcessor
327 */
328 protected $tokenProcessor;
329
330 protected $tokenRow;
331
332 /**
333 * Class constructor.
334 *
335 * @param array $tokenProcessor
336 * @param array $tokenRow
337 */
338 public function __construct($tokenProcessor, $tokenRow) {
339 $this->tokenProcessor = $tokenProcessor;
340 $this->tokenRow = $tokenRow;
341 }
342
343 /**
344 * Does offset exist.
345 *
346 * @param mixed $offset
347 *
348 * @return bool
349 */
350 public function offsetExists($offset) {
351 return isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])
352 || isset($this->tokenProcessor->context[$offset]);
353 }
354
355 /**
356 * Get offset.
357 *
358 * @param string $offset
359 *
360 * @return string
361 */
362 public function &offsetGet($offset) {
363 if (isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])) {
364 return $this->tokenProcessor->rowContexts[$this->tokenRow][$offset];
365 }
366 if (isset($this->tokenProcessor->context[$offset])) {
367 return $this->tokenProcessor->context[$offset];
368 }
369 $val = NULL;
370 return $val;
371 }
372
373 /**
374 * Set offset.
375 *
376 * @param string $offset
377 * @param mixed $value
378 */
379 public function offsetSet($offset, $value) {
380 $this->tokenProcessor->rowContexts[$this->tokenRow][$offset] = $value;
381 }
382
383 /**
384 * Unset offset.
385 *
386 * @param mixed $offset
387 */
388 public function offsetUnset($offset) {
389 unset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]);
390 }
391
392 /**
393 * Get iterator.
394 *
395 * @return \ArrayIterator
396 */
397 public function getIterator() {
398 return new \ArrayIterator($this->createMergedArray());
399 }
400
401 /**
402 * Count.
403 *
404 * @return int
405 */
406 public function count() {
407 return count($this->createMergedArray());
408 }
409
410 /**
411 * Create merged array.
412 *
413 * @return array
414 */
415 protected function createMergedArray() {
416 return array_merge(
417 $this->tokenProcessor->rowContexts[$this->tokenRow],
418 $this->tokenProcessor->context
419 );
420 }
421
422 }