CRM-13067 code tidy up - move import specific function to import class
[civicrm-core.git] / CRM / Member / Import / Parser / Membership.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
164 if (!CRM_Utils_Array::value('membership_start_date', $params) && !CRM_Utils_Array::value('join_date', $params)) {
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) {
259
260 // first make sure this is a valid line
261 $response = $this->summary($values);
a05662ef 262 if ($response != CRM_Import_Parser::VALID) {
6a488035
TO
263 return $response;
264 }
265
266 $params = &$this->getActiveFieldParams();
267
268 //assign join date equal to start date if join date is not provided
269 if (!CRM_Utils_Array::value('join_date', $params) &&
270 CRM_Utils_Array::value('membership_start_date', $params)
271 ) {
272 $params['join_date'] = $params['membership_start_date'];
273 }
274
275 $session = CRM_Core_Session::singleton();
276 $dateType = $session->get('dateTypes');
277 $formatted = array();
278 $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
279
280 // don't add to recent items, CRM-4399
281 $formatted['skipRecentView'] = TRUE;
87bbc876 282 $dateLabels = array(
283 'join_date' => ts('Member Since'),
284 'membership_start_date' => ts('Start Date'),
285 'membership_end_date' => ts('End Date'),
286 );
6a488035
TO
287 foreach ($params as $key => $val) {
288 if ($val) {
289 switch ($key) {
290 case 'join_date':
6a488035 291 case 'membership_start_date':
6a488035
TO
292 case 'membership_end_date':
293 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
294 if (!CRM_Utils_Rule::date($params[$key])) {
87bbc876 295 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
6a488035
TO
296 }
297 }
298 else {
87bbc876 299 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
6a488035
TO
300 }
301 break;
302
303 case 'membership_type_id':
304 if (!is_numeric($val)) {
305 unset($params['membership_type_id']);
306 $params['membership_type'] = $val;
307 }
308 break;
309
310 case 'status_id':
311 if (!is_numeric($val)) {
312 unset($params['status_id']);
313 $params['membership_status'] = $val;
314 }
315 break;
316
317 case 'is_override':
318 $params[$key] = CRM_Utils_String::strtobool($val);
319 break;
320 }
321 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
322 if ( $customFields[$customFieldID]['data_type'] == 'Date' ) {
719a6fec 323 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
6a488035
TO
324 unset($params[$key]);
325 } else if ( $customFields[$customFieldID]['data_type'] == 'Boolean' ) {
326 $params[$key] = CRM_Utils_String::strtoboolstr($val);
327 }
328 }
329 }
330 }
331 //date-Format part ends
332
333 static $indieFields = NULL;
334 if ($indieFields == NULL) {
335 $tempIndieFields = CRM_Member_DAO_Membership::import();
336 $indieFields = $tempIndieFields;
337 }
338
339 $formatValues = array();
340 foreach ($params as $key => $field) {
341 if ($field == NULL || $field === '') {
342 continue;
343 }
344
345 $formatValues[$key] = $field;
346 }
3c15495c 347
348 //format params to meet api v2 requirements.
349 //@todo find a way to test removing this formatting
350 $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
6a488035
TO
351
352 if ($formatError) {
353 array_unshift($values, $formatError['error_message']);
a05662ef 354 return CRM_Import_Parser::ERROR;
6a488035
TO
355 }
356
a05662ef 357 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
6a488035
TO
358 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
359 CRM_Core_DAO::$_nullObject,
360 NULL,
361 'Membership'
362 );
363 }
364 else {
365 //fix for CRM-2219 Update Membership
a05662ef 366 // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
6a488035
TO
367 if (CRM_Utils_Array::value('is_override', $formatted) &&
368 !CRM_Utils_Array::value('status_id', $formatted)
369 ) {
370 array_unshift($values, 'Required parameter missing: Status');
a05662ef 371 return CRM_Import_Parser::ERROR;
6a488035
TO
372 }
373
374 if ($formatValues['membership_id']) {
375 $dao = new CRM_Member_BAO_Membership();
376 $dao->id = $formatValues['membership_id'];
377 $dates = array('join_date', 'start_date', 'end_date');
378 foreach ($dates as $v) {
379 if (!CRM_Utils_Array::value( $v, $formatted )) {
380 $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
381 }
382 }
383
384 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
385 CRM_Core_DAO::$_nullObject,
386 $formatValues['membership_id'],
387 'Membership'
388 );
389 if ($dao->find(TRUE)) {
390 $ids = array(
391 'membership' => $formatValues['membership_id'],
392 'userId' => $session->get('userID'),
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.');
a05662ef 398 return CRM_Import_Parser::ERROR;
6a488035
TO
399 }
400 else {
401 $this->_newMemberships[] = $newMembership->id;
a05662ef 402 return CRM_Import_Parser::VALID;
6a488035
TO
403 }
404 }
405 else {
406 array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
a05662ef 407 return CRM_Import_Parser::ERROR;
6a488035
TO
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');
a05662ef 429 return CRM_Import_Parser::ERROR;
6a488035
TO
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 (!CRM_Utils_Array::value('is_override', $formatted)) {
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 );
455
456 if (!CRM_Utils_Array::value('status_id', $formatted)) {
457 $formatted['status_id'] = $calcStatus['id'];
458 }
459 elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
460 if (empty($calcStatus)) {
461 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.');
a05662ef 462 return CRM_Import_Parser::ERROR;
6a488035
TO
463 }
464 elseif ($formatted['status_id'] != $calcStatus['id']) {
465 //Status Hold" is either NOT mapped or is FALSE
466 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.');
a05662ef 467 return CRM_Import_Parser::ERROR;
6a488035
TO
468 }
469 }
470
471 $formatted['version'] = 3;
472 $newMembership = civicrm_api('membership', 'create', $formatted);
473 if (civicrm_error($newMembership)) {
474 array_unshift($values, $newMembership['error_message']);
a05662ef 475 return CRM_Import_Parser::ERROR;
6a488035
TO
476 }
477
478 $this->_newMemberships[] = $newMembership['id'];
a05662ef 479 return CRM_Import_Parser::VALID;
6a488035
TO
480 }
481 }
482 else {
483 // Using new Dedupe rule.
484 $ruleParams = array(
485 'contact_type' => $this->_contactType,
486 'used' => 'Unsupervised',
487 );
488 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
489 $disp = '';
490
491 foreach ($fieldsArray as $value) {
492 if (array_key_exists(trim($value), $params)) {
493 $paramValue = $params[trim($value)];
494 if (is_array($paramValue)) {
495 $disp .= $params[trim($value)][0][trim($value)] . " ";
496 }
497 else {
498 $disp .= $params[trim($value)] . " ";
499 }
500 }
501 }
502
503 if (CRM_Utils_Array::value('external_identifier', $params)) {
504 if ($disp) {
505 $disp .= "AND {$params['external_identifier']}";
506 }
507 else {
508 $disp = $params['external_identifier'];
509 }
510 }
511
512 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
a05662ef 513 return CRM_Import_Parser::ERROR;
6a488035
TO
514 }
515 }
516 else {
517 if (CRM_Utils_Array::value('external_identifier', $formatValues)) {
518 $checkCid = new CRM_Contact_DAO_Contact();
519 $checkCid->external_identifier = $formatValues['external_identifier'];
520 $checkCid->find(TRUE);
521 if ($checkCid->id != $formatted['contact_id']) {
522 array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
a05662ef 523 return CRM_Import_Parser::ERROR;
6a488035
TO
524 }
525 }
526
527 //to calculate dates
528 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'],
529 $joinDate,
530 $startDate,
531 $endDate
532 );
533 self::formattedDates($calcDates, $formatted);
534 //end of date calculation part
535
536 //fix for CRM-3570, exclude the statuses those having is_admin = 1
537 //now user can import is_admin if is override is true.
538 $excludeIsAdmin = FALSE;
539 if (!CRM_Utils_Array::value('is_override', $formatted)) {
540 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
541 }
542 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
543 $endDate,
544 $joinDate,
545 'today',
546 $excludeIsAdmin
547 );
548 if (!CRM_Utils_Array::value('status_id', $formatted)) {
549 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
550 }
551 elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
552 if (empty($calcStatus)) {
553 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.');
a05662ef 554 return CRM_Import_Parser::ERROR;
6a488035
TO
555 }
556 elseif ($formatted['status_id'] != $calcStatus['id']) {
557 //Status Hold" is either NOT mapped or is FALSE
558 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.');
a05662ef 559 return CRM_Import_Parser::ERROR;
6a488035
TO
560 }
561 }
562
563 $formatted['version'] = 3;
564 $newMembership = civicrm_api('membership', 'create', $formatted);
565 if (civicrm_error($newMembership)) {
566 array_unshift($values, $newMembership['error_message']);
a05662ef 567 return CRM_Import_Parser::ERROR;
6a488035
TO
568 }
569
570 $this->_newMemberships[] = $newMembership['id'];
a05662ef 571 return CRM_Import_Parser::VALID;
6a488035
TO
572 }
573 }
574
575 /**
ceb10dc7 576 * Get the array of successfully imported membership id's
6a488035
TO
577 *
578 * @return array
579 * @access public
580 */
581 function &getImportedMemberships() {
582 return $this->_newMemberships;
583 }
584
585 /**
586 * the initializer code, called before the processing
587 *
588 * @return void
589 * @access public
590 */
591 function fini() {}
592
593 /**
594 * to calculate join, start and end dates
595 *
596 * @param Array $calcDates array of dates returned by getDatesForMembershipType()
597 *
598 * @return Array formatted containing date values
599 *
600 * @access public
601 */
602 function formattedDates($calcDates, &$formatted) {
603 $dates = array(
604 'join_date',
605 'start_date',
606 'end_date',
607 );
608
609 foreach ($dates as $d) {
610 if (isset($formatted[$d]) &&
611 !CRM_Utils_System::isNull($formatted[$d])
612 ) {
613 $formatted[$d] = CRM_Utils_Date::isoToMysql($formatted[$d]);
614 }
615 elseif (isset($calcDates[$d])) {
616 $formatted[$d] = CRM_Utils_Date::isoToMysql($calcDates[$d]);
617 }
618 }
619 }
3c15495c 620 /**
621 * @deprecated - this function formats params according to v2 standards but
622 * need to be sure about the impact of not calling it so retaining on the import class
623 * take the input parameter list as specified in the data model and
624 * convert it into the same format that we use in QF and BAO object
625 *
626 * @param array $params Associative array of property name/value
627 * pairs to insert in new contact.
628 * @param array $values The reformatted properties that we can use internally
629 *
630 * @param array $create Is the formatted Values array going to
631 * be used for CRM_Member_BAO_Membership:create()
632 *
633 * @return array|error
634 * @access public
635 */
636 function membership_format_params($params, &$values, $create = FALSE) {
637 require_once 'api/v3/utils.php';
638 $fields = CRM_Member_DAO_Membership::fields();
639 _civicrm_api3_store_values($fields, $params, $values);
640
641 $customFields = CRM_Core_BAO_CustomField::getFields( 'Membership');
642
643 foreach ($params as $key => $value) {
644 // ignore empty values or empty arrays etc
645 if (CRM_Utils_System::isNull($value)) {
646 continue;
647 }
648
649 //Handling Custom Data
650 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
651 $values[$key] = $value;
652 $type = $customFields[$customFieldID]['html_type'];
653 if( $type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
654 $mulValues = explode( ',' , $value );
655 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
656 $values[$key] = array();
657 foreach( $mulValues as $v1 ) {
658 foreach($customOption as $customValueID => $customLabel) {
659 $customValue = $customLabel['value'];
660 if (( strtolower($customLabel['label']) == strtolower(trim($v1)) ) ||
661 ( strtolower($customValue) == strtolower(trim($v1)) )) {
662 if ( $type == 'CheckBox' ) {
663 $values[$key][$customValue] = 1;
664 } else {
665 $values[$key][] = $customValue;
666 }
667 }
668 }
669 }
670 }
671 }
672
673 switch ($key) {
674 case 'membership_contact_id':
675 if (!CRM_Utils_Rule::integer($value)) {
676 return civicrm_api3_create_error("contact_id not valid: $value");
677 }
678 $dao = new CRM_Core_DAO();
679 $qParams = array();
680 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
681 $qParams
682 );
683 if (!$svq) {
684 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
685 }
686 $values['contact_id'] = $values['membership_contact_id'];
687 unset($values['membership_contact_id']);
688 break;
689
690 case 'membership_type_id':
691 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
692 return civicrm_api3_create_error('Invalid Membership Type Id');
693 }
694 $values[$key] = $value;
695 break;
696
697 case 'membership_type':
698 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value),
699 CRM_Member_PseudoConstant::membershipType()
700 );
701 if ($membershipTypeId) {
702 if (CRM_Utils_Array::value('membership_type_id', $values) &&
703 $membershipTypeId != $values['membership_type_id']
704 ) {
705 return civicrm_api3_create_error('Mismatched membership Type and Membership Type Id');
706 }
707 }
708 else {
709 return civicrm_api3_create_error('Invalid Membership Type');
710 }
711 $values['membership_type_id'] = $membershipTypeId;
712 break;
713
714 case 'status_id':
715 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
716 return civicrm_api3_create_error('Invalid Membership Status Id');
717 }
718 $values[$key] = $value;
719 break;
720
721 case 'membership_status':
722 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value),
723 CRM_Member_PseudoConstant::membershipStatus()
724 );
725 if ($membershipStatusId) {
726 if (CRM_Utils_Array::value('status_id', $values) &&
727 $membershipStatusId != $values['status_id']
728 ) {
729 return civicrm_api3_create_error('Mismatched membership Status and Membership Status Id');
730 }
731 }
732 else {
733 return civicrm_api3_create_error('Invalid Membership Status');
734 }
735 $values['status_id'] = $membershipStatusId;
736 break;
737
738 default:
739 break;
740 }
741 }
742
743 _civicrm_api3_custom_format_params($params, $values, 'Membership');
744
745
746 if ($create) {
747 // CRM_Member_BAO_Membership::create() handles membership_start_date,
748 // membership_end_date and membership_source. So, if $values contains
749 // membership_start_date, membership_end_date or membership_source,
750 // convert it to start_date, end_date or source
751 $changes = array(
752 'membership_start_date' => 'start_date',
753 'membership_end_date' => 'end_date',
754 'membership_source' => 'source',
755 );
756
757 foreach ($changes as $orgVal => $changeVal) {
758 if (isset($values[$orgVal])) {
759 $values[$changeVal] = $values[$orgVal];
760 unset($values[$orgVal]);
761 }
762 }
763 }
764
765 return NULL;
766 }
6a488035
TO
767}
768