7d112472656642f29d630125d5eb4842d911361a
[civicrm-core.git] / CRM / Member / Import / Parser / Membership.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 * $Id$
33 *
34 */
35
36
37 require_once 'api/api.php';
38
39 /**
40 * class to parse membership csv files
41 */
42 class CRM_Member_Import_Parser_Membership extends CRM_Member_Import_Parser {
43
44 protected $_mapperKeys;
45
46 private $_contactIdIndex;
47 private $_totalAmountIndex;
48 private $_membershipTypeIndex;
49 private $_membershipStatusIndex;
50
51 /**
52 * Array of successfully imported membership id's
53 *
54 * @array
55 */
56 protected $_newMemberships;
57
58 /**
59 * Class constructor.
60 *
61 * @param $mapperKeys
62 * @param null $mapperLocType
63 * @param null $mapperPhoneType
64 */
65 public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
66 parent::__construct();
67 $this->_mapperKeys = &$mapperKeys;
68 }
69
70 /**
71 * The initializer code, called before the processing
72 *
73 * @return void
74 */
75 public function init() {
76 $fields = CRM_Member_BAO_Membership::importableFields($this->_contactType, FALSE);
77
78 foreach ($fields as $name => $field) {
79 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
80 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
81 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
82 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
83 }
84
85 $this->_newMemberships = array();
86
87 $this->setActiveFields($this->_mapperKeys);
88
89 // FIXME: we should do this in one place together with Form/MapField.php
90 $this->_contactIdIndex = -1;
91 $this->_membershipTypeIndex = -1;
92 $this->_membershipStatusIndex = -1;
93
94 $index = 0;
95 foreach ($this->_mapperKeys as $key) {
96 switch ($key) {
97 case 'membership_contact_id':
98 $this->_contactIdIndex = $index;
99 break;
100
101 case 'membership_type_id':
102 $this->_membershipTypeIndex = $index;
103 break;
104
105 case 'status_id':
106 $this->_membershipStatusIndex = $index;
107 break;
108 }
109 $index++;
110 }
111 }
112
113 /**
114 * Handle the values in mapField mode.
115 *
116 * @param array $values
117 * The array of values belonging to this line.
118 *
119 * @return bool
120 */
121 public function mapField(&$values) {
122 return CRM_Import_Parser::VALID;
123 }
124
125 /**
126 * Handle the values in preview mode.
127 *
128 * @param array $values
129 * The array of values belonging to this line.
130 *
131 * @return bool
132 * the result of this processing
133 */
134 public function preview(&$values) {
135 return $this->summary($values);
136 }
137
138 /**
139 * Handle the values in summary mode.
140 *
141 * @param array $values
142 * The array of values belonging to this line.
143 *
144 * @return bool
145 * the result of this processing
146 */
147 public function summary(&$values) {
148 $erroneousField = NULL;
149 $response = $this->setActiveFieldValues($values, $erroneousField);
150
151 $errorRequired = FALSE;
152
153 if ($this->_membershipTypeIndex < 0) {
154 $errorRequired = TRUE;
155 }
156 else {
157 $errorRequired = !CRM_Utils_Array::value($this->_membershipTypeIndex, $values);
158 }
159
160 if ($errorRequired) {
161 array_unshift($values, ts('Missing required fields'));
162 return CRM_Import_Parser::ERROR;
163 }
164
165 $params = $this->getActiveFieldParams();
166 $errorMessage = NULL;
167
168 //To check whether start date or join date is provided
169 if (empty($params['membership_start_date']) && empty($params['join_date'])) {
170 $errorMessage = 'Membership Start Date is required to create a memberships.';
171 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
172 }
173
174 //for date-Formats
175 $session = CRM_Core_Session::singleton();
176 $dateType = $session->get('dateTypes');
177 foreach ($params as $key => $val) {
178
179 if ($val) {
180 switch ($key) {
181 case 'join_date':
182 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
183 if (!CRM_Utils_Rule::date($params[$key])) {
184 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Member Since', $errorMessage);
185 }
186 }
187 else {
188 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Member Since', $errorMessage);
189 }
190 break;
191
192 case 'membership_start_date':
193 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
194 if (!CRM_Utils_Rule::date($params[$key])) {
195 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
196 }
197 }
198 else {
199 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
200 }
201 break;
202
203 case 'membership_end_date':
204 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
205 if (!CRM_Utils_Rule::date($params[$key])) {
206 CRM_Contact_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage);
207 }
208 }
209 else {
210 CRM_Contact_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage);
211 }
212 break;
213
214 case 'membership_type_id':
215 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
216 if (!CRM_Utils_Array::crmInArray($val, $membershipTypes) &&
217 !array_key_exists($val, $membershipTypes)
218 ) {
219 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Membership Type', $errorMessage);
220 }
221 break;
222
223 case 'status_id':
224 if (!CRM_Utils_Array::crmInArray($val, CRM_Member_PseudoConstant::membershipStatus())) {
225 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Membership Status', $errorMessage);
226 }
227 break;
228
229 case 'email':
230 if (!CRM_Utils_Rule::email($val)) {
231 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Email Address', $errorMessage);
232 }
233 }
234 }
235 }
236 //date-Format part ends
237
238 $params['contact_type'] = 'Membership';
239
240 //checking error in custom data
241 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
242
243 if ($errorMessage) {
244 $tempMsg = "Invalid value for field(s) : $errorMessage";
245 array_unshift($values, $tempMsg);
246 $errorMessage = NULL;
247 return CRM_Import_Parser::ERROR;
248 }
249
250 return CRM_Import_Parser::VALID;
251 }
252
253 /**
254 * Handle the values in import mode.
255 *
256 * @param int $onDuplicate
257 * The code for what action to take on duplicates.
258 * @param array $values
259 * The array of values belonging to this line.
260 *
261 * @return bool
262 * the result of this processing
263 */
264 public function import($onDuplicate, &$values) {
265 try {
266 // first make sure this is a valid line
267 $response = $this->summary($values);
268 if ($response != CRM_Import_Parser::VALID) {
269 return $response;
270 }
271
272 $params = $this->getActiveFieldParams();
273
274 //assign join date equal to start date if join date is not provided
275 if (empty($params['join_date']) && !empty($params['membership_start_date'])) {
276 $params['join_date'] = $params['membership_start_date'];
277 }
278
279 $session = CRM_Core_Session::singleton();
280 $dateType = $session->get('dateTypes');
281 $formatted = array();
282 $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
283
284 // don't add to recent items, CRM-4399
285 $formatted['skipRecentView'] = TRUE;
286 $dateLabels = array(
287 'join_date' => ts('Member Since'),
288 'membership_start_date' => ts('Start Date'),
289 'membership_end_date' => ts('End Date'),
290 );
291 foreach ($params as $key => $val) {
292 if ($val) {
293 switch ($key) {
294 case 'join_date':
295 case 'membership_start_date':
296 case 'membership_end_date':
297 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
298 if (!CRM_Utils_Rule::date($params[$key])) {
299 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
300 }
301 }
302 else {
303 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
304 }
305 break;
306
307 case 'membership_type_id':
308 if (!is_numeric($val)) {
309 unset($params['membership_type_id']);
310 $params['membership_type'] = $val;
311 }
312 break;
313
314 case 'status_id':
315 if (!is_numeric($val)) {
316 unset($params['status_id']);
317 $params['membership_status'] = $val;
318 }
319 break;
320
321 case 'is_override':
322 $params[$key] = CRM_Utils_String::strtobool($val);
323 break;
324 }
325 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
326 if ($customFields[$customFieldID]['data_type'] == 'Date') {
327 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
328 unset($params[$key]);
329 }
330 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
331 $params[$key] = CRM_Utils_String::strtoboolstr($val);
332 }
333 }
334 }
335 }
336 //date-Format part ends
337
338 static $indieFields = NULL;
339 if ($indieFields == NULL) {
340 $tempIndieFields = CRM_Member_DAO_Membership::import();
341 $indieFields = $tempIndieFields;
342 }
343
344 $formatValues = array();
345 foreach ($params as $key => $field) {
346 if ($field == NULL || $field === '') {
347 continue;
348 }
349
350 $formatValues[$key] = $field;
351 }
352
353 //format params to meet api v2 requirements.
354 //@todo find a way to test removing this formatting
355 $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
356
357 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
358 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
359 NULL,
360 'Membership'
361 );
362 }
363 else {
364 //fix for CRM-2219 Update Membership
365 // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
366 if (!empty($formatted['is_override']) && empty($formatted['status_id'])) {
367 array_unshift($values, 'Required parameter missing: Status');
368 return CRM_Import_Parser::ERROR;
369 }
370
371 if (!empty($formatValues['membership_id'])) {
372 $dao = new CRM_Member_BAO_Membership();
373 $dao->id = $formatValues['membership_id'];
374 $dates = array('join_date', 'start_date', 'end_date');
375 foreach ($dates as $v) {
376 if (empty($formatted[$v])) {
377 $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
378 }
379 }
380
381 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
382 $formatValues['membership_id'],
383 'Membership'
384 );
385 if ($dao->find(TRUE)) {
386 $ids = array(
387 'membership' => $formatValues['membership_id'],
388 'userId' => $session->get('userID'),
389 );
390
391 if (empty($params['line_item']) && !empty($formatted['membership_type_id'])) {
392 CRM_Price_BAO_LineItem::getLineItemArray($formatted, NULL, 'membership', $formatted['membership_type_id']);
393 }
394
395 $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
396 if (civicrm_error($newMembership)) {
397 array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
398 return CRM_Import_Parser::ERROR;
399 }
400 else {
401 $this->_newMemberships[] = $newMembership->id;
402 return CRM_Import_Parser::VALID;
403 }
404 }
405 else {
406 array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
407 return CRM_Import_Parser::ERROR;
408 }
409 }
410 }
411
412 //Format dates
413 $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d');
414 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
415 $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
416
417 if ($this->_contactIdIndex < 0) {
418
419 //retrieve contact id using contact dedupe rule
420 $formatValues['contact_type'] = $this->_contactType;
421 $formatValues['version'] = 3;
422 require_once 'CRM/Utils/DeprecatedUtils.php';
423 $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
424
425 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
426 $matchedIDs = explode(',', $error['error_message']['params'][0]);
427 if (count($matchedIDs) > 1) {
428 array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
429 return CRM_Import_Parser::ERROR;
430 }
431 else {
432 $cid = $matchedIDs[0];
433 $formatted['contact_id'] = $cid;
434
435 //fix for CRM-1924
436 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'],
437 $joinDate,
438 $startDate,
439 $endDate
440 );
441 self::formattedDates($calcDates, $formatted);
442
443 //fix for CRM-3570, exclude the statuses those having is_admin = 1
444 //now user can import is_admin if is override is true.
445 $excludeIsAdmin = FALSE;
446 if (empty($formatted['is_override'])) {
447 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
448 }
449 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
450 $endDate,
451 $joinDate,
452 'today',
453 $excludeIsAdmin,
454 $formatted['membership_type_id'],
455 $formatted
456 );
457
458 if (empty($formatted['status_id'])) {
459 $formatted['status_id'] = $calcStatus['id'];
460 }
461 elseif (empty($formatted['is_override'])) {
462 if (empty($calcStatus)) {
463 array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
464 return CRM_Import_Parser::ERROR;
465 }
466 elseif ($formatted['status_id'] != $calcStatus['id']) {
467 //Status Hold" is either NOT mapped or is FALSE
468 array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
469 return CRM_Import_Parser::ERROR;
470 }
471 }
472
473 $newMembership = civicrm_api3('membership', 'create', $formatted);
474
475 $this->_newMemberships[] = $newMembership['id'];
476 return CRM_Import_Parser::VALID;
477 }
478 }
479 else {
480 // Using new Dedupe rule.
481 $ruleParams = array(
482 'contact_type' => $this->_contactType,
483 'used' => 'Unsupervised',
484 );
485 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
486 $disp = '';
487
488 foreach ($fieldsArray as $value) {
489 if (array_key_exists(trim($value), $params)) {
490 $paramValue = $params[trim($value)];
491 if (is_array($paramValue)) {
492 $disp .= $params[trim($value)][0][trim($value)] . " ";
493 }
494 else {
495 $disp .= $params[trim($value)] . " ";
496 }
497 }
498 }
499
500 if (!empty($params['external_identifier'])) {
501 if ($disp) {
502 $disp .= "AND {$params['external_identifier']}";
503 }
504 else {
505 $disp = $params['external_identifier'];
506 }
507 }
508
509 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
510 return CRM_Import_Parser::ERROR;
511 }
512 }
513 else {
514 if (!empty($formatValues['external_identifier'])) {
515 $checkCid = new CRM_Contact_DAO_Contact();
516 $checkCid->external_identifier = $formatValues['external_identifier'];
517 $checkCid->find(TRUE);
518 if ($checkCid->id != $formatted['contact_id']) {
519 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
520 return CRM_Import_Parser::ERROR;
521 }
522 }
523
524 //to calculate dates
525 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'],
526 $joinDate,
527 $startDate,
528 $endDate
529 );
530 self::formattedDates($calcDates, $formatted);
531 //end of date calculation part
532
533 //fix for CRM-3570, exclude the statuses those having is_admin = 1
534 //now user can import is_admin if is override is true.
535 $excludeIsAdmin = FALSE;
536 if (empty($formatted['is_override'])) {
537 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
538 }
539 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
540 $endDate,
541 $joinDate,
542 'today',
543 $excludeIsAdmin,
544 $formatted['membership_type_id'],
545 $formatted
546 );
547 if (empty($formatted['status_id'])) {
548 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
549 }
550 elseif (empty($formatted['is_override'])) {
551 if (empty($calcStatus)) {
552 array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
553 return CRM_Import_Parser::ERROR;
554 }
555 elseif ($formatted['status_id'] != $calcStatus['id']) {
556 //Status Hold" is either NOT mapped or is FALSE
557 array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
558 return CRM_Import_Parser::ERROR;
559 }
560 }
561
562 $newMembership = civicrm_api3('membership', 'create', $formatted);
563
564 $this->_newMemberships[] = $newMembership['id'];
565 return CRM_Import_Parser::VALID;
566 }
567 }
568 catch (Exception $e) {
569 array_unshift($values, $e->getMessage());
570 return CRM_Import_Parser::ERROR;
571 }
572 }
573
574 /**
575 * Get the array of successfully imported membership id's
576 *
577 * @return array
578 */
579 public function &getImportedMemberships() {
580 return $this->_newMemberships;
581 }
582
583 /**
584 * The initializer code, called before the processing
585 *
586 * @return void
587 */
588 public function fini() {
589 }
590
591 /**
592 * to calculate join, start and end dates
593 *
594 * @param array $calcDates
595 * Array of dates returned by getDatesForMembershipType().
596 *
597 * @param $formatted
598 *
599 */
600 public function formattedDates($calcDates, &$formatted) {
601 $dates = array(
602 'join_date',
603 'start_date',
604 'end_date',
605 );
606
607 foreach ($dates as $d) {
608 if (isset($formatted[$d]) &&
609 !CRM_Utils_System::isNull($formatted[$d])
610 ) {
611 $formatted[$d] = CRM_Utils_Date::isoToMysql($formatted[$d]);
612 }
613 elseif (isset($calcDates[$d])) {
614 $formatted[$d] = CRM_Utils_Date::isoToMysql($calcDates[$d]);
615 }
616 }
617 }
618
619 /**
620 * @deprecated - this function formats params according to v2 standards but
621 * need to be sure about the impact of not calling it so retaining on the import class
622 * take the input parameter list as specified in the data model and
623 * convert it into the same format that we use in QF and BAO object
624 *
625 * @param array $params
626 * Associative array of property name/value.
627 * pairs to insert in new contact.
628 * @param array $values
629 * The reformatted properties that we can use internally.
630 *
631 * @param array|bool $create Is the formatted Values array going to
632 * be used for CRM_Member_BAO_Membership:create()
633 *
634 * @throws Exception
635 * @return array|error
636 */
637 public function membership_format_params($params, &$values, $create = FALSE) {
638 require_once 'api/v3/utils.php';
639 $fields = CRM_Member_DAO_Membership::fields();
640 _civicrm_api3_store_values($fields, $params, $values);
641
642 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
643
644 foreach ($params as $key => $value) {
645 // ignore empty values or empty arrays etc
646 if (CRM_Utils_System::isNull($value)) {
647 continue;
648 }
649
650 //Handling Custom Data
651 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
652 $values[$key] = $value;
653 $type = $customFields[$customFieldID]['html_type'];
654 if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
655 $mulValues = explode(',', $value);
656 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
657 $values[$key] = array();
658 foreach ($mulValues as $v1) {
659 foreach ($customOption as $customValueID => $customLabel) {
660 $customValue = $customLabel['value'];
661 if ((strtolower($customLabel['label']) == strtolower(trim($v1))) ||
662 (strtolower($customValue) == strtolower(trim($v1)))
663 ) {
664 if ($type == 'CheckBox') {
665 $values[$key][$customValue] = 1;
666 }
667 else {
668 $values[$key][] = $customValue;
669 }
670 }
671 }
672 }
673 }
674 }
675
676 switch ($key) {
677 case 'membership_contact_id':
678 if (!CRM_Utils_Rule::integer($value)) {
679 throw new Exception("contact_id not valid: $value");
680 }
681 $dao = new CRM_Core_DAO();
682 $qParams = array();
683 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
684 $qParams
685 );
686 if (!$svq) {
687 throw new Exception("Invalid Contact ID: There is no contact record with contact_id = $value.");
688 }
689 $values['contact_id'] = $values['membership_contact_id'];
690 unset($values['membership_contact_id']);
691 break;
692
693 case 'membership_type_id':
694 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
695 throw new Exception('Invalid Membership Type Id');
696 }
697 $values[$key] = $value;
698 break;
699
700 case 'membership_type':
701 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value),
702 CRM_Member_PseudoConstant::membershipType()
703 );
704 if ($membershipTypeId) {
705 if (!empty($values['membership_type_id']) &&
706 $membershipTypeId != $values['membership_type_id']
707 ) {
708 throw new Exception('Mismatched membership Type and Membership Type Id');
709 }
710 }
711 else {
712 throw new Exception('Invalid Membership Type');
713 }
714 $values['membership_type_id'] = $membershipTypeId;
715 break;
716
717 case 'status_id':
718 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
719 throw new Exception('Invalid Membership Status Id');
720 }
721 $values[$key] = $value;
722 break;
723
724 case 'membership_status':
725 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value),
726 CRM_Member_PseudoConstant::membershipStatus()
727 );
728 if ($membershipStatusId) {
729 if (!empty($values['status_id']) &&
730 $membershipStatusId != $values['status_id']
731 ) {
732 throw new Exception('Mismatched membership Status and Membership Status Id');
733 }
734 }
735 else {
736 throw new Exception('Invalid Membership Status');
737 }
738 $values['status_id'] = $membershipStatusId;
739 break;
740
741 default:
742 break;
743 }
744 }
745
746 _civicrm_api3_custom_format_params($params, $values, 'Membership');
747
748 if ($create) {
749 // CRM_Member_BAO_Membership::create() handles membership_start_date,
750 // membership_end_date and membership_source. So, if $values contains
751 // membership_start_date, membership_end_date or membership_source,
752 // convert it to start_date, end_date or source
753 $changes = array(
754 'membership_start_date' => 'start_date',
755 'membership_end_date' => 'end_date',
756 'membership_source' => 'source',
757 );
758
759 foreach ($changes as $orgVal => $changeVal) {
760 if (isset($values[$orgVal])) {
761 $values[$changeVal] = $values[$orgVal];
762 unset($values[$orgVal]);
763 }
764 }
765 }
766
767 return NULL;
768 }
769
770 }