Merge pull request #13042 from jackrabbithanna/dev-core-475
[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 providing simplified access to the
9 * TokenProcessor.
10 *
11 * A TokenRow combines two elements:
12 * - context: This is backend data provided by the controller.
13 * - tokens: This is frontend data that can be mail-merged.
14 *
15 * The context and tokens can be accessed using either methods
16 * or attributes. The methods are appropriate for updates
17 * (and generally accept a mix of arrays), and the attributes
18 * are appropriate for reads.
19 *
20 * To update the context or the tokens, use the methods.
21 * Note that the methods are fairly flexible about accepting
22 * single values or arrays. If given an array, the values
23 * will be merged recursively.
24 *
25 * @code
26 * $row
27 * ->context('contact_id', 123)
28 * ->context(array('contact_id' => 123))
29 * ->tokens('profile', array('viewUrl' => 'http://example.com'))
30 * ->tokens('profile', 'viewUrl, 'http://example.com');
31 *
32 * echo $row->context['contact_id'];
33 * echo $row->tokens['profile']['viewUrl'];
34 *
35 * $row->tokens('profile', array(
36 * 'viewUrl' => 'http://example.com/view/' . urlencode($row->context['contact_id'];
37 * ));
38 * @endcode
39 */
40 class TokenRow {
41
42 /**
43 * @var TokenProcessor
44 */
45 public $tokenProcessor;
46
47 public $tokenRow;
48
49 public $format;
50
51 /**
52 * @var array|\ArrayAccess
53 * List of token values.
54 * Ex: array('contact' => array('display_name' => 'Alice')).
55 */
56 public $tokens;
57
58 /**
59 * @var array|\ArrayAccess
60 * List of context values.
61 * Ex: array('controller' => 'CRM_Foo_Bar').
62 */
63 public $context;
64
65 public function __construct(TokenProcessor $tokenProcessor, $key) {
66 $this->tokenProcessor = $tokenProcessor;
67 $this->tokenRow = $key;
68 $this->format('text/plain'); // Set a default.
69 $this->context = new TokenRowContext($tokenProcessor, $key);
70 }
71
72 /**
73 * @param string $format
74 * @return TokenRow
75 */
76 public function format($format) {
77 $this->format = $format;
78 $this->tokens = &$this->tokenProcessor->rowValues[$this->tokenRow][$format];
79 return $this;
80 }
81
82 /**
83 * Update the value of a context element.
84 *
85 * @param string|array $a
86 * @param mixed $b
87 * @return TokenRow
88 */
89 public function context($a = NULL, $b = NULL) {
90 if (is_array($a)) {
91 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow], $a);
92 }
93 elseif (is_array($b)) {
94 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow][$a], $b);
95 }
96 else {
97 $this->tokenProcessor->rowContexts[$this->tokenRow][$a] = $b;
98 }
99 return $this;
100 }
101
102 /**
103 * Update the value of a token.
104 *
105 * @param string|array $a
106 * @param string|array $b
107 * @param mixed $c
108 * @return TokenRow
109 */
110 public function tokens($a = NULL, $b = NULL, $c = NULL) {
111 if (is_array($a)) {
112 \CRM_Utils_Array::extend($this->tokens, $a);
113 }
114 elseif (is_array($b)) {
115 \CRM_Utils_Array::extend($this->tokens[$a], $b);
116 }
117 elseif (is_array($c)) {
118 \CRM_Utils_Array::extend($this->tokens[$a][$b], $c);
119 }
120 elseif ($c === NULL) {
121 $this->tokens[$a] = $b;
122 }
123 else {
124 $this->tokens[$a][$b] = $c;
125 }
126 return $this;
127 }
128
129 /**
130 * Update the value of a custom field token.
131 *
132 * @param string $entity
133 * @param int $customFieldID
134 * @param int $entityID
135 * @return TokenRow
136 */
137 public function customToken($entity, $customFieldID, $entityID) {
138 $customFieldName = "custom_" . $customFieldID;
139 $record = civicrm_api3($entity, "getSingle", [
140 'return' => $customFieldName,
141 'id' => $entityID,
142 ]);
143 $fieldValue = \CRM_Utils_Array::value($customFieldName, $record, '');
144
145 // format the raw custom field value into proper display value
146 if (isset($fieldValue)) {
147 $fieldValue = \CRM_Core_BAO_CustomField::displayValue($fieldValue, $customFieldID);
148 }
149
150 return $this->tokens($entity, $customFieldName, $fieldValue);
151 }
152
153 /**
154 * Update the value of a token. Apply formatting based on DB schema.
155 *
156 * @param string $tokenEntity
157 * @param string $tokenField
158 * @param string $baoName
159 * @param array $baoField
160 * @param mixed $fieldValue
161 * @return TokenRow
162 * @throws \CRM_Core_Exception
163 */
164 public function dbToken($tokenEntity, $tokenField, $baoName, $baoField, $fieldValue) {
165 if ($fieldValue === NULL || $fieldValue === '') {
166 return $this->tokens($tokenEntity, $tokenField, '');
167 }
168
169 $fields = $baoName::fields();
170 if (!empty($fields[$baoField]['pseudoconstant'])) {
171 $options = $baoName::buildOptions($baoField, 'get');
172 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $options[$fieldValue]);
173 }
174
175 switch ($fields[$baoField]['type']) {
176 case \CRM_Utils_Type::T_DATE + \CRM_Utils_Type::T_TIME:
177 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Date::customFormat($fieldValue));
178
179 case \CRM_Utils_Type::T_MONEY:
180 // Is this something you should ever use? Seems like you need more context
181 // to know which currency to use.
182 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Money::format($fieldValue));
183
184 case \CRM_Utils_Type::T_STRING:
185 case \CRM_Utils_Type::T_BOOLEAN:
186 case \CRM_Utils_Type::T_INT:
187 case \CRM_Utils_Type::T_TEXT:
188 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $fieldValue);
189
190 }
191
192 throw new \CRM_Core_Exception("Cannot format token for field '$baoField' in '$baoName'");
193 }
194
195 /**
196 * Auto-convert between different formats
197 *
198 * @param string $format
199 *
200 * @return TokenRow
201 */
202 public function fill($format = NULL) {
203 if ($format === NULL) {
204 $format = $this->format;
205 }
206
207 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/html'])) {
208 $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = array();
209 }
210 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'])) {
211 $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = array();
212 }
213
214 $htmlTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/html'];
215 $textTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'];
216
217 switch ($format) {
218 case 'text/html':
219 // Plain => HTML.
220 foreach ($textTokens as $entity => $values) {
221 foreach ($values as $field => $value) {
222 if (!isset($htmlTokens[$entity][$field])) {
223 // CRM-18420 - Activity Details Field are enclosed within <p>,
224 // hence if $body_text is empty, htmlentities will lead to
225 // conversion of these tags resulting in raw HTML.
226 if ($entity == 'activity' && $field == 'details') {
227 $htmlTokens[$entity][$field] = $value;
228 }
229 else {
230 $htmlTokens[$entity][$field] = htmlentities($value);
231 }
232 }
233 }
234 }
235 break;
236
237 case 'text/plain':
238 // HTML => Plain.
239 foreach ($htmlTokens as $entity => $values) {
240 foreach ($values as $field => $value) {
241 if (!isset($textTokens[$entity][$field])) {
242 $textTokens[$entity][$field] = html_entity_decode(strip_tags($value));
243 }
244 }
245 }
246 break;
247
248 default:
249 throw new \RuntimeException("Invalid format");
250 }
251
252 return $this;
253 }
254
255 /**
256 * Render a message.
257 *
258 * @param string $name
259 * The name previously registered with TokenProcessor::addMessage.
260 * @return string
261 * Fully rendered message, with tokens merged.
262 */
263 public function render($name) {
264 return $this->tokenProcessor->render($name, $this);
265 }
266
267 }
268
269 /**
270 * Class TokenRowContext
271 * @package Civi\Token
272 *
273 * Combine the row-context and general-context into a single array-like facade.
274 */
275 class TokenRowContext implements \ArrayAccess, \IteratorAggregate, \Countable {
276
277 /**
278 * @var TokenProcessor
279 */
280 protected $tokenProcessor;
281
282 protected $tokenRow;
283
284 /**
285 * Class constructor.
286 *
287 * @param array $tokenProcessor
288 * @param array $tokenRow
289 */
290 public function __construct($tokenProcessor, $tokenRow) {
291 $this->tokenProcessor = $tokenProcessor;
292 $this->tokenRow = $tokenRow;
293 }
294
295 /**
296 * Does offset exist.
297 *
298 * @param mixed $offset
299 *
300 * @return bool
301 */
302 public function offsetExists($offset) {
303 return
304 isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])
305 || isset($this->tokenProcessor->context[$offset]);
306 }
307
308 /**
309 * Get offset.
310 *
311 * @param string $offset
312 *
313 * @return string
314 */
315 public function &offsetGet($offset) {
316 if (isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])) {
317 return $this->tokenProcessor->rowContexts[$this->tokenRow][$offset];
318 }
319 if (isset($this->tokenProcessor->context[$offset])) {
320 return $this->tokenProcessor->context[$offset];
321 }
322 $val = NULL;
323 return $val;
324 }
325
326 /**
327 * Set offset.
328 *
329 * @param string $offset
330 * @param mixed $value
331 */
332 public function offsetSet($offset, $value) {
333 $this->tokenProcessor->rowContexts[$this->tokenRow][$offset] = $value;
334 }
335
336 /**
337 * Unset offset.
338 *
339 * @param mixed $offset
340 */
341 public function offsetUnset($offset) {
342 unset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]);
343 }
344
345 /**
346 * Get iterator.
347 *
348 * @return \ArrayIterator
349 */
350 public function getIterator() {
351 return new \ArrayIterator($this->createMergedArray());
352 }
353
354 /**
355 * Count.
356 *
357 * @return int
358 */
359 public function count() {
360 return count($this->createMergedArray());
361 }
362
363 /**
364 * Create merged array.
365 *
366 * @return array
367 */
368 protected function createMergedArray() {
369 return array_merge(
370 $this->tokenProcessor->rowContexts[$this->tokenRow],
371 $this->tokenProcessor->context
372 );
373 }
374
375 }