77207fa5f9d5bae509edbbdb946a4e9d4a6e5a07
[civicrm-core.git] / CRM / Contribute / Tokens.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 use Civi\ActionSchedule\Event\MailingQueryEvent;
14 use Civi\Token\AbstractTokenSubscriber;
15 use Civi\Token\TokenProcessor;
16 use Civi\Token\TokenRow;
17
18 /**
19 * Class CRM_Contribute_Tokens
20 *
21 * Generate "contribution.*" tokens.
22 *
23 * At time of writing, we don't have any particularly special tokens -- we just
24 * do some basic formatting based on the corresponding DB field.
25 */
26 class CRM_Contribute_Tokens extends AbstractTokenSubscriber {
27
28 /**
29 * @return string
30 */
31 protected function getEntityName(): string {
32 return 'contribution';
33 }
34
35 /**
36 * Get the relevant bao name.
37 */
38 public function getBAOName(): string {
39 return CRM_Core_DAO_AllCoreTables::getFullName(ucfirst($this->getEntityName()));
40 }
41
42 /**
43 * Metadata about the entity fields.
44 *
45 * @var array
46 */
47 protected $fieldMetadata = [];
48
49 /**
50 * Get a list of tokens whose name and title match the DB fields.
51 * @return array
52 */
53 protected function getPassthruTokens(): array {
54 return [
55 'contribution_page_id',
56 'source',
57 'id',
58 'receive_date',
59 'total_amount',
60 'fee_amount',
61 'net_amount',
62 'trxn_id',
63 'invoice_id',
64 'currency',
65 'cancel_date',
66 'receipt_date',
67 'thankyou_date',
68 'tax_amount',
69 'contribution_status_id',
70 'financial_type_id',
71 'payment_instrument_id',
72 ];
73 }
74
75 /**
76 * Get tokens supporting the syntax we are migrating to.
77 *
78 * In general these are tokens that were not previously supported
79 * so we can add them in the preferred way or that we have
80 * undertaken some, as yet to be written, db update.
81 *
82 * See https://lab.civicrm.org/dev/core/-/issues/2650
83 *
84 * @return string[]
85 */
86 public function getBasicTokens(): array {
87 $return = [];
88 foreach (['contribution_status_id', 'payment_instrument_id', 'financial_type_id'] as $fieldName) {
89 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
90 }
91 return $return;
92 }
93
94 /**
95 * Get pseudoTokens - it tokens that reflect the name or label of a pseudoconstant.
96 *
97 * @internal - this function will likely be made protected soon.
98 *
99 * @return array
100 */
101 public function getPseudoTokens(): array {
102 $return = [];
103 foreach (array_keys($this->getBasicTokens()) as $fieldName) {
104 if (!empty($this->fieldMetadata[$fieldName]['pseudoconstant'])) {
105 $return[$fieldName . ':label'] = $this->fieldMetadata[$fieldName]['html']['label'];
106 $return[$fieldName . ':name'] = ts('Machine name') . ': ' . $this->fieldMetadata[$fieldName]['html']['label'];
107 }
108 }
109 return $return;
110 }
111
112 /**
113 * Class constructor.
114 */
115 public function __construct() {
116 $tokens = CRM_Utils_Array::subset(
117 CRM_Utils_Array::collect('title', $this->getFieldMetadata()),
118 $this->getPassthruTokens()
119 );
120 $tokens = array_merge($tokens, $this->getPseudoTokens(), CRM_Utils_Token::getCustomFieldTokens('Contribution'));
121 parent::__construct('contribution', $tokens);
122 }
123
124 /**
125 * Check if the token processor is active.
126 *
127 * @param \Civi\Token\TokenProcessor $processor
128 *
129 * @return bool
130 */
131 public function checkActive(TokenProcessor $processor) {
132 return !empty($processor->context['actionMapping'])
133 && $processor->context['actionMapping']->getEntity() === 'civicrm_contribution';
134 }
135
136 /**
137 * Alter action schedule query.
138 *
139 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
140 */
141 public function alterActionScheduleQuery(MailingQueryEvent $e): void {
142 if ($e->mapping->getEntity() !== 'civicrm_contribution') {
143 return;
144 }
145
146 $fields = $this->getFieldMetadata();
147 foreach ($this->getPassthruTokens() as $token) {
148 $e->query->select("e." . $fields[$token]['name'] . " AS contrib_{$token}");
149 }
150 foreach (array_keys($this->getPseudoTokens()) as $token) {
151 $split = explode(':', $token);
152 $e->query->select("e." . $fields[$split[0]]['name'] . " AS contrib_{$split[0]}");
153 }
154 }
155
156 /**
157 * @inheritDoc
158 */
159 public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL) {
160 $actionSearchResult = $row->context['actionSearchResult'];
161 $fieldValue = $actionSearchResult->{"contrib_$field"} ?? NULL;
162
163 if (in_array($field, ['total_amount', 'fee_amount', 'net_amount'])) {
164 return $row->format('text/plain')->tokens($entity, $field,
165 \CRM_Utils_Money::format($fieldValue, $actionSearchResult->contrib_currency));
166 }
167 elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
168 $row->customToken($entity, $cfID, $actionSearchResult->entity_id);
169 }
170 elseif (array_key_exists($field, $this->getPseudoTokens())) {
171 $split = explode(':', $field);
172 $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $actionSearchResult->{"contrib_$split[0]"} ?? NULL));
173 }
174 elseif (in_array($field, array_keys($this->getBasicTokens()))) {
175 $row->tokens($entity, $field, $fieldValue);
176 }
177 elseif (!array_key_exists($field, CRM_Contribute_BAO_Contribution::fields())) {
178 if ($this->isDateField($field)) {
179 $row->format('text/plain')->tokens($entity, $field, \CRM_Utils_Date::customFormat($fieldValue));
180 }
181 else {
182 $row->format('text/plain')->tokens($entity, $field, $fieldValue);
183 }
184 }
185 else {
186 $row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $field, $fieldValue);
187 }
188 }
189
190 /**
191 * Is the given field a date field.
192 *
193 * @param string $fieldName
194 *
195 * @return bool
196 */
197 public function isDateField($fieldName): bool {
198 return $this->getFieldMetadata()[$fieldName]['type'] === (\CRM_Utils_Type::T_DATE + \CRM_Utils_Type::T_TIME);
199 }
200
201 /**
202 * Get the value for the relevant pseudo field.
203 *
204 * @param string $realField e.g contribution_status_id
205 * @param string $pseudoKey e.g name
206 * @param int|string $fieldValue e.g 1
207 *
208 * @return string
209 * Eg. 'Completed' in the example above.
210 *
211 * @internal function will likely be protected soon.
212 */
213 public function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
214 if ($pseudoKey === 'name') {
215 $fieldValue = (string) CRM_Core_PseudoConstant::getName($this->getBAOName(), $realField, $fieldValue);
216 }
217 if ($pseudoKey === 'label') {
218 $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($this->getBAOName(), $realField, $fieldValue);
219 }
220 return (string) $fieldValue;
221 }
222
223 /**
224 * Get the metadata for the available fields.
225 *
226 * @return array
227 */
228 protected function getFieldMetadata(): array {
229 if (empty($this->fieldMetadata)) {
230 $baoName = $this->getBAOName();
231 $fields = (array) $baoName::fields();
232 // re-index by real field name. I originally wanted to use apiv4
233 // getfields - but it returns different stuff for 'type' and
234 // does not return 'pseudoconstant' as a key so for now...
235 foreach ($fields as $details) {
236 $this->fieldMetadata[$details['name']] = $details;
237 }
238 }
239 return $this->fieldMetadata;
240 }
241
242 }