Merge pull request #4607 from samuelsov/CRM-15637
[civicrm-core.git] / CRM / Contribute / Form / UpdateBilling.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for processing a contribution
38 *
39 */
40 class 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;
50
51 /**
52 * @var array current payment processor including a copy of the object in 'object' key
53 */
54 public $_paymentProcessor = array();
55
56 public $_paymentProcessorObj = NULL;
57
58 /**
59 * Set variables up before form is built
60 *
61 * @return void
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);
70
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');
80 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
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');
86 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
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
107 if (!$this->_paymentProcessor['object']->isSupported('updateSubscriptionBillingInfo')) {
108 CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.",
109 array(1 => $this->_paymentProcessor['object']->_processorName)
110 ));
111 }
112 $this->assign('paymentProcessor', $this->_paymentProcessor);
113
114 // get the billing location type
115 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
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
132 /**
133 * This virtual function is used to set the default values of
134 * various form elements
135 *
136 * access public
137 *
138 * @return array reference to the array of default values
139 *
140 */
141 /**
142 * @return array
143 */
144 public function setDefaultValues() {
145 $this->_defaults = array();
146
147 if ($this->_subscriptionDetails->contact_id) {
148 $fields = array();
149 $names = array(
150 'first_name', 'middle_name', 'last_name', "street_address-{$this->_bltID}", "city-{$this->_bltID}",
151 "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "state_province_id-{$this->_bltID}",
152 );
153 foreach ($names as $name) {
154 $fields[$name] = 1;
155 }
156 $fields["state_province-{$this->_bltID}"] = 1;
157 $fields["country-{$this->_bltID}"] = 1;
158 $fields["email-{$this->_bltID}"] = 1;
159 $fields['email-Primary'] = 1;
160
161 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_subscriptionDetails->contact_id, $fields, $this->_defaults);
162
163 // use primary email address if billing email address is empty
164 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
165 !empty($this->_defaults['email-Primary'])
166 ) {
167 $this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
168 }
169
170 foreach ($names as $name) {
171 if (!empty($this->_defaults[$name])) {
172 $this->_defaults['billing_' . $name] = $this->_defaults[$name];
173 }
174 }
175 }
176
177 $config = CRM_Core_Config::singleton();
178 // set default country from config if no country set
179 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
180 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
181 }
182
183 return $this->_defaults;
184 }
185
186 /**
187 * Build the form object
188 *
189 * @return void
190 */
191 public function buildQuickForm() {
192 $type = 'next';
193 if ( $this->_selfService ) {
194 $type = 'submit';
195 }
196
197 $this->addButtons(array(
198 array(
199 'type' => $type,
200 'name' => ts('Save'),
201 'isDefault' => TRUE,
202 ),
203 array(
204 'type' => 'cancel',
205 'name' => ts('Cancel'),
206 ),
207 )
208 );
209
210 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor['object'], TRUE);
211 $this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
212 }
213
214 /**
215 * Global form rule
216 *
217 * @param array $fields the input form values
218 * @param array $files the uploaded files if any
219 * @param $self
220 *
221 *
222 * @return true if no errors, else array of errors
223 * @static
224 */
225 public static function formRule($fields, $files, $self) {
226 $errors = array();
227 CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
228
229 // make sure that credit card number and cvv are valid
230 CRM_Core_Payment_Form::validateCreditCard($fields, $errors);
231
232 return empty($errors) ? TRUE : $errors;
233 }
234
235 /**
236 * Process the form
237 *
238 * @return void
239 */
240 public function postProcess() {
241 $params = $this->controller->exportValues($this->_name);
242 $status = NULL;
243
244 // now set the values for the billing location.
245 foreach ($this->_fields as $name => $value) {
246 $fields[$name] = 1;
247 }
248 $fields["email-{$this->_bltID}"] = 1;
249
250 $processorParams = array();
251 foreach ($params as $key => $val) {
252 $key = str_replace('billing_', '', $key);
253 list($key) = explode('-', $key);
254 $processorParams[$key] = $val;
255 }
256 $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
257 $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
258 $processorParams['month'] = $processorParams['credit_card_exp_date']['M'];
259 $processorParams['year'] = $processorParams['credit_card_exp_date']['Y'];
260 $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
261 $processorParams['amount'] = $this->_subscriptionDetails->amount;
262
263 $updateSubscription = $this->_paymentProcessorObj->updateSubscriptionBillingInfo($message, $processorParams);
264
265 if (is_a($updateSubscription, 'CRM_Core_Error')) {
266 CRM_Core_Error::displaySessionError($updateSubscription);
267 }
268 elseif ($updateSubscription) {
269 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type');
270 $contact = &CRM_Contact_BAO_Contact::createProfileContact($params,
271 $fields,
272 $this->_subscriptionDetails->contact_id,
273 NULL,
274 NULL,
275 $ctype
276 );
277
278 // build tpl params
279 if ($this->_subscriptionDetails->membership_id) {
280 $inputParams = array('id' => $this->_subscriptionDetails->membership_id);
281 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
282 $tplParams = $tplParams[$this->_subscriptionDetails->membership_id];
283 $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
284 $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
285 $status = ts('Billing details for your automatically renewed %1 membership have been updated.',
286 array(1 => $tplParams['membershipType'])
287 );
288 $msgTitle = ts('Details Updated');
289 $msgType = 'success';
290 }
291 else {
292 $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.',
293 array(
294 1 => $this->_subscriptionDetails->amount,
295 2 => $this->_subscriptionDetails->frequency_interval,
296 3 => $this->_subscriptionDetails->frequency_unit
297 )
298 );
299 $msgTitle = ts('Details Updated');
300 $msgType = 'success';
301
302 $tplParams = array(
303 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
304 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
305 'amount' => $this->_subscriptionDetails->amount,
306 );
307 }
308
309 // format new address for display
310 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
311 foreach ($addressParts as $part) {
312 $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams);
313 }
314 $tplParams['address'] = CRM_Utils_Address::format($addressParts);
315
316 // format old address to store in activity details
317 $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
318 $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
319 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
320 foreach ($addressParts as $part) {
321 $key = "{$part}-{$this->_bltID}";
322 $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults);
323 }
324 $this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
325
326 // format new billing name
327 $name = $processorParams['first_name'];
328 if (!empty($processorParams['middle_name'])) {
329 $name .= " {$processorParams['middle_name']}";
330 }
331 $name .= ' ' . $processorParams['last_name'];
332 $name = trim($name);
333 $tplParams['billingName'] = $name;
334
335 // format old billing name
336 $name = $this->_defaults['first_name'];
337 if (!empty($this->_defaults['middle_name'])) {
338 $name .= " {$this->_defaults['middle_name']}";
339 }
340 $name .= ' ' . $this->_defaults['last_name'];
341 $name = trim($name);
342 $this->_defaults['billingName'] = $name;
343
344 $message .= "
345 <br/><br/>New Billing Name and Address
346 <br/>==============================
347 <br/>{$tplParams['billingName']}
348 <br/>{$tplParams['address']}
349
350 <br/><br/>Previous Billing Name and Address
351 <br/>==================================
352 <br/>{$this->_defaults['billingName']}
353 <br/>{$this->_defaults['address']}";
354
355 $activityParams = array(
356 'source_contact_id' => $this->_subscriptionDetails->contact_id,
357 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
358 'Update Recurring Contribution Billing Details',
359 'name'
360 ),
361 'subject' => ts('Recurring Contribution Billing Details Updated'),
362 'details' => $message,
363 'activity_date_time' => date('YmdHis'),
364 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
365 'Completed',
366 'name'
367 ),
368 );
369 $session = CRM_Core_Session::singleton();
370 $cid = $session->get('userID');
371 if ($cid) {
372 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
373 $activityParams['source_contact_id'] = $cid;
374 }
375 CRM_Activity_BAO_Activity::create($activityParams);
376
377 // send notification
378 if ($this->_subscriptionDetails->contribution_page_id) {
379 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
380 $this->_subscriptionDetails->contribution_page_id, $value, array(
381 'title',
382 'receipt_from_name',
383 'receipt_from_email',
384 )
385 );
386 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
387 }
388 else {
389 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
390 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
391 }
392 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
393 $tplParams['contact'] = array('display_name' => $donorDisplayName);
394
395 $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']);
396 $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date);
397 $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']);
398 $tplParams['credit_card_type'] = $processorParams['credit_card_type'];
399
400 $sendTemplateParams = array(
401 'groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
402 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing',
403 'contactId' => $this->_subscriptionDetails->contact_id,
404 'tplParams' => $tplParams,
405 'isTest' => $this->_subscriptionDetails->is_test,
406 'PDFFilename' => 'receipt.pdf',
407 'from' => $receiptFrom,
408 'toName' => $donorDisplayName,
409 'toEmail' => $donorEmail,
410 );
411 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
412 }
413 else {
414 $status = ts('There was some problem updating the billing details.');
415 $msgTitle = ts('Update Error');
416 $msgType = 'error';
417 }
418
419 $session = CRM_Core_Session::singleton();
420 $userID = $session->get('userID');
421 if ( $userID && $status) {
422 $session->setStatus($status, $msgTitle, $msgType);
423 } else if (!$userID) {
424 if ($status)
425 CRM_Utils_System::setUFMessage($status);
426 $result = (int) ($updateSubscription && isset($ctype));
427 if (isset($tplParams))
428 $session->set('resultParams', $tplParams);
429 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
430 "reset=1&task=billing&result={$result}"));
431 }
432 }
433 }