Fix checksum failure on editing recurring contributions
[civicrm-core.git] / CRM / Contribute / Form / UpdateBilling.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class generates form components for processing a contribution.
36 */
37 class CRM_Contribute_Form_UpdateBilling extends CRM_Contribute_Form_ContributionRecur {
38 protected $_mode = NULL;
39
40 protected $_subscriptionDetails = NULL;
41
42 protected $_selfService = FALSE;
43
44 public $_bltID = NULL;
45
46 /**
47 * Set variables up before form is built.
48 *
49 * @throws \CRM_Core_Exception
50 */
51 public function preProcess() {
52 parent::preProcess();
53 if ($this->_crid) {
54 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
55 if ($this->_subscriptionDetails->membership_id) {
56 $this->_mid = $this->_subscriptionDetails->membership_id;
57 }
58 }
59
60 if ($this->_coid) {
61 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
62 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
63 }
64
65 if ($this->_mid) {
66 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
67 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
68 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership');
69 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
70 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
71 $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
72 $this->_mode = 'auto_renew';
73 }
74
75 if ((!$this->_crid && !$this->_coid && !$this->_mid) || (!$this->_subscriptionDetails)) {
76 CRM_Core_Error::fatal('Required information missing.');
77 }
78 if (!CRM_Core_Permission::check('edit contributions')) {
79 if ($this->_subscriptionDetails->contact_id != $this->getContactID()) {
80 CRM_Core_Error::statusBounce(ts('You do not have permission to cancel subscription.'));
81 }
82 $this->_selfService = TRUE;
83 }
84
85 if (!$this->_paymentProcessor['object']->supports('updateSubscriptionBillingInfo')) {
86 CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.",
87 array(1 => $this->_paymentProcessor['object']->_processorName)
88 ));
89 }
90 $this->assign('paymentProcessor', $this->_paymentProcessor);
91
92 $this->assignBillingType();
93
94 $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
95 $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
96 $this->assign('amount', $this->_subscriptionDetails->amount);
97 $this->assign('installments', $this->_subscriptionDetails->installments);
98 $this->assign('mode', $this->_mode);
99
100 // handle context redirection
101 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
102 }
103
104 /**
105 * Set the default values of various form elements.
106 *
107 * @return array
108 * Default values
109 */
110 public function setDefaultValues() {
111 $this->_defaults = array();
112
113 if ($this->_subscriptionDetails->contact_id) {
114 $fields = array();
115 $names = array(
116 'first_name',
117 'middle_name',
118 'last_name',
119 "street_address-{$this->_bltID}",
120 "city-{$this->_bltID}",
121 "postal_code-{$this->_bltID}",
122 "country_id-{$this->_bltID}",
123 "state_province_id-{$this->_bltID}",
124 );
125 foreach ($names as $name) {
126 $fields[$name] = 1;
127 }
128 $fields["state_province-{$this->_bltID}"] = 1;
129 $fields["country-{$this->_bltID}"] = 1;
130 $fields["email-{$this->_bltID}"] = 1;
131 $fields['email-Primary'] = 1;
132
133 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_subscriptionDetails->contact_id, $fields, $this->_defaults);
134
135 // use primary email address if billing email address is empty
136 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
137 !empty($this->_defaults['email-Primary'])
138 ) {
139 $this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
140 }
141
142 foreach ($names as $name) {
143 if (!empty($this->_defaults[$name])) {
144 $this->_defaults['billing_' . $name] = $this->_defaults[$name];
145 }
146 }
147 }
148
149 $config = CRM_Core_Config::singleton();
150 // set default country from config if no country set
151 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
152 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
153 }
154
155 return $this->_defaults;
156 }
157
158 /**
159 * Build the form object.
160 */
161 public function buildQuickForm() {
162 $type = 'next';
163 if ($this->_selfService) {
164 $type = 'submit';
165 }
166
167 $this->addButtons(array(
168 array(
169 'type' => $type,
170 'name' => ts('Save'),
171 'isDefault' => TRUE,
172 ),
173 array(
174 'type' => 'cancel',
175 'name' => ts('Cancel'),
176 ),
177 ));
178
179 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, TRUE, TRUE);
180 $this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
181 }
182
183 /**
184 * Global form rule.
185 *
186 * @param array $fields
187 * The input form values.
188 * @param array $files
189 * The uploaded files if any.
190 * @param CRM_Core_Form $self
191 *
192 *
193 * @return bool|array
194 * true if no errors, else array of errors
195 */
196 public static function formRule($fields, $files, $self) {
197 $errors = array();
198 CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
199
200 // validate the payment instrument values (e.g. credit card number)
201 CRM_Core_Payment_Form::validatePaymentInstrument($self->_paymentProcessor['id'], $fields, $errors, NULL);
202
203 return empty($errors) ? TRUE : $errors;
204 }
205
206 /**
207 * Process the form.
208 */
209 public function postProcess() {
210 $params = $this->controller->exportValues($this->_name);
211 $status = NULL;
212
213 // now set the values for the billing location.
214 foreach ($this->_fields as $name => $value) {
215 $fields[$name] = 1;
216 }
217 $fields["email-{$this->_bltID}"] = 1;
218
219 $processorParams = array();
220 foreach ($params as $key => $val) {
221 $key = str_replace('billing_', '', $key);
222 list($key) = explode('-', $key);
223 $processorParams[$key] = $val;
224 }
225 $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
226 $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
227 $processorParams['month'] = $processorParams['credit_card_exp_date']['M'];
228 $processorParams['year'] = $processorParams['credit_card_exp_date']['Y'];
229 $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
230 $processorParams['amount'] = $this->_subscriptionDetails->amount;
231 $updateSubscription = $this->_paymentProcessor['object']->updateSubscriptionBillingInfo($message, $processorParams);
232 if (is_a($updateSubscription, 'CRM_Core_Error')) {
233 CRM_Core_Error::displaySessionError($updateSubscription);
234 }
235 elseif ($updateSubscription) {
236 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type');
237 $contact = &CRM_Contact_BAO_Contact::createProfileContact($params,
238 $fields,
239 $this->_subscriptionDetails->contact_id,
240 NULL,
241 NULL,
242 $ctype
243 );
244
245 // build tpl params
246 if ($this->_subscriptionDetails->membership_id) {
247 $inputParams = array('id' => $this->_subscriptionDetails->membership_id);
248 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
249 $tplParams = $tplParams[$this->_subscriptionDetails->membership_id];
250 $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
251 $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
252 $status = ts('Billing details for your automatically renewed %1 membership have been updated.',
253 array(1 => $tplParams['membershipType'])
254 );
255 $msgTitle = ts('Details Updated');
256 $msgType = 'success';
257 }
258 else {
259 $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.',
260 array(
261 1 => $this->_subscriptionDetails->amount,
262 2 => $this->_subscriptionDetails->frequency_interval,
263 3 => $this->_subscriptionDetails->frequency_unit,
264 )
265 );
266 $msgTitle = ts('Details Updated');
267 $msgType = 'success';
268
269 $tplParams = array(
270 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
271 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
272 'amount' => $this->_subscriptionDetails->amount,
273 );
274 }
275
276 // format new address for display
277 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
278 foreach ($addressParts as $part) {
279 $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams);
280 }
281 $tplParams['address'] = CRM_Utils_Address::format($addressParts);
282
283 // format old address to store in activity details
284 $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
285 $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
286 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
287 foreach ($addressParts as $part) {
288 $key = "{$part}-{$this->_bltID}";
289 $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults);
290 }
291 $this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
292
293 // format new billing name
294 $name = $processorParams['first_name'];
295 if (!empty($processorParams['middle_name'])) {
296 $name .= " {$processorParams['middle_name']}";
297 }
298 $name .= ' ' . $processorParams['last_name'];
299 $name = trim($name);
300 $tplParams['billingName'] = $name;
301
302 // format old billing name
303 $name = $this->_defaults['first_name'];
304 if (!empty($this->_defaults['middle_name'])) {
305 $name .= " {$this->_defaults['middle_name']}";
306 }
307 $name .= ' ' . $this->_defaults['last_name'];
308 $name = trim($name);
309 $this->_defaults['billingName'] = $name;
310
311 $message .= "
312 <br/><br/>New Billing Name and Address
313 <br/>==============================
314 <br/>{$tplParams['billingName']}
315 <br/>{$tplParams['address']}
316
317 <br/><br/>Previous Billing Name and Address
318 <br/>==================================
319 <br/>{$this->_defaults['billingName']}
320 <br/>{$this->_defaults['address']}";
321
322 $activityParams = array(
323 'source_contact_id' => $this->_subscriptionDetails->contact_id,
324 'activity_type_id' => CRM_Core_PseudoConstant::getKey(
325 'CRM_Activity_BAO_Activity',
326 'activity_type_id',
327 'Update Recurring Contribution Billing Details'
328 ),
329 'subject' => ts('Recurring Contribution Billing Details Updated'),
330 'details' => $message,
331 'activity_date_time' => date('YmdHis'),
332 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
333 );
334 $session = CRM_Core_Session::singleton();
335 $cid = $session->get('userID');
336 if ($cid) {
337 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
338 $activityParams['source_contact_id'] = $cid;
339 }
340 CRM_Activity_BAO_Activity::create($activityParams);
341
342 // send notification
343 if ($this->_subscriptionDetails->contribution_page_id) {
344 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
345 $this->_subscriptionDetails->contribution_page_id, $value, array(
346 'title',
347 'receipt_from_name',
348 'receipt_from_email',
349 )
350 );
351 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
352 }
353 else {
354 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
355 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
356 }
357 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
358 $tplParams['contact'] = array('display_name' => $donorDisplayName);
359
360 $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']);
361 $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date);
362 $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']);
363 $tplParams['credit_card_type'] = $processorParams['credit_card_type'];
364
365 $sendTemplateParams = array(
366 'groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
367 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing',
368 'contactId' => $this->_subscriptionDetails->contact_id,
369 'tplParams' => $tplParams,
370 'isTest' => $this->_subscriptionDetails->is_test,
371 'PDFFilename' => 'receipt.pdf',
372 'from' => $receiptFrom,
373 'toName' => $donorDisplayName,
374 'toEmail' => $donorEmail,
375 );
376 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
377 }
378 else {
379 $status = ts('There was some problem updating the billing details.');
380 $msgTitle = ts('Update Error');
381 $msgType = 'error';
382 }
383
384 $session = CRM_Core_Session::singleton();
385 $userID = $session->get('userID');
386 if ($userID && $status) {
387 $session->setStatus($status, $msgTitle, $msgType);
388 }
389 elseif (!$userID) {
390 if ($status) {
391 CRM_Utils_System::setUFMessage($status);
392 }
393 $result = (int) ($updateSubscription && isset($ctype));
394 if (isset($tplParams)) {
395 $session->set('resultParams', $tplParams);
396 }
397 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
398 "reset=1&task=billing&result={$result}"));
399 }
400 }
401
402 }