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