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