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