Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-11-16-01-17-32
[civicrm-core.git] / CRM / Member / Form.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 * Base class for offline membership / membership type / membership renewal and membership status forms
36 *
37 */
38 class CRM_Member_Form extends CRM_Contribute_Form_AbstractEditPayment {
39
40 /**
41 * The id of the object being edited / created
42 *
43 * @var int
44 */
45 public $_id;
46
47 /**
48 * Membership Type ID
49 * @var
50 */
51 protected $_memType;
52
53 /**
54 * Array of from email ids
55 * @var array
56 */
57 protected $_fromEmails = array();
58
59 /**
60 * Details of all enabled membership types.
61 *
62 * @var array
63 */
64 protected $allMembershipTypeDetails = array();
65
66 /**
67 * Array of membership type IDs and whether they permit autorenewal.
68 *
69 * @var array
70 */
71 protected $membershipTypeRenewalStatus = array();
72
73 /**
74 * Price set ID configured for the form.
75 *
76 * @var int
77 */
78 public $_priceSetId;
79
80 /**
81 * Price set details as an array.
82 *
83 * @var array
84 */
85 public $_priceSet;
86
87 /**
88 * Values submitted to the form, processed along the way.
89 *
90 * @var array
91 */
92 protected $_params = array();
93
94 public function preProcess() {
95 // Check for edit permission.
96 if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
97 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
98 }
99 parent::preProcess();
100 $params = array();
101 $params['context'] = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'membership');
102 $params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
103 $params['mode'] = CRM_Utils_Request::retrieve('mode', 'String', $this);
104
105 $this->setContextVariables($params);
106
107 $this->assign('context', $this->_context);
108 $this->assign('membershipMode', $this->_mode);
109 $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, array(), TRUE);
110 foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
111 if ($membershipType['auto_renew']) {
112 $this->_recurMembershipTypes[$index] = $membershipType;
113 $this->membershipTypeRenewalStatus[$index] = $membershipType['auto_renew'];
114 }
115 }
116 }
117
118 /**
119 * Set default values for the form. MobileProvider that in edit/view mode
120 * the default values are retrieved from the database
121 *
122 *
123 * @return array
124 * defaults
125 */
126 public function setDefaultValues() {
127 $defaults = array();
128 if (isset($this->_id)) {
129 $params = array('id' => $this->_id);
130 CRM_Member_BAO_Membership::retrieve($params, $defaults);
131 if (isset($defaults['minimum_fee'])) {
132 $defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
133 }
134
135 if (isset($defaults['status'])) {
136 $this->assign('membershipStatus', $defaults['status']);
137 }
138 }
139
140 if ($this->_action & CRM_Core_Action::ADD) {
141 $defaults['is_active'] = 1;
142 }
143
144 if (isset($defaults['member_of_contact_id']) &&
145 $defaults['member_of_contact_id']
146 ) {
147 $defaults['member_org'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
148 $defaults['member_of_contact_id'], 'display_name'
149 );
150 }
151 return $defaults;
152 }
153
154 /**
155 * Build the form object.
156 */
157 public function buildQuickForm() {
158
159 if ($this->_mode) {
160 $this->add('select', 'payment_processor_id',
161 ts('Payment Processor'),
162 $this->_processors, TRUE,
163 array('onChange' => "buildAutoRenew( null, this.value );")
164 );
165 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE);
166 }
167 // Build the form for auto renew. This is displayed when in credit card mode or update mode.
168 // The reason for showing it in update mode is not that clear.
169 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
170 if (!empty($this->_recurPaymentProcessors)) {
171 $this->assign('allowAutoRenew', TRUE);
172 }
173
174 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
175 NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
176 );
177 if ($this->_action & CRM_Core_Action::UPDATE) {
178 $autoRenewElement->freeze();
179 }
180
181 $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors));
182 $this->addElement('checkbox',
183 'auto_renew',
184 ts('Membership renewed automatically'),
185 NULL,
186 array('onclick' => "buildReceiptANDNotice( );")
187 );
188
189 $this->assignPaymentRelatedVariables();
190 }
191 $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
192
193 if ($this->_action & CRM_Core_Action::RENEW) {
194 $this->addButtons(array(
195 array(
196 'type' => 'upload',
197 'name' => ts('Renew'),
198 'isDefault' => TRUE,
199 ),
200 array(
201 'type' => 'cancel',
202 'name' => ts('Cancel'),
203 ),
204 )
205 );
206 }
207 elseif ($this->_action & CRM_Core_Action::DELETE) {
208 $this->addButtons(array(
209 array(
210 'type' => 'next',
211 'name' => ts('Delete'),
212 'isDefault' => TRUE,
213 ),
214 array(
215 'type' => 'cancel',
216 'name' => ts('Cancel'),
217 ),
218 )
219 );
220 }
221 else {
222 $this->addButtons(array(
223 array(
224 'type' => 'upload',
225 'name' => ts('Save'),
226 'isDefault' => TRUE,
227 ),
228 array(
229 'type' => 'upload',
230 'name' => ts('Save and New'),
231 'subName' => 'new',
232 ),
233 array(
234 'type' => 'cancel',
235 'name' => ts('Cancel'),
236 ),
237 )
238 );
239 }
240 }
241
242 /**
243 * Extract values from the contact create boxes on the form and assign appropriately to
244 *
245 * - $this->_contributorEmail,
246 * - $this->_memberEmail &
247 * - $this->_contributionName
248 * - $this->_memberName
249 * - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
250 * - $this->_contributorContactId - id of the contributor
251 * - $this->_receiptContactId
252 *
253 * If the member & contributor are the same then the values will be the same. But if different people paid
254 * then they weill differ
255 *
256 * @param array $formValues
257 * values from form. The important values we are looking for are.
258 * - contact_id
259 * - soft_credit_contact_id
260 */
261 public function storeContactFields($formValues) {
262 // in a 'standalone form' (contact id not in the url) the contact will be in the form values
263 if (!empty($formValues['contact_id'])) {
264 $this->_contactID = $formValues['contact_id'];
265 }
266
267 list($this->_memberDisplayName,
268 $this->_memberEmail
269 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
270
271 //CRM-10375 Where the payer differs to the member the payer should get the email.
272 // here we store details in order to do that
273 if (!empty($formValues['soft_credit_contact_id'])) {
274 $this->_receiptContactId = $this->_contributorContactID = $formValues['soft_credit_contact_id'];
275 list($this->_contributorDisplayName,
276 $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contributorContactID);
277 }
278 else {
279 $this->_receiptContactId = $this->_contributorContactID = $this->_contactID;
280 $this->_contributorDisplayName = $this->_memberDisplayName;
281 $this->_contributorEmail = $this->_memberEmail;
282 }
283 }
284
285 /**
286 * Set variables in a way that can be accessed from different places.
287 *
288 * This is part of refactoring for unit testability on the submit function.
289 *
290 * @param array $params
291 */
292 protected function setContextVariables($params) {
293 $variables = array(
294 'action' => '_action',
295 'context' => '_context',
296 'id' => '_id',
297 'cid' => '_contactID',
298 'mode' => '_mode',
299 );
300 foreach ($variables as $paramKey => $classVar) {
301 if (isset($params[$paramKey]) && !isset($this->$classVar)) {
302 $this->$classVar = $params[$paramKey];
303 }
304 }
305
306 if ($this->_mode) {
307 $this->assignPaymentRelatedVariables();
308 }
309
310 if ($this->_id) {
311 $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
312 $this->_membershipIDs[] = $this->_id;
313 }
314 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
315 }
316
317 /**
318 * Create a recurring contribution record.
319 *
320 * Recurring contribution parameters are set explicitly rather than merging paymentParams because it's hard
321 * to know the downstream impacts if we keep passing around the same array.
322 *
323 * @param $paymentParams
324 *
325 * @return array
326 * @throws \CiviCRM_API3_Exception
327 */
328 protected function processRecurringContribution($paymentParams) {
329 $membershipID = $paymentParams['membership_type_id'][1];
330 $contributionRecurParams = array(
331 'contact_id' => $paymentParams['contactID'],
332 'amount' => $paymentParams['total_amount'],
333 'payment_processor_id' => $paymentParams['payment_processor_id'],
334 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams),
335 'financial_type_id' => $paymentParams['financial_type_id'],
336 'is_email_receipt' => CRM_Utils_Array::value('is_email_receipt', $paymentParams),
337 // This is not great as it could also be direct debit - but is consistent with elsewhere & all need fixing.
338 'payment_instrument_id' => 1,
339 'invoice_id' => CRM_Utils_Array::value('invoiceID ', $paymentParams),
340 );
341
342 $mapping = array(
343 'frequency_interval' => 'duration_interval',
344 'frequency_unit' => 'duration_unit',
345 );
346 $membershipType = civicrm_api3('MembershipType', 'getsingle', array(
347 'id' => $membershipID,
348 'return' => $mapping,
349 ));
350
351 $returnParams = array('is_recur' => TRUE);
352 foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
353 $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
354 $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
355 }
356
357 $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
358 $returnParams['contributionRecurID'] = $contributionRecur['id'];
359 return $returnParams;
360 }
361
362 /**
363 * Ensure price parameters are set.
364 *
365 * If they are not set it means a quick config option has been chosen so we
366 * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
367 *
368 * @param array $formValues
369 */
370 protected function ensurePriceParamsAreSet(&$formValues) {
371 foreach ($formValues as $key => $value) {
372 if ((substr($key, 0, 6) == 'price_') && is_int(substr($key, 7))) {
373 return;
374 }
375 }
376 $priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
377 $formValues['membership_type_id'][0],
378 $formValues['membership_type_id'][1],
379 $formValues['total_amount'],
380 $this->_priceSetId
381 );
382 $formValues = array_merge($formValues, $priceFields['price_fields']);
383 }
384
385 /**
386 * Get the details for the selected price set.
387 *
388 * @param array $params
389 * Parameters submitted to the form.
390 *
391 * @return array
392 */
393 protected static function getPriceSetDetails($params) {
394 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
395 if ($priceSetID) {
396 return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
397 }
398 else {
399 $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
400 $priceSet = reset($priceSet);
401 return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
402 }
403 }
404
405 /**
406 * Get the selected price set id.
407 *
408 * @param array $params
409 * Parameters submitted to the form.
410 *
411 * @return int
412 */
413 protected static function getPriceSetID($params) {
414 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
415 if (!$priceSetID) {
416 $priceSetDetails = self::getPriceSetDetails($params);
417 return key($priceSetDetails);
418 }
419 return $priceSetID;
420 }
421
422 /**
423 * Store parameters relating to price sets.
424 *
425 * @param array $formValues
426 *
427 * @return array
428 */
429 protected function setPriceSetParameters($formValues) {
430 $this->_priceSetId = self::getPriceSetID($formValues);
431 $priceSetDetails = self::getPriceSetDetails($formValues);
432 $this->_priceSet = $priceSetDetails[$this->_priceSetId];
433 // process price set and get total amount and line items.
434 $this->ensurePriceParamsAreSet($formValues);
435 return $formValues;
436 }
437
438 /**
439 * Assign billing name to the template.
440 */
441 protected function assignBillingName() {
442 $name = '';
443 if (!empty($this->_params['billing_first_name'])) {
444 $name = $this->_params['billing_first_name'];
445 }
446
447 if (!empty($this->_params['billing_middle_name'])) {
448 $name .= " {$this->_params['billing_middle_name']}";
449 }
450
451 if (!empty($this->_params['billing_last_name'])) {
452 $name .= " {$this->_params['billing_last_name']}";
453 }
454 $this->assign('billingName', $name);
455 }
456
457 /**
458 * Wrapper function for unit tests.
459 *
460 * @param array $formValues
461 */
462 public function testSubmit($formValues) {
463 $this->_memType = $formValues['membership_type_id'][1];
464 $this->_params = $formValues;
465 $this->submit();
466 }
467
468 }