Fix checksum failure on editing recurring contributions
[civicrm-core.git] / CRM / Contribute / Form / UpdateSubscription.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
6a488035 29 * @package CRM
6b83d5bd 30 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
31 */
32
33/**
c0f62075 34 * This class generates form components generic to recurring contributions.
6a488035
TO
35 *
36 * It delegates the work to lower level subclasses and integrates the changes
37 * back in. It also uses a lot of functionality with the CRM API's, so any change
38 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
6a488035 39 */
ca809bb6 40class CRM_Contribute_Form_UpdateSubscription extends CRM_Contribute_Form_ContributionRecur {
6a488035 41
6a488035
TO
42 protected $_subscriptionDetails = NULL;
43
44 protected $_selfService = FALSE;
45
46 public $_paymentProcessor = NULL;
47
48 public $_paymentProcessorObj = NULL;
49
0c6c47a5 50 /**
51 * Fields that affect the schedule and are defined as editable by the processor.
52 *
53 * @var array
54 */
be2fb01f 55 protected $editableScheduleFields = [];
0c6c47a5 56
6a488035 57 /**
fe482240 58 * The id of the contact associated with this recurring contribution.
6a488035
TO
59 *
60 * @var int
6a488035 61 */
430ae6dd
TO
62 public $_contactID;
63
c0f62075 64 /**
65 * Pre-processing for the form.
66 *
67 * @throws \Exception
68 */
00be9182 69 public function preProcess() {
6a488035 70
1f17c8ef 71 parent::preProcess();
a0d322b1
KW
72 $this->setAction(CRM_Core_Action::UPDATE);
73
6a488035
TO
74 if ($this->_coid) {
75 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
cd3ad80e 76 // @todo test & replace with $this->_paymentProcessorObj = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
6a488035 77 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
0c6c47a5 78 $this->contributionRecurID = $this->_subscriptionDetails->recur_id;
6a488035 79 }
0c6c47a5 80 elseif ($this->contributionRecurID) {
81 $this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->contributionRecurID, 'id', 'contribution_recur_id');
8de2c073 82 }
6a488035 83
1273d77c 84 if (!$this->contributionRecurID || !$this->_subscriptionDetails) {
7bcd892a 85 CRM_Core_Error::statusBounce(ts('Required information missing.'));
6a488035
TO
86 }
87
88 if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
14b61354 89 // Add Membership details to form
be2fb01f 90 $membership = civicrm_api3('Membership', 'get', [
14b61354 91 'contribution_recur_id' => $this->contributionRecurID,
be2fb01f 92 ]);
14b61354
MW
93 if (!empty($membership['count'])) {
94 $membershipDetails = reset($membership['values']);
95 $values['membership_id'] = $membershipDetails['id'];
96 $values['membership_name'] = $membershipDetails['membership_name'];
97 }
98 $this->assign('recurMembership', $values);
99 $this->assign('contactId', $this->_subscriptionDetails->contact_id);
6a488035
TO
100 }
101
102 if (!CRM_Core_Permission::check('edit contributions')) {
a21270c0 103 if ($this->_subscriptionDetails->contact_id != $this->getContactID()) {
7bcd892a 104 CRM_Core_Error::statusBounce(ts('You do not have permission to update subscription.'));
6a488035
TO
105 }
106 $this->_selfService = TRUE;
107 }
108 $this->assign('self_service', $this->_selfService);
109
0c6c47a5 110 $this->editableScheduleFields = $this->_paymentProcessorObj->getEditableRecurringScheduleFields();
111
112 $changeHelpText = $this->_paymentProcessorObj->getRecurringScheduleUpdateHelpText();
113 if (!in_array('amount', $this->editableScheduleFields)) {
114 // Not sure if this is good behaviour - maintaining this existing behaviour for now.
115 CRM_Core_Session::setStatus($changeHelpText, ts('Warning'), 'alert');
116 }
117 else {
118 $this->assign('changeHelpText', $changeHelpText);
119 }
be2fb01f 120 $alreadyHardCodedFields = ['amount', 'installments'];
0c6c47a5 121 foreach ($this->editableScheduleFields as $editableScheduleField) {
122 if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
be2fb01f 123 $this->addField($editableScheduleField, ['entity' => 'ContributionRecur'], FALSE, FALSE);
0c6c47a5 124 }
6a488035
TO
125 }
126
0699333e
MW
127 // when custom data is included in this page
128 if (!empty($_POST['hidden_custom'])) {
129 CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'ContributionRecur', $this->contributionRecurID);
130 CRM_Custom_Form_CustomData::buildQuickForm($this);
131 CRM_Custom_Form_CustomData::setDefaultValues($this);
132 }
133
0c6c47a5 134 $this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
6a488035
TO
135
136 if ($this->_subscriptionDetails->contact_id) {
137 list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
138 }
139
140 CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
141
0c6c47a5 142 // Handle context redirection.
6a488035
TO
143 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
144 }
145
146 /**
347e061b 147 * Set default values for the form.
6a488035 148 *
347e061b 149 * Note that in edit/view mode the default values are retrieved from the database.
6a488035 150 */
00be9182 151 public function setDefaultValues() {
be2fb01f 152 $this->_defaults = [];
6a488035
TO
153 $this->_defaults['amount'] = $this->_subscriptionDetails->amount;
154 $this->_defaults['installments'] = $this->_subscriptionDetails->installments;
7083dc2a 155 $this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
467fe956 156 $this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
6a488035 157 $this->_defaults['is_notify'] = 1;
0c6c47a5 158 foreach ($this->editableScheduleFields as $field) {
0699333e 159 $this->_defaults[$field] = isset($this->_subscriptionDetails->$field) ? $this->_subscriptionDetails->$field : NULL;
0c6c47a5 160 }
6a488035
TO
161
162 return $this->_defaults;
163 }
164
165 /**
fe482240 166 * Actually build the components of the form.
6a488035
TO
167 */
168 public function buildQuickForm() {
8de2c073 169 // CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
be2fb01f 170 $amtAttr = ['size' => 20];
8de2c073 171 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
172 if (count($lineItems) > 1) {
be2fb01f 173 $amtAttr += ['readonly' => TRUE];
8de2c073 174 }
175 $this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
176 TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
6a488035
TO
177 );
178
be2fb01f 179 $this->add('text', 'installments', ts('Number of Installments'), ['size' => 20], FALSE);
6a488035
TO
180
181 if ($this->_donorEmail) {
182 $this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
183 }
184
7083dc2a 185 if (CRM_Core_Permission::check('edit contributions')) {
edb227cd 186 CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_subscriptionDetails->campaign_id);
467fe956 187 }
188
0c6c47a5 189 if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
be2fb01f 190 $this->addEntityRef('financial_type_id', ts('Financial Type'), ['entity' => 'FinancialType'], !$this->_selfService);
7083dc2a 191 }
192
0699333e
MW
193 // Add custom data
194 $this->assign('customDataType', 'ContributionRecur');
195 $this->assign('entityID', $this->contributionRecurID);
196
6a488035 197 $type = 'next';
481a74f4 198 if ($this->_selfService) {
6a488035
TO
199 $type = 'submit';
200 }
201
202 // define the buttons
be2fb01f 203 $this->addButtons([
1330f57a
SL
204 [
205 'type' => $type,
206 'name' => ts('Save'),
207 'isDefault' => TRUE,
208 ],
209 [
210 'type' => 'cancel',
211 'name' => ts('Cancel'),
212 ],
213 ]);
6a488035
TO
214 }
215
216 /**
347e061b 217 * Called after the user submits the form.
6a488035
TO
218 */
219 public function postProcess() {
220 // store the submitted values in an array
221 $params = $this->exportValues();
222
223 if ($this->_selfService && $this->_donorEmail) {
224 // for self service force notify
225 $params['is_notify'] = 1;
226 }
227
228 // if this is an update of an existing recurring contribution, pass the ID
229 $params['id'] = $this->_subscriptionDetails->recur_id;
230 $message = '';
231
232 $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
4eeb9a5b 233 $updateSubscription = TRUE;
b690491e 234 if ($this->_paymentProcessorObj->supports('changeSubscriptionAmount')) {
353ffa53 235 $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
6a488035
TO
236 }
237 if (is_a($updateSubscription, 'CRM_Core_Error')) {
353ffa53
TO
238 CRM_Core_Error::displaySessionError($updateSubscription);
239 $status = ts('Could not update the Recurring contribution details');
240 $msgTitle = ts('Update Error');
241 $msgType = 'error';
6a488035
TO
242 }
243 elseif ($updateSubscription) {
0699333e
MW
244 // Handle custom data
245 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->contributionRecurID, 'ContributionRecur');
353ffa53 246 // save the changes
0699333e 247 CRM_Contribute_BAO_ContributionRecur::add($params);
353ffa53 248 $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
be2fb01f 249 [
353ffa53
TO
250 1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
251 2 => $this->_subscriptionDetails->frequency_interval,
252 3 => $this->_subscriptionDetails->frequency_unit,
253 4 => $params['installments'],
be2fb01f 254 ]
353ffa53
TO
255 );
256
257 $msgTitle = ts('Update Success');
258 $msgType = 'success';
c6c91efc 259 $msg = ts('Recurring Contribution Updated');
353ffa53
TO
260 $contactID = $this->_subscriptionDetails->contact_id;
261
262 if ($this->_subscriptionDetails->amount != $params['amount']) {
263 $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
be2fb01f 264 [
353ffa53
TO
265 1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
266 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
be2fb01f 267 ]) . ' ';
c6c91efc 268 if ($this->_subscriptionDetails->amount < $params['amount']) {
269 $msg = ts('Recurring Contribution Updated - increased installment amount');
270 }
271 else {
272 $msg = ts('Recurring Contribution Updated - decreased installment amount');
273 }
353ffa53 274 }
6a488035 275
353ffa53 276 if ($this->_subscriptionDetails->installments != $params['installments']) {
be2fb01f 277 $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", [
1330f57a
SL
278 1 => $this->_subscriptionDetails->installments,
279 2 => $params['installments'],
280 ]) . ' ';
353ffa53 281 }
6a488035 282
be2fb01f 283 $activityParams = [
353ffa53 284 'source_contact_id' => $contactID,
12853dec 285 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Update Recurring Contribution'),
c6c91efc 286 'subject' => $msg,
353ffa53
TO
287 'details' => $message,
288 'activity_date_time' => date('YmdHis'),
12853dec 289 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
be2fb01f 290 ];
12853dec 291
353ffa53
TO
292 $session = CRM_Core_Session::singleton();
293 $cid = $session->get('userID');
6a488035 294
353ffa53
TO
295 if ($cid) {
296 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
297 $activityParams['source_contact_id'] = $cid;
298 }
299 CRM_Activity_BAO_Activity::create($activityParams);
300
301 if (!empty($params['is_notify'])) {
302 // send notification
303 if ($this->_subscriptionDetails->contribution_page_id) {
304 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
be2fb01f 305 $this->_subscriptionDetails->contribution_page_id, $value, [
353ffa53
TO
306 'title',
307 'receipt_from_name',
308 'receipt_from_email',
be2fb01f 309 ]
6a488035 310 );
353ffa53
TO
311 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
312 }
313 else {
314 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
315 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
6a488035 316 }
353ffa53
TO
317
318 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
319
be2fb01f 320 $tplParams = [
353ffa53
TO
321 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
322 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
323 'amount' => CRM_Utils_Money::format($params['amount']),
324 'installments' => $params['installments'],
be2fb01f 325 ];
353ffa53 326
be2fb01f 327 $tplParams['contact'] = ['display_name' => $donorDisplayName];
353ffa53
TO
328 $tplParams['receipt_from_email'] = $receiptFrom;
329
be2fb01f 330 $sendTemplateParams = [
353ffa53
TO
331 'groupName' => 'msg_tpl_workflow_contribution',
332 'valueName' => 'contribution_recurring_edit',
333 'contactId' => $contactID,
334 'tplParams' => $tplParams,
335 'isTest' => $this->_subscriptionDetails->is_test,
336 'PDFFilename' => 'receipt.pdf',
337 'from' => $receiptFrom,
338 'toName' => $donorDisplayName,
339 'toEmail' => $donorEmail,
be2fb01f 340 ];
353ffa53 341 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035 342 }
353ffa53 343 }
6a488035
TO
344
345 $session = CRM_Core_Session::singleton();
353ffa53 346 $userID = $session->get('userID');
481a74f4 347 if ($userID && $status) {
6a488035 348 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
0db6c3e1 349 }
4c9b6178 350 elseif (!$userID) {
317fceb4 351 if ($status) {
6a488035 352 CRM_Utils_System::setUFMessage($status);
317fceb4 353 }
6a488035
TO
354 // keep result as 1, since we not displaying anything on the redirected page anyway
355 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 356 "reset=1&task=update&result=1"));
6a488035
TO
357 }
358 }
96025800 359
6a488035 360}