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