-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgive.module
341 lines (311 loc) · 11.9 KB
/
give.module
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
<?php
/**
* @file
* Enables the use of donation forms to give money on your site.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\Xss;
use Drupal\filter\Entity\FilterFormat;
/**
* Denotes that the donation is not completed.
*/
const DONATION_NOT_COMPLETED = 0;
/**
* Denotes that the donation is completed.
*/
const DONATION_COMPLETED = 1;
/**
* Process donation with Stripe.
*/
const GIVE_WITH_STRIPE = 1;
/**
* Process donation with Dwolla.
*/
const GIVE_WITH_DWOLLA = 2;
/**
* Accept a pledge to pay by check or other.
*/
const GIVE_WITH_CHECK = 3;
/**
* Return array of donation method constants with human-readable, text names.
*
* @param bool $long
*/
function give_methods($long = FALSE) {
if ($long !== TRUE) {
$pairs = [
GIVE_WITH_STRIPE => t('Card'),
GIVE_WITH_CHECK => t('Check'),
GIVE_WITH_DWOLLA => t('Bank transfer'),
];
}
else {
$pairs = [
GIVE_WITH_STRIPE => t('Payment card (Stripe)'),
GIVE_WITH_CHECK => t('Check pledge'),
GIVE_WITH_DWOLLA => t('Bank transfer (Dwolla)'),
];
}
return $pairs;
}
/**
* Implements hook_help().
*/
function give_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.give':
$menu_page = \Drupal::moduleHandler()->moduleExists('menu_ui') ? \Drupal::url('entity.menu.collection') : '#';
$block_page = \Drupal::moduleHandler()->moduleExists('block') ? \Drupal::url('block.admin_display') : '#';
$give_page = \Drupal::url('entity.give_form.collection');
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Give module allows visitors to donate to you with credit/debit card or bank transfer using donation forms you can configure. For more information, see the <a href=":give">online documentation for the Give module</a>.', [':give' => 'https://www.drupal.org/project/give']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Configuring give (donation) forms') . '</dt>';
$output .= '<dd>' . t('On the <a href=":give_admin">Give forms page</a>, you can configure the fields and display of the donation forms. Each give form has a machine name, a label, and zero or more defined recipients to receive notification when someone donates (or tries to donate).', [':give_admin' => $give_page]) . '</dd>';
$output .= '<dt>' . t('Linking to give (donation) forms') . '</dt>';
$output .= '<dd>' . t('One give form can be designated as the default donation form. If you choose to designate a default form, the <em>Give</em> menu link in the <em>Main</em> menu will link to it. You can modify this link from the <a href=":menu-settings">Menus page</a> if you have the Menu UI module installed. You can also create links to other give forms; the URL for each form you have set up has format <em>give/machine_name_of_form</em>.', [':menu-settings' => $menu_page]) . '</p>';
$output .= '<dt>' . t('Adding fields to give forms') . '</dt>';
$output .= '<dd>' . t('From the <a href=":give_admin">Give forms page</a>, you can configure the fields to be shown on different give forms, including their labels and help text. If you would like other content (such as text or images) to appear on a donation form, use a block. You can create and edit blocks on the <a href=":blocks">Block layout page</a>, if the Block module is installed. Another possibility is to embed donation forms in content with an entity reference field, or in paragraphs with the contributed <a href=":paragraphs">Paragraphs module</a>.', [':blocks' => $block_page, ':give_admin' => $give_page, ':paragraphs' => 'https://www.drupal.org/project/paragraphs']) . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_entity_extra_field_info().
*/
function give_entity_extra_field_info() {
$fields = [];
foreach (array_keys(\Drupal::service('entity_type.bundle.info')->getBundleInfo('give_donation')) as $bundle) {
$fields['give_donation'][$bundle]['form']['name'] = [
'label' => t('Donor name'),
'description' => t('Text'),
'weight' => -50,
];
$fields['give_donation'][$bundle]['form']['mail'] = [
'label' => t('Donor e-mail'),
'description' => t('Email'),
'weight' => -40,
];
$fields['give_donation'][$bundle]['form']['recurring'] = [
'label' => t('Recurring donation'),
'description' => t('Option'),
'weight' => 50,
];
}
return $fields;
}
/**
* Implements hook_entity_base_field_info_alter().
*
* Makes fields on donations configurable.
*
* @TODO do this in the first place rather than as an alter hook.
*/
function give_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'give_donation') {
foreach ([
'name',
'mail',
'give_form',
'label',
'uuid',
'id',
'langcode',
'amount',
'recurring',
'created',
'method',
'telephone',
'check_or_other_information',
'complete',
'address_line1',
'address_line2',
'address_city',
'address_state',
'address_zip',
'address_country',
'stripe_token',
'card_funding',
'card_brand',
'card_last4',
'changed',
] as $field_name) {
$fields[$field_name]->setDisplayConfigurable('view', TRUE);
}
}
}
/**
* Implements hook_entity_operation().
*/
function give_entity_operation(EntityInterface $entity) {
$operations = [];
$info = $entity->getEntityType();
// Add preview e-mails link to Give (donation) forms.
if ($info->getBundleOf() == 'give_donation') {
$account = \Drupal::currentUser();
if ($account->hasPermission('create and edit give forms')) {
$operations['preview-reply'] = [
'title' => t('Preview e-mails'),
'weight' => 15,
'url' => Url::fromRoute("entity.give_form.preview_reply", [
$entity->getEntityTypeId() => $entity->id(),
]),
];
}
}
return $operations;
}
/**
* Implements hook_mail().
*/
function give_mail($key, &$message, $params) {
$give_donation = $params['give_donation'];
/** @var $donor \Drupal\user\UserInterface */
$donor = $params['donor'];
$language = \Drupal::languageManager()->getLanguage($message['langcode']);
$variables = [
'@site-name' => \Drupal::config('system.site')->get('name'),
'@label' => $give_donation->getLabel(),
'@form' => !empty($params['give_form']) ? $params['give_form']->label() : NULL,
'@form-url' => \Drupal::url('<current>', [], ['absolute' => TRUE, 'language' => $language]),
'@donor-name' => $donor->getDisplayName(),
];
if ($donor->isAuthenticated()) {
$variables['@donor-url'] = $donor->url('canonical', ['absolute' => TRUE, 'language' => $language]);
}
else {
$variables['@donor-url'] = $params['donor']->getEmail();
}
switch ($key) {
case 'donation_notice':
$options = ['langcode' => $language->getId()];
$message['subject'] .= t('[@form] @label', $variables, $options);
// $message['body'][] = t("", $variables, $options);
$markup = entity_view($give_donation, 'notice');
$message['body'][] = render($markup);
break;
case 'donation_receipt':
$give_form = $params['give_form'];
switch ($give_donation->getReplyType()) {
case 'onetime':
$params['reply'] = $give_form->get('reply');
$params['subject'] = $give_form->get('subject');
break;
case 'recurring':
$params['reply'] = $give_form->get('reply_recurring');
$params['subject'] = $give_form->get('subject_recurring');
break;
case 'pledge':
$params['reply'] = $give_form->get('reply_pledge');
$params['subject'] = $give_form->get('subject_pledge');
break;
default:
$this->logger->notice('Unknown reply type %type triggered for %donor-name (@donor-from) via %give_form; no message sent.', [
'%donor-name' => $donor->getDisplayName(),
'@donor-from' => $donor->getEmail(),
'%give_form' => $give_form->label(),
'%type' => $give_donation->getReplyType(),
]);
}
$message['subject'] .= give_replace_donation_tokens($params['subject'], $give_donation);
$render_array = [
"#type" => "processed_text",
"#text" => give_replace_donation_tokens($params['reply'], $give_donation),
"#format" => give_format(),
"#langcode" => $language->getId(),
];
$message['body'][] = render($render_array);
$markup = entity_view($give_donation, 'receipt');
$message['body'][] = render($markup);
break;
}
}
/**
* Implements hook_theme().
*/
function give_theme($existing, $type, $theme, $path) {
return [
// Make Drupal aware of our field template for our view mode.
// @see give_theme_suggestions_field_alter().
'field__give_donation__mail' => [
'base hook' => 'field',
],
];
}
/**
* Implement hook_theme_suggestions_HOOK_alter() for fields.
*
* Provide an alternate suggestion for fields in our donation e-mail view modes.
*/
function give_theme_suggestions_field_alter(array &$suggestions, array $variables) {
// If it's not from our module, don't mess with it.
if ($variables['element']['#entity_type'] !== 'give_donation' || $variables['element']['#bundle'] !== 'donate') {
return;
}
if (in_array($variables['element']['#view_mode'], ['notice', 'receipt'], TRUE)) {
$suggestions[] = 'field__give_donation__mail';
}
}
/**
* Simple no-dependency token replacement. More robust would be better.
*/
function give_replace_donation_tokens($message, \Drupal\give\DonationInterface $donation) {
$search_replace = [
'[donor_name]' => $donation->getDonorName(),
'[donor_email]' => $donation->getDonorMail(),
'[give_label]' => $donation->getGiveForm()->label(),
'[dollar_amount]' => $donation->getDollarAmount(),
'[recurring]' => $donation->recurring() ? 'recurring ' : '',
'[recurrence]' => strtolower($donation->getRecurrence()),
'[today_date]' => strftime('%B %e, %Y'),
'[date]' => strftime('%B %e, %Y', $donation->getUpdatedTime()),
];
return str_replace(give_donation_tokens(), array_values($search_replace), $message);
}
/**
* Tokens used in simple search-replace for donation messages.
*/
function give_donation_tokens() {
return [
'[donor_name]',
'[donor_email]',
'[give_label]',
'[dollar_amount]',
'[recurring]',
'[recurrence]',
'[today_date]',
'[date]',
];
}
/**
* Default pre-created frequencies.
*/
function give_get_default_frequencies() {
return [
0 => ['interval' => 'month', 'interval_count' => '1', 'description' => 'Every month'],
1 => ['interval' => 'month', 'interval_count' => '3', 'description' => 'Every 3 months (quarterly)'],
2 => ['interval' => 'month', 'interval_count' => '6', 'description' => 'Every 6 months (semi-annually)'],
3 => ['interval' => 'month', 'interval_count' => '12', 'description' => 'Every year (annually)'],
];
}
/**
* Get the text format used for processing administrator-entered messages.
*
* Give module requires Minimal HTML module, which sets up the minimalhtml text
* format, but there's no guarantee in Drupal that a text format won't have its
* name changed or be deleted, so if necessary complain and use a fallback.
*/
function give_format() {
if (FilterFormat::load('minimalhtml')) {
return 'minimalhtml';
}
else {
\Drupal::logger('give')->error('Missing format <em>minimalhtml</em>; administrator-defined messages on the donation form and receipts may lack formatting. Make sure <a href="https://www.drupal.org/project/minimalhtml">Minimal HTML</a> module is enabled and an appropriate format called <em>minimalhtml</em> is present.');
return filter_fallback_format();
}
}