Merge pull request #4979 from xurizaemon/codingstandards-12
[civicrm-core.git] / CRM / Member / Form / MembershipType.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for Membership Type
38 *
39 */
fb3082b2 40class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
6a488035
TO
41
42 /**
100fef9d 43 * Max number of contacts we will display for membership-organisation
6a488035 44 */
7da04cde 45 const MAX_CONTACTS = 50;
6a488035 46
00be9182 47 public function preProcess() {
481a74f4 48 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
6a488035
TO
49 $this->_BAOName = 'CRM_Member_BAO_MembershipType';
50 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
51 $this->assign('action', $this->_action);
52
53 $session = CRM_Core_Session::singleton();
54 $url = CRM_Utils_System::url('civicrm/admin/member/membershipType', 'reset=1');
55 $session->pushUserContext($url);
e2046b33
CW
56
57 $this->setPageTitle(ts('Membership Type'));
6a488035
TO
58 }
59
60 /**
c490a46a 61 * Set default values for the form. MobileProvider that in edit/view mode
6a488035
TO
62 * the default values are retrieved from the database
63 *
6a488035 64 *
355ba699 65 * @return void
6a488035
TO
66 */
67 public function setDefaultValues() {
68 $defaults = parent::setDefaultValues();
69
6a488035
TO
70 //finding default weight to be put
71 if (!isset($defaults['weight']) || (!$defaults['weight'])) {
72 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Member_DAO_MembershipType');
73 }
74 //setting default relationshipType
75 if (isset($defaults['relationship_type_id'])) {
76 //$defaults['relationship_type_id'] = $defaults['relationship_type_id'].'_a_b';
77 // Set values for relation type select box
78 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_type_id']);
79 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_direction']);
80 $defaults['relationship_type_id'] = array();
81 foreach ($relTypeIds as $key => $value) {
82 $defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
83 }
84 }
85
86
87 //setting default fixed_period_start_day & fixed_period_rollover_day
88 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
89 foreach ($periods as $per) {
90 if (isset($defaults[$per])) {
353ffa53 91 $date = $defaults[$per];
6a488035
TO
92
93 $defaults[$per] = array();
94 if ($date > 31) {
353ffa53 95 $date = ($date < 999) ? '0' . $date : $date;
6a488035
TO
96 $defaults[$per]['M'] = substr($date, 0, 2);
97 $defaults[$per]['d'] = substr($date, 2, 3);
98 }
99 else {
100 //special case when only day is rollover and duration is month
101 $defaults['month_fixed_period_rollover_day']['d'] = $date;
102 }
103 }
104 }
105
106 return $defaults;
107 }
108
109 /**
c490a46a 110 * Build the form object
6a488035 111 *
355ba699 112 * @return void
6a488035
TO
113 */
114 public function buildQuickForm() {
115 parent::buildQuickForm();
116
117 if ($this->_action & CRM_Core_Action::DELETE) {
118 return;
119 }
120
121 $this->applyFilter('__ALL__', 'trim');
122 $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
123
124 $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
125 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)
126 );
127 $this->add('text', 'description', ts('Description'),
128 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')
129 );
130 $this->add('text', 'minimum_fee', ts('Minimum Fee'),
131 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')
132 );
133 $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
134
2267460c 135 $this->addSelect('duration_unit', array(), TRUE);
6a488035
TO
136
137 //period type
ab5e0c41 138 $this->addSelect('period_type', array(), TRUE);
6a488035
TO
139
140 $this->add('text', 'duration_interval', ts('Duration Interval'),
141 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')
142 );
143
fc791e90
CW
144 $props = array('api' => array('params' => array('contact_type' => 'Organization')));
145 $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
6a488035
TO
146
147 //start day
148 $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'),
149 CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
150 );
151
152 //Auto-renew Option
353ffa53
TO
153 $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
154 $isAuthorize = FALSE;
155 $options = array();
6a488035
TO
156 if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
157 $isAuthorize = TRUE;
dbd82592 158 $options = CRM_Core_SelectValues::memberAutoRenew();
6a488035
TO
159 }
160
161 $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
162 $this->assign('authorize', $isAuthorize);
163
164 //rollover day
165 $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
166 CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
167 );
168 $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
169 CRM_Core_SelectValues::date(NULL, 'd'), FALSE
170 );
171
481a74f4 172 $this->add('select', 'financial_type_id', ts('Financial Type'),
ab5e0c41 173 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), TRUE, array('class' => 'crm-select2')
6a488035
TO
174 );
175
176 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
177 if (is_array($relTypeInd)) {
178 asort($relTypeInd);
179 }
180 $memberRel = &$this->add('select', 'relationship_type_id', ts('Relationship Type'),
181 array('' => ts('- select -')) + $relTypeInd);
182 $memberRel->setMultiple(TRUE);
183
764b1cdc 184 $this->addSelect('visibility', array('placeholder' => NULL, 'option_url' => NULL));
b3872345 185
6a488035
TO
186 $this->add('text', 'weight', ts('Order'),
187 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')
188 );
189 $this->add('checkbox', 'is_active', ts('Enabled?'));
190
191 $membershipRecords = FALSE;
192 if ($this->_action & CRM_Core_Action::UPDATE) {
193 $membershipType = new CRM_Member_BAO_Membership();
194 $membershipType->membership_type_id = $this->_id;
195 if ($membershipType->find(TRUE)) {
196 $membershipRecords = TRUE;
197 $memberRel->freeze();
198 }
199 }
200
201 $this->assign('membershipRecordsExists', $membershipRecords);
202
203 $this->add('text', 'max_related', ts('Max related'),
353ffa53 204 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related')
6a488035
TO
205 );
206
207 $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
208
209 $this->assign('membershipTypeId', $this->_id);
210 }
211
212 /**
100fef9d 213 * Validation
6a488035 214 *
b2363ea8
TO
215 * @param array $params
216 * (ref.) an assoc array of name/value pairs.
6a488035 217 *
72b3a70c
CW
218 * @return bool|array
219 * mixed true or array of errors
6a488035 220 */
00be9182 221 public static function formRule($params) {
6a488035
TO
222 $errors = array();
223
224 if (!$params['name']) {
225 $errors['name'] = ts('Please enter a membership type name.');
226 }
227
481a74f4 228 if (($params['minimum_fee'] > 0) && !$params['financial_type_id']) {
6c68db9f 229 $errors['financial_type_id'] = ts('Please enter the financial Type.');
6a488035
TO
230 }
231
6a488035
TO
232 if (empty($params['duration_interval']) and $params['duration_unit'] != 'lifetime') {
233 $errors['duration_interval'] = ts('Please enter a duration interval.');
234 }
235
236 if (in_array(CRM_Utils_Array::value('auto_renew', $params), array(
353ffa53
TO
237 1,
238 2
239 ))) {
6a488035
TO
240 if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
241 ($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
242 ) {
243 $errors['duration_unit'] = ts('Automatic renewals are not supported by the currently available payment processors when the membership duration is greater than 1 year / 12 months.');
244 }
245 }
246
6a488035
TO
247 if ($params['period_type'] == 'fixed' &&
248 $params['duration_unit'] == 'day'
249 ) {
250 $errors['period_type'] = ts('Period type should be Rolling when duration unit is Day');
251 }
252
253 if (($params['period_type'] == 'fixed') &&
254 ($params['duration_unit'] == 'year')
255 ) {
256 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
257 foreach ($periods as $period) {
258 $month = $params[$period]['M'];
259 $date = $params[$period]['d'];
260 if (!$month || !$date) {
261 switch ($period) {
262 case 'fixed_period_start_day':
263 $errors[$period] = ts('Please enter a valid fixed period start day');
264 break;
265
266 case 'fixed_period_rollover_day':
267 $errors[$period] = ts('Please enter a valid fixed period rollover day');
268 break;
269 }
270 }
271 }
272 }
273
274 if ($params['fixed_period_start_day'] && !empty($params['fixed_period_start_day'])) {
275 $params['fixed_period_start_day']['Y'] = date('Y');
276 if (!CRM_Utils_Rule::qfDate($params['fixed_period_start_day'])) {
277 $errors['fixed_period_start_day'] = ts('Please enter valid Fixed Period Start Day');
278 }
279 }
280
281 if ($params['fixed_period_rollover_day'] && !empty($params['fixed_period_rollover_day'])) {
282 $params['fixed_period_rollover_day']['Y'] = date('Y');
283 if (!CRM_Utils_Rule::qfDate($params['fixed_period_rollover_day'])) {
284 $errors['fixed_period_rollover_day'] = ts('Please enter valid Fixed Period Rollover Day');
285 }
286 }
287
288 return empty($errors) ? TRUE : $errors;
289 }
290
291 /**
c490a46a 292 * Process the form submission
6a488035 293 *
6a488035 294 *
355ba699 295 * @return void
6a488035
TO
296 */
297 public function postProcess() {
298 if ($this->_action & CRM_Core_Action::DELETE) {
92e4c2a5 299 try {
353ffa53 300 CRM_Member_BAO_MembershipType::del($this->_id);
dcc4f6a7 301 }
353ffa53 302 catch (CRM_Core_Exception $e) {
dcc4f6a7 303 CRM_Core_Error::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
304 }
6a488035
TO
305 CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
306 }
307 else {
308 $buttonName = $this->controller->getButtonName();
309 $submitted = $this->controller->exportValues($this->_name);
310
311 $fields = array(
312 'name',
313 'weight',
314 'is_active',
315 'member_of_contact_id',
316 'visibility',
317 'period_type',
318 'minimum_fee',
319 'description',
320 'auto_renew',
321 'duration_unit',
322 'duration_interval',
323 'financial_type_id',
324 'fixed_period_start_day',
325 'fixed_period_rollover_day',
326 'month_fixed_period_rollover_day',
21dfd5f5 327 'max_related',
6a488035
TO
328 );
329
330 $params = $ids = array();
331 foreach ($fields as $fld) {
332 $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
333 }
334
335 //clean money.
336 if ($params['minimum_fee']) {
337 $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
338 }
339
340 $hasRelTypeVal = FALSE;
341 if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
342 // To insert relation ids and directions with value separator
343 $relTypeDirs = $submitted['relationship_type_id'];
344 $relIds = $relDirection = array();
345 foreach ($relTypeDirs as $key => $value) {
346 $relationId = explode('_', $value);
347 if (count($relationId) == 3 &&
348 is_numeric($relationId[0])
349 ) {
350 $relIds[] = $relationId[0];
351 $relDirection[] = $relationId[1] . '_' . $relationId[2];
352 }
353 }
354 if (!empty($relIds)) {
355 $hasRelTypeVal = TRUE;
356 $params['relationship_type_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relIds);
357 $params['relationship_direction'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relDirection);
358 }
359 }
360 if (!$hasRelTypeVal) {
361 $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'NULL';
362 }
363
364 if ($params['duration_unit'] == 'lifetime' &&
365 empty($params['duration_interval'])
366 ) {
367 $params['duration_interval'] = 1;
368 }
369
370 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
371 foreach ($periods as $per) {
8cc574cf 372 if (!empty($params[$per]['M']) && !empty($params[$per]['d'])) {
353ffa53
TO
373 $mon = $params[$per]['M'];
374 $dat = $params[$per]['d'];
375 $mon = ($mon < 10) ? '0' . $mon : $mon;
376 $dat = ($dat < 10) ? '0' . $dat : $dat;
6a488035
TO
377 $params[$per] = $mon . $dat;
378 }
353ffa53 379 elseif ($per == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
6a488035
TO
380 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
381 unset($params['month_fixed_period_rollover_day']);
382 }
383 else {
384 $params[$per] = 'NULL';
385 }
386 }
387 $oldWeight = NULL;
388
389 if ($this->_id) {
390 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
391 $this->_id, 'weight', 'id'
392 );
393 }
394 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Member_DAO_MembershipType',
395 $oldWeight, $params['weight']
396 );
397
398 if ($this->_action & CRM_Core_Action::UPDATE) {
399 $ids['membershipType'] = $this->_id;
400 }
401
402 $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
403
404 CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.',
353ffa53
TO
405 array(1 => $membershipType->name)
406 ), ts('Saved'), 'success');
6a488035
TO
407 $session = CRM_Core_Session::singleton();
408 if ($buttonName == $this->getButtonName('upload', 'new')) {
60970bf5
DL
409 $session->replaceUserContext(
410 CRM_Utils_System::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
6a488035
TO
411 );
412 }
413 }
414 }
415
bb3a214a 416 /**
100fef9d
CW
417 * @param int $previousID
418 * @param int $priceSetId
419 * @param int $membershipTypeId
bb3a214a
EM
420 * @param $optionsIds
421 */
6975b8a7 422 public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
6a488035
TO
423 if ($previousID) {
424 $editedFieldParams = array(
425 'price_set_id ' => $priceSetId,
426 'name' => $previousID,
427 );
428 $editedResults = array();
9da8dc8c 429 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
430 if (!empty($editedResults)) {
431 $editedFieldParams = array(
432 'price_field_id' => $editedResults['id'],
433 'membership_type_id' => $membershipTypeId,
434 );
435 $editedResults = array();
9da8dc8c 436 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035
TO
437 $optionsIds['option_id'][1] = CRM_Utils_Array::value('id', $editedResults);
438 }
439 }
440 }
441}