CRM-20786 consolidate calls to deprecated function
[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 $error = $this->checkContactDuplicate($formatValues);
419
420 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
421 $matchedIDs = explode(',', $error['error_message']['params'][0]);
422 if (count($matchedIDs) > 1) {
423 array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
424 return CRM_Import_Parser::ERROR;
425 }
426 else {
427 $cid = $matchedIDs[0];
428 $formatted['contact_id'] = $cid;
429
430 //fix for CRM-1924
431 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'],
432 $joinDate,
433 $startDate,
434 $endDate
435 );
436 self::formattedDates($calcDates, $formatted);
437
438 //fix for CRM-3570, exclude the statuses those having is_admin = 1
439 //now user can import is_admin if is override is true.
440 $excludeIsAdmin = FALSE;
441 if (empty($formatted['is_override'])) {
442 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
443 }
444 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
445 $endDate,
446 $joinDate,
447 'today',
448 $excludeIsAdmin,
449 $formatted['membership_type_id'],
450 $formatted
451 );
452
453 if (empty($formatted['status_id'])) {
454 $formatted['status_id'] = $calcStatus['id'];
455 }
456 elseif (empty($formatted['is_override'])) {
457 if (empty($calcStatus)) {
458 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.');
459 return CRM_Import_Parser::ERROR;
460 }
461 elseif ($formatted['status_id'] != $calcStatus['id']) {
462 //Status Hold" is either NOT mapped or is FALSE
463 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.');
464 return CRM_Import_Parser::ERROR;
465 }
466 }
467
468 $newMembership = civicrm_api3('membership', 'create', $formatted);
469
470 $this->_newMemberships[] = $newMembership['id'];
471 return CRM_Import_Parser::VALID;
472 }
473 }
474 else {
475 // Using new Dedupe rule.
476 $ruleParams = array(
477 'contact_type' => $this->_contactType,
478 'used' => 'Unsupervised',
479 );
480 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
481 $disp = '';
482
483 foreach ($fieldsArray as $value) {
484 if (array_key_exists(trim($value), $params)) {
485 $paramValue = $params[trim($value)];
486 if (is_array($paramValue)) {
487 $disp .= $params[trim($value)][0][trim($value)] . " ";
488 }
489 else {
490 $disp .= $params[trim($value)] . " ";
491 }
492 }
493 }
494
495 if (!empty($params['external_identifier'])) {
496 if ($disp) {
497 $disp .= "AND {$params['external_identifier']}";
498 }
499 else {
500 $disp = $params['external_identifier'];
501 }
502 }
503
504 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
505 return CRM_Import_Parser::ERROR;
506 }
507 }
508 else {
509 if (!empty($formatValues['external_identifier'])) {
510 $checkCid = new CRM_Contact_DAO_Contact();
511 $checkCid->external_identifier = $formatValues['external_identifier'];
512 $checkCid->find(TRUE);
513 if ($checkCid->id != $formatted['contact_id']) {
514 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
515 return CRM_Import_Parser::ERROR;
516 }
517 }
518
519 //to calculate dates
520 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'],
521 $joinDate,
522 $startDate,
523 $endDate
524 );
525 self::formattedDates($calcDates, $formatted);
526 //end of date calculation part
527
528 //fix for CRM-3570, exclude the statuses those having is_admin = 1
529 //now user can import is_admin if is override is true.
530 $excludeIsAdmin = FALSE;
531 if (empty($formatted['is_override'])) {
532 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
533 }
534 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
535 $endDate,
536 $joinDate,
537 'today',
538 $excludeIsAdmin,
539 $formatted['membership_type_id'],
540 $formatted
541 );
542 if (empty($formatted['status_id'])) {
543 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
544 }
545 elseif (empty($formatted['is_override'])) {
546 if (empty($calcStatus)) {
547 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.');
548 return CRM_Import_Parser::ERROR;
549 }
550 elseif ($formatted['status_id'] != $calcStatus['id']) {
551 //Status Hold" is either NOT mapped or is FALSE
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 (' . $calcStatus['name'] . '). Record was not imported.');
553 return CRM_Import_Parser::ERROR;
554 }
555 }
556
557 $newMembership = civicrm_api3('membership', 'create', $formatted);
558
559 $this->_newMemberships[] = $newMembership['id'];
560 return CRM_Import_Parser::VALID;
561 }
562 }
563 catch (Exception $e) {
564 array_unshift($values, $e->getMessage());
565 return CRM_Import_Parser::ERROR;
566 }
567 }
568
569 /**
570 * Get the array of successfully imported membership id's
571 *
572 * @return array
573 */
574 public function &getImportedMemberships() {
575 return $this->_newMemberships;
576 }
577
578 /**
579 * The initializer code, called before the processing
580 *
581 * @return void
582 */
583 public function fini() {
584 }
585
586 /**
587 * to calculate join, start and end dates
588 *
589 * @param array $calcDates
590 * Array of dates returned by getDatesForMembershipType().
591 *
592 * @param $formatted
593 *
594 */
595 public function formattedDates($calcDates, &$formatted) {
596 $dates = array(
597 'join_date',
598 'start_date',
599 'end_date',
600 );
601
602 foreach ($dates as $d) {
603 if (isset($formatted[$d]) &&
604 !CRM_Utils_System::isNull($formatted[$d])
605 ) {
606 $formatted[$d] = CRM_Utils_Date::isoToMysql($formatted[$d]);
607 }
608 elseif (isset($calcDates[$d])) {
609 $formatted[$d] = CRM_Utils_Date::isoToMysql($calcDates[$d]);
610 }
611 }
612 }
613
614 /**
615 * @deprecated - this function formats params according to v2 standards but
616 * need to be sure about the impact of not calling it so retaining on the import class
617 * take the input parameter list as specified in the data model and
618 * convert it into the same format that we use in QF and BAO object
619 *
620 * @param array $params
621 * Associative array of property name/value.
622 * pairs to insert in new contact.
623 * @param array $values
624 * The reformatted properties that we can use internally.
625 *
626 * @param array|bool $create Is the formatted Values array going to
627 * be used for CRM_Member_BAO_Membership:create()
628 *
629 * @throws Exception
630 * @return array|error
631 */
632 public function membership_format_params($params, &$values, $create = FALSE) {
633 require_once 'api/v3/utils.php';
634 $fields = CRM_Member_DAO_Membership::fields();
635 _civicrm_api3_store_values($fields, $params, $values);
636
637 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
638
639 foreach ($params as $key => $value) {
640 // ignore empty values or empty arrays etc
641 if (CRM_Utils_System::isNull($value)) {
642 continue;
643 }
644
645 //Handling Custom Data
646 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
647 $values[$key] = $value;
648 $type = $customFields[$customFieldID]['html_type'];
649 if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
650 $mulValues = explode(',', $value);
651 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
652 $values[$key] = array();
653 foreach ($mulValues as $v1) {
654 foreach ($customOption as $customValueID => $customLabel) {
655 $customValue = $customLabel['value'];
656 if ((strtolower($customLabel['label']) == strtolower(trim($v1))) ||
657 (strtolower($customValue) == strtolower(trim($v1)))
658 ) {
659 if ($type == 'CheckBox') {
660 $values[$key][$customValue] = 1;
661 }
662 else {
663 $values[$key][] = $customValue;
664 }
665 }
666 }
667 }
668 }
669 }
670
671 switch ($key) {
672 case 'membership_contact_id':
673 if (!CRM_Utils_Rule::integer($value)) {
674 throw new Exception("contact_id not valid: $value");
675 }
676 $dao = new CRM_Core_DAO();
677 $qParams = array();
678 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
679 $qParams
680 );
681 if (!$svq) {
682 throw new Exception("Invalid Contact ID: There is no contact record with contact_id = $value.");
683 }
684 $values['contact_id'] = $values['membership_contact_id'];
685 unset($values['membership_contact_id']);
686 break;
687
688 case 'membership_type_id':
689 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
690 throw new Exception('Invalid Membership Type Id');
691 }
692 $values[$key] = $value;
693 break;
694
695 case 'membership_type':
696 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value),
697 CRM_Member_PseudoConstant::membershipType()
698 );
699 if ($membershipTypeId) {
700 if (!empty($values['membership_type_id']) &&
701 $membershipTypeId != $values['membership_type_id']
702 ) {
703 throw new Exception('Mismatched membership Type and Membership Type Id');
704 }
705 }
706 else {
707 throw new Exception('Invalid Membership Type');
708 }
709 $values['membership_type_id'] = $membershipTypeId;
710 break;
711
712 case 'status_id':
713 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
714 throw new Exception('Invalid Membership Status Id');
715 }
716 $values[$key] = $value;
717 break;
718
719 case 'membership_status':
720 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value),
721 CRM_Member_PseudoConstant::membershipStatus()
722 );
723 if ($membershipStatusId) {
724 if (!empty($values['status_id']) &&
725 $membershipStatusId != $values['status_id']
726 ) {
727 throw new Exception('Mismatched membership Status and Membership Status Id');
728 }
729 }
730 else {
731 throw new Exception('Invalid Membership Status');
732 }
733 $values['status_id'] = $membershipStatusId;
734 break;
735
736 default:
737 break;
738 }
739 }
740
741 _civicrm_api3_custom_format_params($params, $values, 'Membership');
742
743 if ($create) {
744 // CRM_Member_BAO_Membership::create() handles membership_start_date,
745 // membership_end_date and membership_source. So, if $values contains
746 // membership_start_date, membership_end_date or membership_source,
747 // convert it to start_date, end_date or source
748 $changes = array(
749 'membership_start_date' => 'start_date',
750 'membership_end_date' => 'end_date',
751 'membership_source' => 'source',
752 );
753
754 foreach ($changes as $orgVal => $changeVal) {
755 if (isset($values[$orgVal])) {
756 $values[$changeVal] = $values[$orgVal];
757 unset($values[$orgVal]);
758 }
759 }
760 }
761
762 return NULL;
763 }
764
765 }