PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.17.0
GiveWP – Donation Plugin and Fundraising Platform v4.17.0
4.17.0 4.16.9 4.16.8.1 4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 All 256 releases
give / src / FormBuilder / ViewModels / FormBuilderViewModel.php

FormBuilderViewModel.php in GiveWP – Donation Plugin and Fundraising Platform 4.17.0, at src/FormBuilder/ViewModels/FormBuilderViewModel.php

420 lines 14.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Give\FormBuilder\ViewModels;
4
5 use Give\Campaigns\Models\Campaign;
6 use Give\DonationForms\Actions\GenerateDonationFormPageUrl;
7 use Give\DonationForms\Actions\GenerateDonationFormPreviewRouteUrl;
8 use Give\DonationForms\Actions\GenerateExternalEmbedScriptUrl;
9 use Give\DonationForms\Models\DonationForm;
10 use Give\DonationForms\ValueObjects\GoalProgressType;
11 use Give\DonationForms\ValueObjects\GoalSource;
12 use Give\DonationForms\ValueObjects\GoalType;
13 use Give\Donations\Models\Donation;
14 use Give\Donations\ValueObjects\DonationMetaKeys;
15 use Give\Donors\Models\Donor;
16 use Give\Donors\ValueObjects\DonorMetaKeys;
17 use Give\FormBuilder\DataTransferObjects\EmailNotificationData;
18 use Give\FormBuilder\ValueObjects\FormBuilderRestRouteConfig;
19 use Give\Framework\FormDesigns\FormDesign;
20 use Give\Framework\FormDesigns\Registrars\FormDesignRegistrar;
21 use Give\Framework\PaymentGateways\PaymentGateway;
22 use Give\Framework\Support\Facades\Scripts\ScriptAsset;
23 use Give\Helpers\IntlTelInput;
24 use Give\Subscriptions\Models\Subscription;
25 use Give_License;
26
27 class FormBuilderViewModel
28 {
29 /**
30 * @since 4.17.0 Add externalEmbedScriptUrl key (naming the form, so the embed script carries its skeleton) to the returned array; build permalink through GenerateDonationFormPageUrl
31 * @since 4.14.0 Add countries key to the returned array
32 * @since 3.12.0 Add goalProgressOptions key to the returned array
33 * @since 3.9.0 Add support to intlTelInputSettings key in the returned array
34 * @since 3.7.0 Add support to isExcerptEnabled key in the returned array
35 * @since 3.2.0 Add nameTitlePrefixes key to the returned array
36 * @since 3.0.0
37 */
38 public function storageData(int $donationFormId): array
39 {
40 /** @var DonationForm $donationForm */
41 $donationForm = DonationForm::find($donationFormId);
42
43 return [
44 'formId' => $donationFormId,
45 'resourceURL' => rest_url(FormBuilderRestRouteConfig::NAMESPACE . '/form/' . $donationFormId),
46 'previewURL' => (new GenerateDonationFormPreviewRouteUrl())($donationFormId),
47 'externalEmbedScriptUrl' => (new GenerateExternalEmbedScriptUrl())($donationFormId),
48 'nonce' => wp_create_nonce('wp_rest'),
49 'blockData' => $donationForm->blocks->toJson(),
50 'settings' => $donationForm->settings->toJson(),
51 'currency' => give_get_currency(),
52 'formDesigns' => array_map(static function ($designClass) {
53 /** @var FormDesign $design */
54 $design = give($designClass);
55
56 return [
57 'id' => $design::id(),
58 'name' => $design::name(),
59 'isMultiStep' => $design->isMultiStep(),
60 ];
61 }, give(FormDesignRegistrar::class)->getDesigns()),
62 'formPage' => [
63 'isEnabled' => give_is_setting_enabled(give_get_option('forms_singular')),
64 // Note: Boolean values must be nested in an array to maintain boolean type, see \WP_Scripts::localize().
65 'permalink' => (new GenerateDonationFormPageUrl())($donationFormId),
66 'rewriteSlug' => get_post_type_object('give_forms')->rewrite['slug'],
67 'baseUrl' => preg_replace('/^https?:\/\//', '', site_url()),
68 ],
69 'gateways' => $this->getGateways(),
70 'gatewaySettingsUrl' => admin_url('edit.php?post_type=give_forms&page=give-settings&tab=gateways'),
71 'isRecurringEnabled' => defined('GIVE_RECURRING_VERSION') ? GIVE_RECURRING_VERSION : null,
72 'recurringAddonData' => [
73 'isInstalled' => defined('GIVE_RECURRING_VERSION'),
74 ],
75 'formFieldManagerData' => [
76 'isInstalled' => defined('GIVE_FFM_VERSION'),
77 'isLicensed' => (Give_License::get_license_by_plugin_dirname('give-form-field-manager')['license'] ?? '') === 'valid',
78 ],
79 'emailTemplateTags' => $this->getEmailTemplateTags(),
80 'emailNotifications' => array_map(static function ($notification) {
81 return EmailNotificationData::fromLegacyNotification($notification);
82 }, apply_filters('give_email_notification_options_metabox_fields', [], $donationFormId)),
83 'emailPreviewURL' => rest_url('givewp/form-builder/email-preview'),
84 'emailDefaultAddress' => get_option('admin_email'),
85 'disallowedFieldNames' => $this->getDisallowedFieldNames(),
86 'donationConfirmationTemplateTags' => $this->getDonationConfirmationPageTemplateTags(),
87 'termsAndConditions' => [
88 'checkboxLabel' => give_get_option('agree_to_terms_label'),
89 'agreementText' => give_get_option('agreement_text'),
90 ],
91 'goalTypeOptions' => $this->getGoalTypeOptions(),
92 'goalSourceOptions' => $this->getGoalSourceOptions(),
93 'goalProgressOptions' => $this->getGoalProgressOptions(),
94 'nameTitlePrefixes' => give_get_option('title_prefixes', array_values(give_get_default_title_prefixes())),
95 'isExcerptEnabled' => give_is_setting_enabled(give_get_option('forms_excerpt')),
96 'intlTelInputSettings' => IntlTelInput::getSettings(),
97 'campaignColors' => $this->getCampaignColors($donationFormId),
98 'showFormGoalNotice' => !get_user_meta(get_current_user_id(), 'givewp_campaign_form_goal_notice', true),
99 'countries' => give_get_country_list(),
100 ];
101 }
102
103 /**
104 * @since 3.0.0
105 */
106 public function isRecurringEnabled(): bool
107 {
108 return defined('GIVE_RECURRING_VERSION') && GIVE_RECURRING_VERSION;
109 }
110
111 /**
112 * @since 3.0.0
113 */
114 public function getGoalTypeOption(
115 string $value,
116 string $label,
117 string $description,
118 bool $isCurrency = false
119 ): array
120 {
121 return [
122 'value' => $value,
123 'label' => $label,
124 'description' => $description,
125 'isCurrency' => $isCurrency,
126 ];
127 }
128
129
130 /**
131 * @since 4.1.0
132 */
133 public function getGoalSourceOption(
134 string $value,
135 string $label,
136 string $description
137 ): array
138 {
139 return [
140 'value' => $value,
141 'label' => $label,
142 'description' => $description,
143 ];
144 }
145
146
147 /**
148 * @since 3.12.0
149 */
150 public function getGoalProgressOption(
151 string $value,
152 string $label,
153 string $description
154 ): array
155 {
156 return [
157 'value' => $value,
158 'label' => $label,
159 'description' => $description
160 ];
161 }
162
163
164 /**
165 * @since 3.0.0
166 */
167 public function getGoalTypeOptions(): array
168 {
169 $options = [
170 $this->getGoalTypeOption(
171 GoalType::AMOUNT,
172 __('Amount Raised', 'give'),
173 __('The total amount raised for the form', 'give'),
174 true
175 ),
176 $this->getGoalTypeOption(
177 GoalType::DONATIONS,
178 __('Number of Donations', 'give'),
179 __('The total number of donations made for the form', 'give')
180 ),
181 $this->getGoalTypeOption(
182 GoalType::DONORS,
183 __('Number of Donors', 'give'),
184 __('The total number of unique donors who have donated to the form', 'give')
185 ),
186 ];
187
188 if ($this->isRecurringEnabled()) {
189 return array_merge($options, [
190 $this->getGoalTypeOption(
191 GoalType::AMOUNT_FROM_SUBSCRIPTIONS,
192 __('Subscription Amount Raised', 'give'),
193 __('The total amount raised for the form through subscriptions', 'give'),
194 true
195 ),
196 $this->getGoalTypeOption(
197 GoalType::SUBSCRIPTIONS,
198 __('Number of Subscriptions', 'give'),
199 __('The total number of subscriptions made for the form', 'give')
200 ),
201 $this->getGoalTypeOption(
202 GoalType::DONORS_FROM_SUBSCRIPTIONS,
203 __('Number of Subscribers', 'give'),
204 __('The total number of unique donors who have donated to the form through subscriptions', 'give')
205 ),
206 ]);
207 }
208
209 return $options;
210 }
211
212 /**
213 * @since 4.1.0
214 */
215 public function getGoalSourceOptions(): array
216 {
217 return [
218 $this->getGoalTypeOption(
219 GoalSource::CAMPAIGN,
220 __('Campaign', 'give'),
221 __('The goal for this form will automatically adjust according to the campaign goal. Change campaign goal.', 'give')
222 ),
223 $this->getGoalTypeOption(
224 GoalSource::FORM,
225 __('Custom', 'give'),
226 __('Set the custom goal for this form', 'give')
227 ),
228 ];
229 }
230
231 /**
232 * @since 3.12.0
233 */
234 public function getGoalProgressOptions(): array
235 {
236 return [
237 $this->getGoalProgressOption(
238 GoalProgressType::ALL_TIME,
239 __('All time', 'give'),
240 __('Displays the goal progress for a lifetime, starting from when this form was published.', 'give')
241 ),
242 $this->getGoalProgressOption(
243 GoalProgressType::CUSTOM,
244 __('Custom', 'give'),
245 __('Displays the goal progress from the start date to the end date.', 'give')
246 )
247 ];
248 }
249
250 /**
251 * @since 3.0.0
252 */
253 public function getEmailTemplateTags(array $tags = []): array
254 {
255 return array_map(static function ($tag) {
256 $tag['id'] = $tag['tag'];
257 $tag['desc'] = html_entity_decode($tag['desc'], ENT_QUOTES);
258 $tag['description'] = html_entity_decode($tag['description'], ENT_QUOTES);
259
260 return $tag;
261 }, array_merge($tags, array_values(give()->email_tags->get_tags())));
262 }
263
264 /**
265 * @since 3.0.0
266 */
267 public function getDonationConfirmationPageTemplateTags(): array
268 {
269 $templateTags = $this->getEmailTemplateTags([
270 [
271 'tag' => 'first_name',
272 'desc' => __('The first name supplied by the donor during their donation.', 'give'),
273 'description' => __('The first name supplied by the donor during their donation.', 'give'),
274 'func' => null,
275 "context" => 'donation',
276 ],
277 [
278 'tag' => 'last_name',
279 'desc' => __('The last name supplied by the donor during their donation.', 'give'),
280 'description' => __('The last name supplied by the donor during their donation.', 'give'),
281 'func' => null,
282 "context" => 'donation',
283 ],
284 [
285 'tag' => 'email',
286 'desc' => __('The email supplied by the donor during their donation.', 'give'),
287 'description' => __('The email supplied by the donor during their donation.', 'give'),
288 'func' => null,
289 "context" => 'donation',
290 ],
291 ]);
292
293 $supportedContexts = [
294 "general",
295 "form",
296 "donation",
297 "donor",
298 "subscription",
299 ];
300
301 array_multisort($templateTags, SORT_ASC);
302
303 return array_values(
304 array_filter($templateTags, static function ($tag) use ($supportedContexts) {
305 return !empty($tag['description']) && in_array((string)$tag['context'], $supportedContexts, true);
306 })
307 );
308 }
309
310 /**
311 * @since 3.0.0
312 */
313 public function jsPathFromPluginRoot(): string
314 {
315 return GIVE_PLUGIN_URL . 'build/formBuilderApp.js';
316 }
317
318 /**
319 * @since 3.0.0
320 */
321 public function jsPathToRegistrars(): string
322 {
323 return GIVE_PLUGIN_URL . 'build/formBuilderRegistrars.js';
324 }
325
326 /**
327 * @since 3.0.0
328 */
329 public function jsRegistrarsDependencies(): array
330 {
331 return ScriptAsset::getDependencies(GIVE_PLUGIN_DIR . 'build/formBuilderRegistrars.asset.php');
332 }
333
334 /**
335 * @since 3.0.0
336 */
337 public function jsDependencies(): array
338 {
339 $dependencies = ScriptAsset::getDependencies(GIVE_PLUGIN_DIR . 'build/formBuilderApp.asset.php');
340
341 return array_merge($dependencies, ['@givewp/form-builder/registrars']);
342 }
343
344 /**
345 * @since 3.0.0
346 */
347 public function getGateways(): array
348 {
349 $enabledGateways = array_keys(give_get_option('gateways_v3', []));
350
351 $builderPaymentGatewayData = array_map(static function ($gatewayClass) use ($enabledGateways) {
352 /** @var PaymentGateway $gateway */
353 $gateway = give($gatewayClass);
354
355 return [
356 'id' => $gateway::id(),
357 'enabled' => in_array($gateway::id(), $enabledGateways, true),
358 'label' => give_get_gateway_checkout_label($gateway::id(), 3) ?? $gateway->getPaymentMethodLabel(),
359 'supportsSubscriptions' => $gateway->supportsSubscriptions(),
360 ];
361 }, give()->gateways->getPaymentGateways(3));
362
363 return array_values($builderPaymentGatewayData);
364 }
365
366 /**
367 * In the Form Builder custom fields have meta keys. These meta keys are used for both the field name and the meta,
368 * as not to be too confusing. This array is used to prevent the user from creating meta keys that conflict with the
369 * existing meta or field names.
370 *
371 * @since 4.3.2 Add country, state, city, zip, address1, and address2 to the disallowed field names.
372 * @since 3.0.0
373 */
374 protected function getDisallowedFieldNames(): array
375 {
376 $disallowedFieldNames = array_merge(
377 Donation::propertyKeys(),
378 array_values(DonationMetaKeys::toArray()),
379 Donor::propertyKeys(),
380 array_values(DonorMetaKeys::toArray()),
381 Subscription::propertyKeys(),
382 [
383 'fund_id',
384 'login',
385 'consent',
386 'donation-summary',
387 'country',
388 'state',
389 'city',
390 'zip',
391 'address1',
392 'address2',
393 ]
394 );
395
396 return array_values(array_unique($disallowedFieldNames));
397 }
398
399 /**
400 * @since 4.1.0
401 */
402 private function getCampaignColors(int $formId): array
403 {
404 /** @var Campaign $campaign */
405 $campaign = give()->campaigns->getByFormId($formId);
406
407 if ($campaign) {
408 return [
409 'primaryColor' => $campaign->primaryColor,
410 'secondaryColor' => $campaign->secondaryColor,
411 ];
412 }
413
414 return [
415 'primaryColor' => '',
416 'secondaryColor' => '',
417 ];
418 }
419 }
420