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