Merge pull request #12801 from civicrm/5.5
[civicrm-core.git] / CRM / Member / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Explicitly declare the entity api name.
89 */
90 public function getDefaultEntity() {
91 return 'Membership';
92 }
93
94 /**
95 * @var array
96 */
97 protected $statusMessage = [];
98
99 /**
100 * Add to the status message.
101 *
102 * @param $message
103 */
104 protected function addStatusMessage($message) {
105 $this->statusMessage[] = $message;
106 }
107
108 /**
109 * Get the status message.
110 *
111 * @return string
112 */
113 protected function getStatusMessage() {
114 return implode(' ', $this->statusMessage);
115 }
116
117 /**
118 * Values submitted to the form, processed along the way.
119 *
120 * @var array
121 */
122 protected $_params = array();
123
124 public function preProcess() {
125 // Check for edit permission.
126 if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
127 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
128 }
129 if (!CRM_Member_BAO_Membership::statusAvailabilty()) {
130 // all possible statuses are disabled - redirect back to contact form
131 CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
132 }
133
134 parent::preProcess();
135 $params = array();
136 $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
137 $params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
138 $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
139
140 $this->setContextVariables($params);
141
142 $this->assign('context', $this->_context);
143 $this->assign('membershipMode', $this->_mode);
144 $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, array(), TRUE);
145 foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
146 if ($membershipType['auto_renew']) {
147 $this->_recurMembershipTypes[$index] = $membershipType;
148 $this->membershipTypeRenewalStatus[$index] = $membershipType['auto_renew'];
149 }
150 }
151 }
152
153 /**
154 * Set default values for the form. MobileProvider that in edit/view mode
155 * the default values are retrieved from the database
156 *
157 *
158 * @return array
159 * defaults
160 */
161 public function setDefaultValues() {
162 $defaults = array();
163 if (isset($this->_id)) {
164 $params = array('id' => $this->_id);
165 CRM_Member_BAO_Membership::retrieve($params, $defaults);
166 if (isset($defaults['minimum_fee'])) {
167 $defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
168 }
169
170 if (isset($defaults['status'])) {
171 $this->assign('membershipStatus', $defaults['status']);
172 }
173
174 if (!empty($defaults['is_override'])) {
175 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
176 }
177 if (!empty($defaults['status_override_end_date'])) {
178 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
179 }
180 }
181
182 if ($this->_action & CRM_Core_Action::ADD) {
183 $defaults['is_active'] = 1;
184 }
185
186 if (isset($defaults['member_of_contact_id']) &&
187 $defaults['member_of_contact_id']
188 ) {
189 $defaults['member_org'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
190 $defaults['member_of_contact_id'], 'display_name'
191 );
192 }
193 if (!empty($defaults['membership_type_id'])) {
194 $this->_memType = $defaults['membership_type_id'];
195 }
196 if (is_numeric($this->_memType)) {
197 $defaults['membership_type_id'] = array();
198 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
199 $this->_memType,
200 'member_of_contact_id',
201 'id'
202 );
203 $defaults['membership_type_id'][1] = $this->_memType;
204 }
205 else {
206 $defaults['membership_type_id'] = $this->_memType;
207 }
208 return $defaults;
209 }
210
211 /**
212 * Build the form object.
213 */
214 public function buildQuickForm() {
215 $this->assignSalesTaxMetadataToTemplate();
216
217 $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
218 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
219 // Build the form for auto renew. This is displayed when in credit card mode or update mode.
220 // The reason for showing it in update mode is not that clear.
221 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
222 if (!empty($this->_recurPaymentProcessors)) {
223 $this->assign('allowAutoRenew', TRUE);
224 }
225
226 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
227 NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
228 );
229 if ($this->_action & CRM_Core_Action::UPDATE) {
230 $autoRenewElement->freeze();
231 }
232
233 $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors));
234 $this->addElement('checkbox',
235 'auto_renew',
236 ts('Membership renewed automatically')
237 );
238
239 }
240 $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
241
242 if ($this->_action & CRM_Core_Action::RENEW) {
243 $this->addButtons(array(
244 array(
245 'type' => 'upload',
246 'name' => ts('Renew'),
247 'isDefault' => TRUE,
248 ),
249 array(
250 'type' => 'cancel',
251 'name' => ts('Cancel'),
252 ),
253 ));
254 }
255 elseif ($this->_action & CRM_Core_Action::DELETE) {
256 $this->addButtons(array(
257 array(
258 'type' => 'next',
259 'name' => ts('Delete'),
260 'isDefault' => TRUE,
261 ),
262 array(
263 'type' => 'cancel',
264 'name' => ts('Cancel'),
265 ),
266 ));
267 }
268 else {
269 $this->addButtons(array(
270 array(
271 'type' => 'upload',
272 'name' => ts('Save'),
273 'isDefault' => TRUE,
274 ),
275 array(
276 'type' => 'upload',
277 'name' => ts('Save and New'),
278 'subName' => 'new',
279 ),
280 array(
281 'type' => 'cancel',
282 'name' => ts('Cancel'),
283 ),
284 ));
285 }
286 }
287
288 /**
289 * Extract values from the contact create boxes on the form and assign appropriately to
290 *
291 * - $this->_contributorEmail,
292 * - $this->_memberEmail &
293 * - $this->_contributionName
294 * - $this->_memberName
295 * - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
296 * - $this->_contributorContactId - id of the contributor
297 * - $this->_receiptContactId
298 *
299 * If the member & contributor are the same then the values will be the same. But if different people paid
300 * then they weill differ
301 *
302 * @param array $formValues
303 * values from form. The important values we are looking for are.
304 * - contact_id
305 * - soft_credit_contact_id
306 */
307 public function storeContactFields($formValues) {
308 // in a 'standalone form' (contact id not in the url) the contact will be in the form values
309 if (!empty($formValues['contact_id'])) {
310 $this->_contactID = $formValues['contact_id'];
311 }
312
313 list($this->_memberDisplayName,
314 $this->_memberEmail
315 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
316
317 //CRM-10375 Where the payer differs to the member the payer should get the email.
318 // here we store details in order to do that
319 if (!empty($formValues['soft_credit_contact_id'])) {
320 $this->_receiptContactId = $this->_contributorContactID = $formValues['soft_credit_contact_id'];
321 list($this->_contributorDisplayName,
322 $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contributorContactID);
323 }
324 else {
325 $this->_receiptContactId = $this->_contributorContactID = $this->_contactID;
326 $this->_contributorDisplayName = $this->_memberDisplayName;
327 $this->_contributorEmail = $this->_memberEmail;
328 }
329 }
330
331 /**
332 * Set variables in a way that can be accessed from different places.
333 *
334 * This is part of refactoring for unit testability on the submit function.
335 *
336 * @param array $params
337 */
338 protected function setContextVariables($params) {
339 $variables = array(
340 'action' => '_action',
341 'context' => '_context',
342 'id' => '_id',
343 'cid' => '_contactID',
344 'mode' => '_mode',
345 );
346 foreach ($variables as $paramKey => $classVar) {
347 if (isset($params[$paramKey]) && !isset($this->$classVar)) {
348 $this->$classVar = $params[$paramKey];
349 }
350 }
351
352 if ($this->_id) {
353 $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
354 $this->_membershipIDs[] = $this->_id;
355 }
356 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
357 }
358
359 /**
360 * Create a recurring contribution record.
361 *
362 * Recurring contribution parameters are set explicitly rather than merging paymentParams because it's hard
363 * to know the downstream impacts if we keep passing around the same array.
364 *
365 * @param $paymentParams
366 *
367 * @return array
368 * @throws \CiviCRM_API3_Exception
369 */
370 protected function processRecurringContribution($paymentParams) {
371 $membershipID = $paymentParams['membership_type_id'][1];
372 $contributionRecurParams = array(
373 'contact_id' => $paymentParams['contactID'],
374 'amount' => $paymentParams['total_amount'],
375 'contribution_status_id' => 'Pending',
376 'payment_processor_id' => $paymentParams['payment_processor_id'],
377 'campaign_id' => $paymentParams['campaign_id'],
378 'financial_type_id' => $paymentParams['financial_type_id'],
379 'is_email_receipt' => $paymentParams['is_email_receipt'],
380 'payment_instrument_id' => $paymentParams['payment_instrument_id'],
381 'invoice_id' => $paymentParams['invoice_id'],
382 );
383
384 $mapping = array(
385 'frequency_interval' => 'duration_interval',
386 'frequency_unit' => 'duration_unit',
387 );
388 $membershipType = civicrm_api3('MembershipType', 'getsingle', array(
389 'id' => $membershipID,
390 'return' => $mapping,
391 ));
392
393 $returnParams = array('is_recur' => TRUE);
394 foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
395 $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
396 $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
397 }
398
399 $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
400 $returnParams['contributionRecurID'] = $contributionRecur['id'];
401 return $returnParams;
402 }
403
404 /**
405 * Ensure price parameters are set.
406 *
407 * If they are not set it means a quick config option has been chosen so we
408 * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
409 *
410 * @param array $formValues
411 */
412 protected function ensurePriceParamsAreSet(&$formValues) {
413 foreach ($formValues as $key => $value) {
414 if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
415 return;
416 }
417 }
418 $priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
419 $formValues['membership_type_id'][0],
420 $formValues['membership_type_id'][1],
421 CRM_Utils_Array::value('total_amount', $formValues),
422 $this->_priceSetId
423 );
424 $formValues = array_merge($formValues, $priceFields['price_fields']);
425 }
426
427 /**
428 * Get the details for the selected price set.
429 *
430 * @param array $params
431 * Parameters submitted to the form.
432 *
433 * @return array
434 */
435 protected static function getPriceSetDetails($params) {
436 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
437 if ($priceSetID) {
438 return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
439 }
440 else {
441 $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
442 $priceSet = reset($priceSet);
443 return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
444 }
445 }
446
447 /**
448 * Get the selected price set id.
449 *
450 * @param array $params
451 * Parameters submitted to the form.
452 *
453 * @return int
454 */
455 protected static function getPriceSetID($params) {
456 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
457 if (!$priceSetID) {
458 $priceSetDetails = self::getPriceSetDetails($params);
459 return key($priceSetDetails);
460 }
461 return $priceSetID;
462 }
463
464 /**
465 * Store parameters relating to price sets.
466 *
467 * @param array $formValues
468 *
469 * @return array
470 */
471 protected function setPriceSetParameters($formValues) {
472 $this->_priceSetId = self::getPriceSetID($formValues);
473 $priceSetDetails = self::getPriceSetDetails($formValues);
474 $this->_priceSet = $priceSetDetails[$this->_priceSetId];
475 // process price set and get total amount and line items.
476 $this->ensurePriceParamsAreSet($formValues);
477 return $formValues;
478 }
479
480 /**
481 * Wrapper function for unit tests.
482 *
483 * @param array $formValues
484 */
485 public function testSubmit($formValues) {
486 $this->setContextVariables($formValues);
487 $this->_memType = $formValues['membership_type_id'][1];
488 $this->_params = $formValues;
489 $this->submit();
490 }
491
492 }