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