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