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