/**
  * Combine all the importable fields from the lower levels object.
  *
  * @param string $contactType
  * @param bool $status
  * @param bool $onlyParticipant
  * @param bool $checkPermission
  *   Is this a permissioned retrieval?
  *
  * @return array
  *   array of importable Fields
  */
 public static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE, $checkPermission = TRUE)
 {
     if (!self::$_importableFields) {
         if (!$onlyParticipant) {
             if (!$status) {
                 $fields = array('' => array('title' => ts('- do not import -')));
             } else {
                 $fields = array('' => array('title' => ts('- Participant Fields -')));
             }
         } else {
             $fields = array();
         }
         $tmpFields = CRM_Event_DAO_Participant::import();
         $note = array('participant_note' => array('title' => ts('Participant Note'), 'name' => 'participant_note', 'headerPattern' => '/(participant.)?note$/i'));
         // Split status and status id into 2 fields
         // Fixme: it would be better to leave as 1 field and intelligently handle both during import
         $participantStatus = array('participant_status' => array('title' => ts('Participant Status'), 'name' => 'participant_status', 'data_type' => CRM_Utils_Type::T_STRING));
         $tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
         // Split role and role id into 2 fields
         // Fixme: it would be better to leave as 1 field and intelligently handle both during import
         $participantRole = array('participant_role' => array('title' => ts('Participant Role'), 'name' => 'participant_role', 'data_type' => CRM_Utils_Type::T_STRING));
         $tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
         $eventType = array('event_type' => array('title' => ts('Event Type'), 'name' => 'event_type', 'data_type' => CRM_Utils_Type::T_STRING));
         $tmpContactField = $contactFields = array();
         $contactFields = array();
         if (!$onlyParticipant) {
             $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             if (is_array($fieldsArray)) {
                 foreach ($fieldsArray as $value) {
                     $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                     $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                     $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                     if (!$status) {
                         $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
                     } else {
                         $title = $tmpContactField[trim($value)]['title'];
                     }
                     $tmpContactField[trim($value)]['title'] = $title;
                 }
             }
         }
         $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
         if ($extIdentifier) {
             $tmpContactField['external_identifier'] = $extIdentifier;
             $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
         }
         $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant', FALSE, FALSE, FALSE, $checkPermission));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #2
0
 /**
  * combine all the importable fields from the lower levels object
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important and should be done in the
  * next week or so, before this can be called complete.
  *
  * @param NULL
  * 
  * @return array    array of importable Fields
  * @access public
  */
 function &importableFields()
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => ts('- do not import -')));
         } else {
             $fields = array('' => array('title' => ts('- Activity Fields -')));
         }
         require_once 'CRM/Activity/DAO/Activity.php';
         $tmpFields = CRM_Activity_DAO_Activity::import();
         require_once 'CRM/Contact/BAO/Contact.php';
         $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', null);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => 'Individual', 'level' => 'Strict');
         require_once 'CRM/Dedupe/BAO/Rule.php';
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpConatctField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
                 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
             }
         }
         $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
         $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
         $fields = array_merge($fields, $tmpConatctField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #3
0
 /**
  * Combine all the importable fields from the lower levels object.
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important and should be done in the
  * next week or so, before this can be called complete.
  *
  * @param string $contactType
  * @param bool $status
  *
  * @return array
  *   array of importable Fields
  */
 public static function &importableFields($contactType = 'Individual', $status = TRUE)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => ts('- do not import -')));
         } else {
             $fields = array('' => array('title' => ts('- Contribution Fields -')));
         }
         $note = CRM_Core_DAO_Note::import();
         $tmpFields = CRM_Contribute_DAO_Contribution::import();
         unset($tmpFields['option_value']);
         $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
         $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpContactField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 //skip if there is no dupe rule
                 if ($value == 'none') {
                     continue;
                 }
                 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                 $tmpContactField[trim($value)] = $contactFields[trim($value)];
                 if (!$status) {
                     $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
                 } else {
                     $title = $tmpContactField[trim($value)]['title'];
                 }
                 $tmpContactField[trim($value)]['title'] = $title;
             }
         }
         $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
         $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
         $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, $note);
         $fields = array_merge($fields, $optionFields);
         $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
 /**
  * combine all the importable fields from the lower levels object
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important and should be done in the
  * next week or so, before this can be called complete.
  *
  * @return array array of importable Fields
  * @access public
  */
 function &importableFields($contacType = 'Individual', $status = true)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => ts('- do not import -')));
         } else {
             $fields = array('' => array('title' => ts('- Contribution Fields -')));
         }
         require_once 'CRM/Core/DAO/Note.php';
         $note = CRM_Core_DAO_Note::import();
         $tmpFields = CRM_Contribute_DAO_Contribution::import();
         unset($tmpFields['option_value']);
         require_once 'CRM/Core/OptionValue.php';
         $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
         require_once 'CRM/Contact/BAO/Contact.php';
         $contactFields = CRM_Contact_BAO_Contact::importableFields($contacType, null);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => $contacType, 'level' => 'Strict');
         require_once 'CRM/Dedupe/BAO/Rule.php';
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpConatctField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 //skip if there is no dupe rule
                 if ($value == 'none') {
                     continue;
                 }
                 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
                 if (!$status) {
                     $title = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
                 } else {
                     $title = $tmpConatctField[trim($value)]['title'];
                 }
                 $tmpConatctField[trim($value)]['title'] = $title;
             }
         }
         $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
         $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
         $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . " (match to contact)";
         $fields = array_merge($fields, $tmpConatctField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, $note);
         $fields = array_merge($fields, $optionFields);
         require_once 'CRM/Contribute/DAO/ContributionType.php';
         $fields = array_merge($fields, CRM_Contribute_DAO_ContributionType::export());
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
Beispiel #6
0
 function preProcess()
 {
     if (!CRM_Core_Permission::check('merge duplicate contacts')) {
         CRM_Core_Error::fatal(ts('You do not have access to this page'));
     }
     $rows = array();
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
     $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
     $this->_rgid = $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
     $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
     $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
     if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
         CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href=\'%1\'>Dedupe Exceptions</a> page.', array(1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1'))));
     }
     //load cache mechanism
     $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'contact_type');
     $cacheKey = "merge {$contactType}";
     $cacheKey .= $rgid ? "_{$rgid}" : '_0';
     $cacheKey .= $gid ? "_{$gid}" : '_0';
     $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND\n                                                             pn.entity_id2 = de.contact_id2 )";
     $where = "de.id IS NULL";
     $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
     // Block access if user does not have EDIT permissions for both contacts.
     if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT))) {
         CRM_Utils_System::permissionDenied();
     }
     // get user info of main contact.
     $config = CRM_Core_Config::singleton();
     $config->doNotResetCache = 1;
     $viewUser = CRM_Core_Permission::check('access user profiles');
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
         $this->assign('mainUfId', $mainUfId);
         $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
     }
     $flipUrl = CRM_Utils_System::url('civicrm/contact/merge', "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$rgid}&gid={$gid}");
     if (!$flip) {
         $flipUrl .= '&flip=1';
     }
     $this->assign('flip', $flipUrl);
     $this->prev = $this->next = NULL;
     foreach (array('prev', 'next') as $position) {
         if (!empty($pos[$position])) {
             if ($pos[$position]['id1'] && $pos[$position]['id2']) {
                 $urlParam = "reset=1&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
                 if ($rgid) {
                     $urlParam .= "&rgid={$rgid}";
                 }
                 if ($gid) {
                     $urlParam .= "&gid={$gid}";
                 }
                 $this->{$position} = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
                 $this->assign($position, $this->{$position});
             }
         }
     }
     // get user info of other contact.
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
         $this->assign('otherUfId', $otherUfId);
         $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
     }
     $cmsUser = $mainUfId && $otherUfId ? TRUE : FALSE;
     $this->assign('user', $cmsUser);
     $session = CRM_Core_Session::singleton();
     // context fixed.
     if ($rgid) {
         $urlParam = "reset=1&action=browse&rgid={$rgid}";
         if ($gid) {
             $urlParam .= "&gid={$gid}";
         }
         $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParam));
     }
     // ensure that oid is not the current user, if so refuse to do the merge
     if ($session->get('userID') == $oid) {
         $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
         $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name));
         CRM_Core_Error::statusBounce($message);
     }
     $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($cid, $oid);
     $main =& $rowsElementsAndInfo['main_details'];
     $other =& $rowsElementsAndInfo['other_details'];
     if ($main['contact_id'] != $cid) {
         CRM_Core_Error::fatal(ts('The main contact record does not exist'));
     }
     if ($other['contact_id'] != $oid) {
         CRM_Core_Error::fatal(ts('The other contact record does not exist'));
     }
     $subtypes = CRM_Contact_BAO_ContactType::subTypePairs(NULL, TRUE, '');
     $this->assign('contact_type', $main['contact_type']);
     if (!empty($main['contact_sub_type'])) {
         $this->assign('main_contact_subtype', CRM_Utils_Array::value('contact_sub_type', $subtypes[$main['contact_sub_type'][0]]));
     }
     if (!empty($other['contact_sub_type'])) {
         $this->assign('other_contact_subtype', CRM_Utils_Array::value('contact_sub_type', $subtypes[$other['contact_sub_type'][0]]));
     }
     $this->assign('main_name', $main['display_name']);
     $this->assign('other_name', $other['display_name']);
     $this->assign('main_cid', $main['contact_id']);
     $this->assign('other_cid', $other['contact_id']);
     $this->assign('rgid', $rgid);
     $this->_cid = $cid;
     $this->_oid = $oid;
     $this->_rgid = $rgid;
     $this->_contactType = $main['contact_type'];
     $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('onclick' => "return toggleCheckboxVals('move_',this);"));
     $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_loc_block']));
     $this->assign('rows', $rowsElementsAndInfo['rows']);
     $this->_locBlockIds = array('main' => $rowsElementsAndInfo['main_details']['loc_block_ids'], 'other' => $rowsElementsAndInfo['other_details']['loc_block_ids']);
     // add elements
     foreach ($rowsElementsAndInfo['elements'] as $element) {
         $this->addElement($element[0], $element[1], array_key_exists('2', $element) ? $element[2] : NULL, array_key_exists('3', $element) ? $element[3] : NULL, array_key_exists('4', $element) ? $element[4] : NULL, array_key_exists('5', $element) ? $element[5] : NULL);
     }
     // add related table elements
     foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
         $element = $this->addElement($relTableElement[0], $relTableElement[1]);
         $element->setChecked(TRUE);
     }
     $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
     $this->assign('userContextURL', $session->readUserContext());
 }
 /**
  * combine all the importable fields from the lower levels object
  *
  * @return array array of importable Fields
  * @access public
  * @static
  */
 static function &importableFields($contactType = 'Individual', $status = TRUE, $onlyParticipant = FALSE)
 {
     if (!self::$_importableFields) {
         if (!$onlyParticipant) {
             if (!$status) {
                 $fields = array('' => array('title' => ts('- do not import -')));
             } else {
                 $fields = array('' => array('title' => ts('- Participant Fields -')));
             }
         } else {
             $fields = array();
         }
         $tmpFields = CRM_Event_DAO_Participant::import();
         $note = array('participant_note' => array('title' => 'Participant Note', 'name' => 'participant_note', 'headerPattern' => '/(participant.)?note$/i'));
         $participantStatus = array('participant_status' => array('title' => 'Participant Status', 'name' => 'participant_status', 'data_type' => CRM_Utils_Type::T_STRING));
         $participantRole = array('participant_role' => array('title' => 'Participant Role', 'name' => 'participant_role', 'data_type' => CRM_Utils_Type::T_STRING));
         $eventType = array('event_type' => array('title' => 'Event Type', 'name' => 'event_type', 'data_type' => CRM_Utils_Type::T_STRING));
         $tmpContactField = $contactFields = array();
         $contactFields = array();
         if (!$onlyParticipant) {
             $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $contactType, 'level' => 'Strict');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             if (is_array($fieldsArray)) {
                 foreach ($fieldsArray as $value) {
                     $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                     $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                     $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                     if (!$status) {
                         $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
                     } else {
                         $title = $tmpContactField[trim($value)]['title'];
                     }
                     $tmpContactField[trim($value)]['title'] = $title;
                 }
             }
         }
         $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
         if ($extIdentifier) {
             $tmpContactField['external_identifier'] = $extIdentifier;
             $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
         }
         $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . ' (match to contact)';
         //campaign fields.
         if (isset($tmpFields['participant_campaign_id'])) {
             $tmpFields['participant_campaign'] = array('title' => ts('Campaign Title'));
         }
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
         //$fields = array_merge($fields, $optionFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #8
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Member_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //assign join date equal to start date if join date is not provided
     if (!$params['join_date'] && $params['membership_start_date']) {
         $params['join_date'] = $params['membership_start_date'];
     }
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'join_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                     }
                     break;
                 case 'membership_start_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                     }
                     break;
                 case 'membership_end_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                     }
                     break;
                 case 'is_override':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID][2] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID][2] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Member/DAO/Membership.php';
         $tempIndieFields =& CRM_Member_DAO_Membership::import();
         $indieFields = $tempIndieFields;
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Member_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Member_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Membership');
     } else {
         //fix for CRM-2219 Update Membership
         // onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE
         if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
             array_unshift($values, "Required parameter missing: Status");
             return CRM_Member_Import_Parser::ERROR;
         }
         if ($formatValues['membership_id']) {
             require_once 'CRM/Member/BAO/Membership.php';
             $dao = new CRM_Member_BAO_Membership();
             $dao->id = $formatValues['membership_id'];
             $dates = array('join_date', 'start_date', 'end_date');
             foreach ($dates as $v) {
                 if (!$formatted[$v]) {
                     $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                 }
             }
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
             if ($dao->find(true)) {
                 $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                 $newMembership =& CRM_Member_BAO_Membership::create($formatted, $ids, true);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['is_error'] . " for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     $this->_newMemberships[] = $newMembership->id;
                     return CRM_Member_Import_Parser::VALID;
                 }
             } else {
                 array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
     }
     //Format dates
     $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d');
     $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d');
     $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The membership was not imported");
                 return CRM_Member_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 //fix for CRM-1924
                 require_once 'CRM/Member/BAO/MembershipStatus.php';
                 require_once 'CRM/Member/BAO/MembershipType.php';
                 require_once 'CRM/Member/PseudoConstant.php';
                 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                 self::formattedDates($calcDates, $formatted);
                 //fix for CRM-3570, exclude the statuses those having is_admin = 1
                 //now user can import is_admin if is override is true.
                 $excludeIsAdmin = false;
                 if (!CRM_Utils_Array::value('is_override', $formatted)) {
                     $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
                 }
                 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
                 if (!$formatted['status_id']) {
                     $formatted['status_id'] = $calcStatus['id'];
                 } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                     if (empty($calcStatus)) {
                         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.");
                         return CRM_Member_Import_Parser::ERROR;
                     } else {
                         if ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             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.");
                             return CRM_Member_Import_Parser::ERROR;
                         }
                     }
                 }
                 $newMembership = civicrm_contact_membership_create($formatted);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['error_message']);
                     return CRM_Member_Import_Parser::ERROR;
                 }
                 $this->_newMemberships[] = $newMembership['id'];
                 return CRM_Member_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Member_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
         //to calculate dates
         require_once 'CRM/Member/BAO/MembershipType.php';
         $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
         self::formattedDates($calcDates, $formatted);
         //end of date calculation part
         //fix for CRM-3570, exclude the statuses those having is_admin = 1
         //now user can import is_admin if is override is true.
         $excludeIsAdmin = false;
         if (!CRM_Utils_Array::value('is_override', $formatted)) {
             $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (!$formatted['status_id']) {
             $formatted['status_id'] = $calcStatus['id'];
         } else {
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     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.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     if ($formatted['status_id'] != $calcStatus['id']) {
                         //Status Hold" is either NOT mapped or is FALSE
                         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.");
                         return CRM_Member_Import_Parser::ERROR;
                     }
                 }
             }
         }
         $newMembership = civicrm_contact_membership_create($formatted);
         if (civicrm_error($newMembership)) {
             array_unshift($values, $newMembership['error_message']);
             return CRM_Member_Import_Parser::ERROR;
         }
         $this->_newMemberships[] = $newMembership['id'];
         return CRM_Member_Import_Parser::VALID;
     }
 }
 /**
  * To find fields related to a rule group.
  *
  * @param array contains the rule group property to identify rule group
  *
  * @return (rule field => weight) array and threshold associated to rule group
  * @access public
  */
 function dedupeRuleFieldsWeight($params)
 {
     $rgBao = new CRM_Dedupe_BAO_RuleGroup();
     $rgBao->level = $params['level'];
     $rgBao->contact_type = $params['contact_type'];
     $rgBao->is_default = 1;
     $rgBao->find(TRUE);
     $ruleBao = new CRM_Dedupe_BAO_Rule();
     $ruleBao->dedupe_rule_group_id = $rgBao->id;
     $ruleBao->find();
     $ruleFields = array();
     while ($ruleBao->fetch()) {
         $ruleFields[$ruleBao->rule_field] = $ruleBao->rule_weight;
     }
     return array($ruleFields, $rgBao->threshold);
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Event_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($key == 'participant_register_date') {
                 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                     if (!CRM_Utils_Rule::date($params[$key])) {
                         CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                     }
                 } else {
                     CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                 }
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     if (!($params['participant_role_id'] || $params['participant_role'])) {
         if ($params['event_id']) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Event/BAO/Participant.php';
         $indieFields =& CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_participant_formatted_param($formatValues, $formatted, true);
     require_once "api/v2/Participant.php";
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Event_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Event_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             require_once 'CRM/Event/BAO/Participant.php';
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['participant_id'], 'Participant');
             if ($dao->find(true)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $newParticipant = civicrm_participant_check_params($formatted, false);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
                 $newParticipant =& CRM_Event_BAO_Participant::create($formatted, $ids);
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Event_Import_Parser::VALID;
             } else {
                 array_unshift($values, "Matching Participant record not found for Participant ID " . $formatValues['participant_id'] . ". Row was skipped.");
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Event_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
         $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Event_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant['error_data']);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant['error_data']);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", true);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Event_Import_Parser::DUPLICATE;
             } else {
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
             }
             return CRM_Event_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = $newParticipant['id'];
     }
     return CRM_Event_Import_Parser::VALID;
 }
Beispiel #11
0
 /**
  * combine all the importable fields from the lower levels object
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important
  *
  * @param int     $contactType     contact Type
  * @param boolean $status          status is used to manipulate first title
  * @param boolean $showAll         if true returns all fields (includes disabled fields)
  * @param boolean $isProfile       if its profile mode
  * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
  *
  * @return array array of importable Fields
  * @access public
  * @static
  */
 static function &importableFields($contactType = 'Individual', $status = FALSE, $showAll = FALSE, $isProfile = FALSE, $checkPermission = TRUE, $withMultiCustomFields = FALSE)
 {
     $contactType = 'Individual';
     $fields = CRM_Hrjobcontract_DAO_HRJobContract::import();
     $tmpContactField = $contactFields = array();
     $contactFields = array();
     $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
     // Using new Dedupe rule.
     $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
     $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
     if (is_array($fieldsArray)) {
         foreach ($fieldsArray as $value) {
             $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
             $value = $customFieldId ? 'custom_' . $customFieldId : $value;
             $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
             if (!$status) {
                 $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
             } else {
                 $title = $tmpContactField[trim($value)]['title'];
             }
             $tmpContactField[trim($value)]['title'] = $title;
         }
     }
     $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
     if ($extIdentifier) {
         $tmpContactField['external_identifier'] = $extIdentifier;
         $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
     }
     $fields = array_merge($fields, $tmpContactField);
     self::$_importableFields = $fields;
     return self::$_importableFields;
     //$fields;
 }
Beispiel #12
0
 /**
  * To find fields related to a rule group.
  * @param array contains the rule group property to identify rule group
  *
  * @return rule fields array associated to rule group
  * @access public
  */
 function dedupeRuleFields($params)
 {
     require_once 'CRM/Dedupe/BAO/RuleGroup.php';
     $rgBao = new CRM_Dedupe_BAO_RuleGroup();
     $rgBao->level = $params['level'];
     $rgBao->contact_type = $params['contact_type'];
     $rgBao->is_default = 1;
     $rgBao->find(true);
     $ruleBao = new CRM_Dedupe_BAO_Rule();
     $ruleBao->dedupe_rule_group_id = $rgBao->id;
     $ruleBao->find();
     $ruleFields = array();
     while ($ruleBao->fetch()) {
         $ruleFields[] = $ruleBao->rule_field;
     }
     return $ruleFields;
 }
Beispiel #13
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Activity_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $activityName = array_search('activity_name', $this->_mapperKeys);
     if ($activityName) {
         $params = array_merge($params, array('activity_name' => $values[$activityName]));
     }
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $params['source_contact_id'] = $session->get('userID');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     foreach ($params as $key => $val) {
         if ($key == 'activity_date_time') {
             if ($val) {
                 if ($dateType == 1) {
                     $params[$key] = CRM_Utils_Date::customFormat($val, '%Y%m%d%H%i');
                     //hack to add seconds
                     $params[$key] = $params[$key] . '00';
                 } else {
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                 }
             }
         } elseif ($key == 'duration') {
             $params['duration_minutes'] = $params['duration'];
             unset($params['duration']);
         }
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             if ($customFields[$customFieldID]['data_type'] == 'Date') {
                 CRM_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
             } else {
                 if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     $formatError = _civicrm_activity_formatted_param($params, $params, true);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, CRM_Core_DAO::$_nullObject, null, 'Activity');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule.
         //since we are support only individual's activity import.
         $params['contact_type'] = 'Individual';
         $error = civicrm_check_contact_dedupe($params);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The activity was not imported");
                 return CRM_Activity_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $params['target_contact_id'] = $cid;
                 $newActivity = civicrm_activity_create($params);
                 if (CRM_Utils_Array::value('is_error', $newActivity)) {
                     array_unshift($values, $newActivity['error_message']);
                     return CRM_Activity_Import_Parser::ERROR;
                 }
                 $this->_newActivity[] = $newActivity['id'];
                 return CRM_Activity_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => 'Individual', 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Activity_Import_Parser::ERROR;
         }
     } else {
         if (CRM_Utils_Array::value('external_identifier', $params)) {
             $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier');
             if (CRM_Utils_Array::value('target_contact_id', $params) && $params['target_contact_id'] != $targetContactId) {
                 array_unshift($values, "Mismatch of External identifier :" . $params['external_identifier'] . " and Contact Id:" . $params['target_contact_id']);
                 return CRM_Activity_Import_Parser::ERROR;
             } else {
                 if ($targetContactId) {
                     $params['target_contact_id'] = $targetContactId;
                 } else {
                     array_unshift($values, "No Matching Contact for External identifier :" . $params['external_identifier']);
                     return CRM_Activity_Import_Parser::ERROR;
                 }
             }
         }
         $newActivity = civicrm_activity_create($params);
         if (CRM_Utils_Array::value('is_error', $newActivity)) {
             array_unshift($values, $newActivity['error_message']);
             return CRM_Activity_Import_Parser::ERROR;
         }
         $this->_newActivity[] = $newActivity['id'];
         return CRM_Activity_Import_Parser::VALID;
     }
 }
 /**
  * To find fields related to a rule group.
  *
  * @param array contains the rule group property to identify rule group
  *
  * @return rule fields array associated to rule group
  * @access public
  */
 static function dedupeRuleFields($params)
 {
     $rgBao = new CRM_Dedupe_BAO_RuleGroup();
     $rgBao->level = $params['level'];
     $rgBao->contact_type = $params['contact_type'];
     $rgBao->is_default = 1;
     $rgBao->find(TRUE);
     $ruleBao = new CRM_Dedupe_BAO_Rule();
     $ruleBao->dedupe_rule_group_id = $rgBao->id;
     $ruleBao->find();
     $ruleFields = array();
     while ($ruleBao->fetch()) {
         $ruleFields[] = $ruleBao->rule_field;
     }
     return $ruleFields;
 }
 /** 
  * Function to build the form 
  * 
  * @return None 
  * @access public 
  */
 public function buildQuickForm()
 {
     $this->applyFilter('__ALL__', 'trim');
     $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
     $this->addElement('checkbox', 'is_online_registration', ts('Allow Online Registration?'), null, array('onclick' => "return showHideByValue('is_online_registration', \n                                                                       '', \n                                                                       'registration_blocks', \n                                                                       'block', \n                                                                       'radio', \n                                                                       false );"));
     $this->add('text', 'registration_link_text', ts('Registration Link Text'));
     if (!$this->_isTemplate) {
         $this->addDateTime('registration_start_date', ts('Registration Start Date'), false, array('formatType' => 'activityDateTime'));
         $this->addDateTime('registration_end_date', ts('Registration End Date'), false, array('formatType' => 'activityDateTime'));
     }
     $this->addElement('checkbox', 'is_multiple_registrations', ts('Register multiple participants?'), null, array('onclick' => "return showHideByValue('is_multiple_registrations', '', 'additional_profile_pre|additional_profile_post', 'table-row', 'radio', false);"));
     require_once 'CRM/Dedupe/BAO/Rule.php';
     $params = array('level' => 'Fuzzy', 'contact_type' => 'Individual');
     $dedupeRuleFields = CRM_Dedupe_BAO_Rule::dedupeRuleFields($params);
     foreach ($dedupeRuleFields as $key => $fields) {
         $ruleFields[$key] = ucwords(str_replace('_', ' ', $fields));
     }
     $this->addElement('checkbox', 'allow_same_participant_emails', ts('Allow multiple registrations from the same email address?'), null, array('onclick' => "return showRuleFields( " . json_encode($ruleFields) . " );"));
     $this->assign('ruleFields', json_encode($ruleFields));
     require_once 'CRM/Event/PseudoConstant.php';
     $participantStatuses =& CRM_Event_PseudoConstant::participantStatus();
     if (in_array('Awaiting approval', $participantStatuses) and in_array('Pending from approval', $participantStatuses) and in_array('Rejected', $participantStatuses)) {
         $this->addElement('checkbox', 'requires_approval', ts('Require participant approval?'), null, array('onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);"));
         $this->add('textarea', 'approval_req_text', ts('Approval message'), $attributes['approval_req_text']);
     }
     $this->add('text', 'expiration_time', ts('Pending participant expiration (hours)'));
     $this->addRule('expiration_time', ts('Please enter the number of hours (as an integer).'), 'integer');
     self::buildRegistrationBlock($this);
     self::buildConfirmationBlock($this);
     self::buildMailBlock($this);
     self::buildThankYouBlock($this);
     parent::buildQuickForm();
 }
 /**
  * Combine all the importable fields from the lower levels object
  *
  * @param string  $contactType contact type
  * @param boolean $status      
  *
  * @return array array of importable Fields
  * @access public
  */
 function &importableFields($contactType = 'Individual', $status = true)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
         } else {
             $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
         }
         $tmpFields = CRM_Member_DAO_Membership::import();
         require_once 'CRM/Contact/BAO/Contact.php';
         $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, null);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => $contactType, 'level' => 'Strict');
         require_once 'CRM/Dedupe/BAO/Rule.php';
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpContactField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                 if (!$status) {
                     $title = $tmpContactField[trim($value)]['title'] . " " . ts("(match to contact)");
                 } else {
                     $title = $tmpContactField[trim($value)]['title'];
                 }
                 $tmpContactField[trim($value)]['title'] = $title;
             }
         }
         $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
         $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts("(match to contact)");
         $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts("(match to contact)");
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #17
0
 public function preProcess()
 {
     if (!CRM_Core_Permission::check('merge duplicate contacts')) {
         CRM_Core_Error::fatal(ts('You do not have access to this page'));
     }
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
     $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
     $this->_rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
     $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
     $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
     $this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
     $urlParams = "reset=1&rgid={$this->_rgid}&gid={$this->_gid}&limit=" . $this->limit;
     // Sanity check
     if ($cid == $oid) {
         CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
     }
     if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
         CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href="%1">Dedupe Exceptions</a> page.', array(1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1'))));
     }
     $this->_contactType = civicrm_api3('Contact', 'getvalue', array('id' => $cid, 'return' => 'contact_type'));
     $isFromDedupeScreen = TRUE;
     if (!$this->_rgid) {
         $isFromDedupeScreen = FALSE;
         $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array('contact_type' => $this->_contactType, 'used' => 'Supervised', 'return' => 'id'));
     }
     $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid);
     $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
     $where = "de.id IS NULL";
     $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
     // Block access if user does not have EDIT permissions for both contacts.
     if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT))) {
         CRM_Utils_System::permissionDenied();
     }
     // get user info of main contact.
     $config = CRM_Core_Config::singleton();
     $config->doNotResetCache = 1;
     $viewUser = CRM_Core_Permission::check('access user profiles');
     $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
     $mainUser = NULL;
     if ($mainUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $mainUser = user_load($mainUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $mainUser = JFactory::getUser($mainUfId);
         }
         $this->assign('mainUfId', $mainUfId);
         $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
     }
     $flipUrl = CRM_Utils_System::url('civicrm/contact/merge', "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$this->_rgid}&gid={$gid}");
     if (!$flip) {
         $flipUrl .= '&flip=1';
     }
     $this->assign('flip', $flipUrl);
     $this->prev = $this->next = NULL;
     foreach (array('prev', 'next') as $position) {
         if (!empty($pos[$position])) {
             if ($pos[$position]['id1'] && $pos[$position]['id2']) {
                 $urlParams .= "&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
                 $this->{$position} = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
                 $this->assign($position, $this->{$position});
             }
         }
     }
     // get user info of other contact.
     $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
     $otherUser = NULL;
     if ($otherUfId) {
         // d6 compatible
         if ($config->userSystem->is_drupal == '1') {
             $otherUser = user_load($otherUfId);
         } elseif ($config->userFramework == 'Joomla') {
             $otherUser = JFactory::getUser($otherUfId);
         }
         $this->assign('otherUfId', $otherUfId);
         $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
     }
     $cmsUser = $mainUfId && $otherUfId ? TRUE : FALSE;
     $this->assign('user', $cmsUser);
     $session = CRM_Core_Session::singleton();
     // context fixed.
     if ($isFromDedupeScreen) {
         $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParams . '&action=browse');
         $session->pushUserContext($browseUrl);
     }
     $this->assign('browseUrl', empty($browseUrl) ? '' : $browseUrl);
     // ensure that oid is not the current user, if so refuse to do the merge
     if ($session->get('userID') == $oid) {
         $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
         $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name));
         CRM_Core_Error::statusBounce($message);
     }
     $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($cid, $oid);
     $main = $this->_mainDetails =& $rowsElementsAndInfo['main_details'];
     $other = $this->_otherDetails =& $rowsElementsAndInfo['other_details'];
     if ($main['contact_id'] != $cid) {
         CRM_Core_Error::fatal(ts('The main contact record does not exist'));
     }
     if ($other['contact_id'] != $oid) {
         CRM_Core_Error::fatal(ts('The other contact record does not exist'));
     }
     $this->assign('contact_type', $main['contact_type']);
     $this->assign('main_name', $main['display_name']);
     $this->assign('other_name', $other['display_name']);
     $this->assign('main_cid', $main['contact_id']);
     $this->assign('other_cid', $other['contact_id']);
     $this->assign('rgid', $this->_rgid);
     $this->_cid = $cid;
     $this->_oid = $oid;
     $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
     $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
     $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
     $this->assign('rows', $rowsElementsAndInfo['rows']);
     // add elements
     foreach ($rowsElementsAndInfo['elements'] as $element) {
         $this->addElement($element[0], $element[1], array_key_exists('2', $element) ? $element[2] : NULL, array_key_exists('3', $element) ? $element[3] : NULL, array_key_exists('4', $element) ? $element[4] : NULL, array_key_exists('5', $element) ? $element[5] : NULL);
     }
     // add related table elements
     foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
         $element = $this->addElement($relTableElement[0], $relTableElement[1]);
         $element->setChecked(TRUE);
     }
     $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
     $this->assign('userContextURL', $session->readUserContext());
 }
Beispiel #18
0
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('version' => 3);
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
     $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
     //CRM-10994
     if (isset($params['total_amount']) && $params['total_amount'] == 0) {
         $params['total_amount'] = '0.00';
     }
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                 case 'cancel_date':
                 case 'receipt_date':
                 case 'thankyou_date':
                     $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
                     break;
                 case 'pledge_payment':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $tempIndieFields = CRM_Contribute_DAO_Contribution::import();
         $indieFields = $tempIndieFields;
     }
     $paramValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $paramValues[$key] = $field;
     }
     //import contribution record according to select contact type
     if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($params['soft_credit'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($paramValues['pledge_payment'])) {
         $paramValues['contact_type'] = $this->_contactType;
     }
     //need to pass $onDuplicate to check import mode.
     if (!empty($paramValues['pledge_payment'])) {
         $paramValues['onDuplicate'] = $onDuplicate;
     }
     require_once 'CRM/Utils/DeprecatedUtils.php';
     $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
         } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
             return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
         }
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution');
     } else {
         //fix for CRM-2219 - Update Contribution
         // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
         if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) {
             $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues));
             $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
             if ($ids['contribution']) {
                 $formatted['id'] = $ids['contribution'];
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution');
                 //process note
                 if (!empty($paramValues['note'])) {
                     $noteID = array();
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
                     $daoNote = new CRM_Core_BAO_Note();
                     $daoNote->entity_table = 'civicrm_contribution';
                     $daoNote->entity_id = $ids['contribution'];
                     if ($daoNote->find(TRUE)) {
                         $noteID['id'] = $daoNote->id;
                     }
                     $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID);
                     CRM_Core_BAO_Note::add($noteParams, $noteID);
                     unset($formatted['note']);
                 }
                 //need to check existing soft credit contribution, CRM-3968
                 if (!empty($formatted['soft_credit'])) {
                     $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']);
                     //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
                     $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']);
                     if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
                         foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
                             if (!empty($existingSoftCreditValues['soft_credit_id'])) {
                                 $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL);
                                 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                             }
                         }
                     }
                 }
                 $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids);
                 $this->_newContributions[] = $newContribution->id;
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             } else {
                 $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID');
                 foreach ($dupeIds as $k => $v) {
                     if ($v) {
                         $errorMsg[] = "{$labels[$k]} {$v}";
                     }
                 }
                 $errorMsg = implode(' AND ', $errorMsg);
                 array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         // set the contact type if its not set
         if (!isset($paramValues['contact_type'])) {
             $paramValues['contact_type'] = $this->_contactType;
         }
         $paramValues['version'] = 3;
         //retrieve contact id using contact dedupe rule
         require_once 'CRM/Utils/DeprecatedUtils.php';
         $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
                 return CRM_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = civicrm_api('contribution', 'create', $formatted);
                 if (civicrm_error($newContribution)) {
                     if (is_array($newContribution['error_message'])) {
                         array_unshift($values, $newContribution['error_message']['message']);
                         if ($newContribution['error_message']['params'][0]) {
                             return CRM_Import_Parser::DUPLICATE;
                         }
                     } else {
                         array_unshift($values, $newContribution['error_message']);
                         return CRM_Import_Parser::ERROR;
                     }
                 }
                 $this->_newContributions[] = $newContribution['id'];
                 $formatted['contribution_id'] = $newContribution['id'];
                 //return soft valid since we need to show how soft credits were added
                 if (!empty($formatted['soft_credit'])) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = NULL;
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($paramValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $paramValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newContribution = civicrm_api('contribution', 'create', $formatted);
         if (civicrm_error($newContribution)) {
             if (is_array($newContribution['error_message'])) {
                 array_unshift($values, $newContribution['error_message']['message']);
                 if ($newContribution['error_message']['params'][0]) {
                     return CRM_Import_Parser::DUPLICATE;
                 }
             } else {
                 array_unshift($values, $newContribution['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $this->_newContributions[] = $newContribution['id'];
         $formatted['contribution_id'] = $newContribution['id'];
         //return soft valid since we need to show how soft credits were added
         if (!empty($formatted['soft_credit'])) {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT;
         }
         // process pledge payment assoc w/ the contribution
         return self::processPledgePayments($formatted);
         return CRM_Import_Parser::VALID;
     }
 }
 /**
  * combine all the importable fields from the lower levels object
  *
  * @return array array of importable Fields
  * @access public
  */
 function &importableFields($contactType = 'Individual', $status = true, $onlyParticipant = false)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$onlyParticipant) {
             if (!$status) {
                 $fields = array('' => array('title' => ts('- do not import -')));
             } else {
                 $fields = array('' => array('title' => ts('- Participant Fields -')));
             }
         } else {
             $fields = array();
         }
         require_once 'CRM/Core/DAO/Note.php';
         $tmpFields = CRM_Event_DAO_Participant::import();
         $note = array('participant_note' => array('title' => 'Participant Note', 'name' => 'participant_note', 'headerPattern' => '/(participant.)?note$/i'));
         $participantStatus = array('participant_status' => array('title' => 'Participant Status', 'name' => 'participant_status', 'data_type' => CRM_Utils_Type::T_STRING));
         $participantRole = array('participant_role' => array('title' => 'Participant Role', 'name' => 'participant_role', 'data_type' => CRM_Utils_Type::T_STRING));
         $eventType = array('event_type' => array('title' => 'Event Type', 'name' => 'event_type', 'data_type' => CRM_Utils_Type::T_STRING));
         $tmpConatctField = array();
         if (!$onlyParticipant) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, null);
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             if (is_array($fieldsArray)) {
                 foreach ($fieldsArray as $value) {
                     $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                     if (!$status) {
                         $title = $tmpContactField[trim($value)]['title'] . " (match to contact)";
                     } else {
                         $title = $tmpContactField[trim($value)]['title'];
                     }
                     $tmpContactField[trim($value)]['title'] = $title;
                 }
             }
         }
         $tmpContactField['external_identifier'] = CRM_Utils_Array::value('external_identifier', $contactFields);
         $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
         $tmpFields['participant_contact_id']['title'] = $tmpFields['participant_contact_id']['title'] . " (match to contact)";
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, $note, $participantStatus, $participantRole, $eventType);
         //$fields = array_merge($fields, $optionFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Participant'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #20
0
 /**
  * Set variables up before form is built.
  */
 public function preProcess()
 {
     $dataSource = $this->get('dataSource');
     $skipColumnHeader = $this->get('skipColumnHeader');
     $this->_mapperFields = $this->get('fields');
     $this->_importTableName = $this->get('importTableName');
     $this->_onDuplicate = $this->get('onDuplicate');
     $highlightedFields = array();
     $highlightedFields[] = 'email';
     $highlightedFields[] = 'external_identifier';
     //format custom field names, CRM-2676
     switch ($this->get('contactType')) {
         case CRM_Import_Parser::CONTACT_INDIVIDUAL:
             $contactType = 'Individual';
             $highlightedFields[] = 'first_name';
             $highlightedFields[] = 'last_name';
             break;
         case CRM_Import_Parser::CONTACT_HOUSEHOLD:
             $contactType = 'Household';
             $highlightedFields[] = 'household_name';
             break;
         case CRM_Import_Parser::CONTACT_ORGANIZATION:
             $contactType = 'Organization';
             $highlightedFields[] = 'organization_name';
             break;
     }
     $this->_contactType = $contactType;
     if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
         unset($this->_mapperFields['id']);
     } else {
         $highlightedFields[] = 'id';
     }
     if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
         //Mark Dedupe Rule Fields as required, since it's used in matching contact
         foreach (array('Individual', 'Household', 'Organization') as $cType) {
             $ruleParams = array('contact_type' => $cType, 'used' => 'Unsupervised');
             $this->_dedupeFields[$cType] = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         }
         //Modify mapper fields title if fields are present in dedupe rule
         if (is_array($this->_dedupeFields[$contactType])) {
             foreach ($this->_dedupeFields[$contactType] as $val) {
                 if ($valTitle = CRM_Utils_Array::value($val, $this->_mapperFields)) {
                     $this->_mapperFields[$val] = $valTitle . ' (match to contact)';
                 }
             }
         }
     }
     // retrieve and highlight required custom fields
     $formattedFieldNames = $this->formatCustomFieldName($this->_mapperFields);
     self::$customFields = CRM_Core_BAO_CustomField::getFields($this->_contactType);
     foreach (self::$customFields as $key => $attr) {
         if (!empty($attr['is_required'])) {
             $highlightedFields[] = "custom_{$key}";
         }
     }
     $this->assign('highlightedFields', $highlightedFields);
     $this->_formattedFieldNames[$contactType] = $this->_mapperFields = array_merge($this->_mapperFields, $formattedFieldNames);
     $columnNames = array();
     //get original col headers from csv if present.
     if ($dataSource == 'CRM_Import_DataSource_CSV' && $skipColumnHeader) {
         $columnNames = $this->get('originalColHeader');
     } else {
         // get the field names from the temp. DB table
         $dao = new CRM_Core_DAO();
         $db = $dao->getDatabaseConnection();
         $columnsQuery = "SHOW FIELDS FROM {$this->_importTableName}\n                         WHERE Field NOT LIKE '\\_%'";
         $columnsResult = $db->query($columnsQuery);
         while ($row = $columnsResult->fetchRow(DB_FETCHMODE_ASSOC)) {
             $columnNames[] = $row['Field'];
         }
     }
     $showColNames = TRUE;
     if ($dataSource == 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
         $showColNames = FALSE;
     }
     $this->assign('showColNames', $showColNames);
     $this->_columnCount = count($columnNames);
     $this->_columnNames = $columnNames;
     $this->assign('columnNames', $columnNames);
     //$this->_columnCount = $this->get( 'columnCount' );
     $this->assign('columnCount', $this->_columnCount);
     $this->_dataValues = $this->get('dataValues');
     $this->assign('dataValues', $this->_dataValues);
     $this->assign('rowDisplayCount', 2);
 }
Beispiel #21
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $activityLabel = array_search('activity_label', $this->_mapperKeys);
     if ($activityLabel) {
         $params = array_merge($params, array('activity_label' => $values[$activityLabel]));
     }
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     if (!isset($params['source_contact_id'])) {
         $params['source_contact_id'] = $session->get('userID');
     }
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     foreach ($params as $key => $val) {
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             if ($key == 'activity_date_time' && $val) {
                 $params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
             } elseif ($customFields[$customFieldID]['data_type'] == 'Date') {
                 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
             } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                 $params[$key] = CRM_Utils_String::strtoboolstr($val);
             }
         } elseif ($key == 'activity_subject') {
             $params['subject'] = $val;
         }
     }
     //date-Format part ends
     require_once 'CRM/Utils/DeprecatedUtils.php';
     $formatError = _civicrm_api3_deprecated_activity_formatted_param($params, $params, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, CRM_Core_DAO::$_nullObject, NULL, 'Activity');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule.
         //since we are support only individual's activity import.
         $params['contact_type'] = 'Individual';
         $params['version'] = 3;
         $error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
                 return CRM_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $params['target_contact_id'] = $cid;
                 $params['version'] = 3;
                 $newActivity = civicrm_api('activity', 'create', $params);
                 if (CRM_Utils_Array::value('is_error', $newActivity)) {
                     array_unshift($values, $newActivity['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $this->_newActivity[] = $newActivity['id'];
                 return CRM_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => 'Individual', 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = NULL;
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (CRM_Utils_Array::value('external_identifier', $params)) {
             $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier');
             if (CRM_Utils_Array::value('target_contact_id', $params) && $params['target_contact_id'] != $targetContactId) {
                 array_unshift($values, 'Mismatch of External identifier :' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
                 return CRM_Import_Parser::ERROR;
             } elseif ($targetContactId) {
                 $params['target_contact_id'] = $targetContactId;
             } else {
                 array_unshift($values, 'No Matching Contact for External identifier :' . $params['external_identifier']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $params['version'] = 3;
         $newActivity = civicrm_api('activity', 'create', $params);
         if (CRM_Utils_Array::value('is_error', $newActivity)) {
             array_unshift($values, $newActivity['error_message']);
             return CRM_Import_Parser::ERROR;
         }
         $this->_newActivity[] = $newActivity['id'];
         return CRM_Import_Parser::VALID;
     }
 }
Beispiel #22
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     //to save the current mappings
     if (!$this->get('savedMapping')) {
         $saveDetailsName = ts('Save this field mapping');
         $this->applyFilter('saveMappingName', 'trim');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     } else {
         $savedMapping = $this->get('savedMapping');
         list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
         $mappingName = $mappingName[1];
         $mappingContactType = $mappingContactType[1];
         $mappingLocation = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingLocation));
         $mappingPhoneType = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingPhoneType));
         $mappingRelation = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingRelation));
         //mapping is to be loaded from database
         $params = array('id' => $savedMapping);
         $temp = array();
         $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
         $this->assign('loadedMapping', $mappingDetails->name);
         $this->set('loadedMapping', $savedMapping);
         $getMappingName = new CRM_Core_DAO_Mapping();
         $getMappingName->id = $savedMapping;
         $getMappingName->mapping_type = 'Import Contributions';
         $getMappingName->find();
         while ($getMappingName->fetch()) {
             $mapperName = $getMappingName->name;
         }
         $this->assign('savedName', $mapperName);
         $this->add('hidden', 'mappingId', $savedMapping);
         $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
         $saveDetailsName = ts('Save as a new field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     }
     $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
     $this->addFormRule(array('CRM_Contribute_Import_Form_MapField', 'formRule'), $this);
     //-------- end of saved mapping stuff ---------
     $defaults = array();
     $mapperKeys = array_keys($this->_mapperFields);
     $hasHeaders = !empty($this->_columnHeaders);
     $headerPatterns = $this->get('headerPatterns');
     $dataPatterns = $this->get('dataPatterns');
     $hasLocationTypes = $this->get('fieldTypes');
     $mapperKeysValues = $this->controller->exportValue($this->_name, 'mapper');
     /* Initialize all field usages to false */
     foreach ($mapperKeys as $key) {
         $this->_fieldUsed[$key] = FALSE;
     }
     $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $sel1 = $this->_mapperFields;
     if (!$this->get('onDuplicate')) {
         unset($sel1['id']);
         unset($sel1['contribution_id']);
     }
     // start of soft credit section
     // get contact type for this import
     $contactTypeId = $this->get('contactType');
     $contactTypes = array(CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual', CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household', CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization');
     $contactType = isset($contactTypes[$contactTypeId]) ? $contactTypes[$contactTypeId] : '';
     // get importable fields for contact type
     $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
     // get the Dedupe rule for this contact type and build soft credit array
     $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
     $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
     $softCreditFields['contact_id'] = ts('Contact ID');
     $softCreditFields['external_identifier'] = ts('External ID');
     $softCreditFields['email'] = ts('Email');
     $sel2['soft_credit'] = $softCreditFields;
     $sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup::values('soft_credit_type');
     $sel4 = NULL;
     // end of soft credit section
     $js = "<script type='text/javascript'>\n";
     $formName = 'document.forms.' . $this->_name;
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL);
         $jsSet = FALSE;
         if ($this->get('savedMapping')) {
             if (isset($mappingName[$i])) {
                 if ($mappingName[$i] != ts('- do not import -')) {
                     $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
                     // reusing contact_type field array for soft credit
                     $softField = isset($mappingContactType[$i]) ? $mappingContactType[$i] : 0;
                     if (!$softField) {
                         $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                     }
                     $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                     $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                     $defaults["mapper[{$i}]"] = array(CRM_Utils_Array::value(0, $mappingHeader), $softField ? $softField : "", isset($locationId) ? $locationId : "", isset($phoneType) ? $phoneType : "");
                     $jsSet = TRUE;
                 } else {
                     $defaults["mapper[{$i}]"] = array();
                 }
                 if (!$jsSet) {
                     for ($k = 1; $k < 4; $k++) {
                         $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                     }
                 }
             } else {
                 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
                 $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n";
                 if ($hasHeaders) {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
                 } else {
                     $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i));
                 }
             }
             //end of load mapping
         } else {
             $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n";
             if ($hasHeaders) {
                 // do array search first to see if has mapped key
                 $columnKey = '';
                 $columnKey = array_search($this->_columnHeaders[$i], $this->_mapperFields);
                 if (isset($this->_fieldUsed[$columnKey])) {
                     $defaults["mapper[{$i}]"] = $columnKey;
                     $this->_fieldUsed[$key] = TRUE;
                 } else {
                     // Infer the default from the column names if we have them
                     $defaults["mapper[{$i}]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns), 0);
                 }
             } else {
                 // Otherwise guess the default from the form of the data
                 $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0);
             }
             if (!empty($mapperKeysValues) && $mapperKeysValues[$i][0] == 'soft_credit') {
                 $js .= "cj('#mapper_" . $i . "_1').val({$mapperKeysValues[$i]}[1]);\n";
                 $js .= "cj('#mapper_" . $i . "_2').val({$mapperKeysValues[$i]}[2]);\n";
             }
         }
         $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     }
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     //set warning if mismatch in more than
     if (isset($mappingName)) {
         if ($this->_columnCount != count($mappingName)) {
             $warning++;
         }
     }
     if ($warning != 0 && $this->get('savedMapping')) {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
     } else {
         $session = CRM_Core_Session::singleton();
         $session->setStatus(NULL);
     }
     $this->setDefaults($defaults);
     $this->addButtons(array(array('type' => 'back', 'name' => ts('Previous')), array('type' => 'next', 'name' => ts('Continue'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
 }
 /**
  * find fields related to a rule group.
  *
  * @param array $params
  *
  * @return array
  *   (rule field => weight) array and threshold associated to rule group
  */
 public static function dedupeRuleFieldsWeight($params)
 {
     $rgBao = new CRM_Dedupe_BAO_RuleGroup();
     $rgBao->contact_type = $params['contact_type'];
     if (!empty($params['id'])) {
         // accept an ID if provided
         $rgBao->id = $params['id'];
     } else {
         $rgBao->used = $params['used'];
     }
     $rgBao->find(TRUE);
     $ruleBao = new CRM_Dedupe_BAO_Rule();
     $ruleBao->dedupe_rule_group_id = $rgBao->id;
     $ruleBao->find();
     $ruleFields = array();
     while ($ruleBao->fetch()) {
         $ruleFields[$ruleBao->rule_field] = $ruleBao->rule_weight;
     }
     return array($ruleFields, $rgBao->threshold);
 }
 /**
  * Combine all the importable fields from the lower levels object.
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important and should be done in the
  * next week or so, before this can be called complete.
  *
  * @param bool $status
  *
  * @return array
  *   array of importable Fields
  */
 public static function &importableFields($status = FALSE)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => ts('- do not import -')));
         } else {
             $fields = array('' => array('title' => ts('- Activity Fields -')));
         }
         $tmpFields = CRM_Activity_DAO_Activity::import();
         $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => 'Individual', 'used' => 'Unsupervised');
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpConatctField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
                 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
             }
         }
         $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
         $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
         $fields = array_merge($fields, $tmpConatctField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #25
0
 /**
  * combine all the importable fields from the lower levels object
  *
  * The ordering is important, since currently we do not have a weight
  * scheme. Adding weight is super important
  *
  * @param int     $contactType     contact Type
  * @param boolean $status          status is used to manipulate first title
  * @param boolean $showAll         if true returns all fields (includes disabled fields)
  * @param boolean $isProfile       if its profile mode
  * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
  *
  * @return array array of importable Fields
  * @access public
  * @static
  */
 static function importableFields($contactType = 'Individual', $status = FALSE, $showAll = FALSE, $isProfile = FALSE, $checkPermission = TRUE, $withMultiCustomFields = FALSE)
 {
     $cacheKeyString = "";
     $cacheKeyString .= $status ? '_1' : '_0';
     $cacheKeyString .= $showAll ? '_1' : '_0';
     $cacheKeyString .= $isProfile ? '_1' : '_0';
     $cacheKeyString .= $checkPermission ? '_1' : '_0';
     $contactType = 'Individual';
     $fields = CRM_Utils_Array::value($cacheKeyString, self::$_importableFields);
     if (!$fields) {
         $fields = CRM_Appraisals_DAO_AppraisalCycle::import();
         $tmpContactField = $contactFields = array();
         $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                 if (!$status) {
                     $title = $tmpContactField[trim($value)]['title'] . ' (match to contact)';
                 } else {
                     $title = $tmpContactField[trim($value)]['title'];
                 }
                 $tmpContactField[trim($value)]['title'] = $title;
             }
         }
         $extIdentifier = CRM_Utils_Array::value('external_identifier', $contactFields);
         if ($extIdentifier) {
             $tmpContactField['external_identifier'] = $extIdentifier;
             $tmpContactField['external_identifier']['title'] = CRM_Utils_Array::value('title', $extIdentifier) . ' (match to contact)';
         }
         $fields = array_merge($fields, $tmpContactField);
         //Sorting fields in alphabetical order(CRM-1507)
         $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
         $fields = CRM_Utils_Array::index(array('name'), $fields);
         CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
     }
     self::$_importableFields[$cacheKeyString] = $fields;
     if (!$isProfile) {
         $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))), self::$_importableFields[$cacheKeyString]);
     }
     return $fields;
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     try {
         // first make sure this is a valid line
         $response = $this->summary($values);
         if ($response != CRM_Import_Parser::VALID) {
             return $response;
         }
         $params =& $this->getActiveFieldParams();
         //assign join date equal to start date if join date is not provided
         if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) {
             $params['join_date'] = $params['membership_start_date'];
         }
         $session = CRM_Core_Session::singleton();
         $dateType = $session->get('dateTypes');
         $formatted = array();
         $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
         // don't add to recent items, CRM-4399
         $formatted['skipRecentView'] = TRUE;
         $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date'));
         foreach ($params as $key => $val) {
             if ($val) {
                 switch ($key) {
                     case 'join_date':
                     case 'membership_start_date':
                     case 'membership_end_date':
                         if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                             if (!CRM_Utils_Rule::date($params[$key])) {
                                 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                             }
                         } else {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                         }
                         break;
                     case 'membership_type_id':
                         if (!is_numeric($val)) {
                             unset($params['membership_type_id']);
                             $params['membership_type'] = $val;
                         }
                         break;
                     case 'status_id':
                         if (!is_numeric($val)) {
                             unset($params['status_id']);
                             $params['membership_status'] = $val;
                         }
                         break;
                     case 'is_override':
                         $params[$key] = CRM_Utils_String::strtobool($val);
                         break;
                 }
                 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                     if ($customFields[$customFieldID]['data_type'] == 'Date') {
                         CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                         unset($params[$key]);
                     } else {
                         if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                             $params[$key] = CRM_Utils_String::strtoboolstr($val);
                         }
                     }
                 }
             }
         }
         //date-Format part ends
         static $indieFields = NULL;
         if ($indieFields == NULL) {
             $tempIndieFields = CRM_Member_DAO_Membership::import();
             $indieFields = $tempIndieFields;
         }
         $formatValues = array();
         foreach ($params as $key => $field) {
             if ($field == NULL || $field === '') {
                 continue;
             }
             $formatValues[$key] = $field;
         }
         //format params to meet api v2 requirements.
         //@todo find a way to test removing this formatting
         $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
         if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership');
         } else {
             //fix for CRM-2219 Update Membership
             // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
             if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
                 array_unshift($values, 'Required parameter missing: Status');
                 return CRM_Import_Parser::ERROR;
             }
             if (!empty($formatValues['membership_id'])) {
                 $dao = new CRM_Member_BAO_Membership();
                 $dao->id = $formatValues['membership_id'];
                 $dates = array('join_date', 'start_date', 'end_date');
                 foreach ($dates as $v) {
                     if (!CRM_Utils_Array::value($v, $formatted)) {
                         $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                     }
                 }
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
                 if ($dao->find(TRUE)) {
                     $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                     $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
                     if (civicrm_error($newMembership)) {
                         array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                         return CRM_Import_Parser::ERROR;
                     } else {
                         $this->_newMemberships[] = $newMembership->id;
                         return CRM_Import_Parser::VALID;
                     }
                 } else {
                     array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
         }
         //Format dates
         $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d');
         $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
         $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
         if ($this->_contactIdIndex < 0) {
             //retrieve contact id using contact dedupe rule
             $formatValues['contact_type'] = $this->_contactType;
             $formatValues['version'] = 3;
             require_once 'CRM/Utils/DeprecatedUtils.php';
             $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
             if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                 $matchedIDs = explode(',', $error['error_message']['params'][0]);
                 if (count($matchedIDs) > 1) {
                     array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
                     return CRM_Import_Parser::ERROR;
                 } else {
                     $cid = $matchedIDs[0];
                     $formatted['contact_id'] = $cid;
                     //fix for CRM-1924
                     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                     self::formattedDates($calcDates, $formatted);
                     //fix for CRM-3570, exclude the statuses those having is_admin = 1
                     //now user can import is_admin if is override is true.
                     $excludeIsAdmin = FALSE;
                     if (!CRM_Utils_Array::value('is_override', $formatted)) {
                         $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
                     }
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
                     if (!CRM_Utils_Array::value('status_id', $formatted)) {
                         $formatted['status_id'] = $calcStatus['id'];
                     } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                         if (empty($calcStatus)) {
                             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.');
                             return CRM_Import_Parser::ERROR;
                         } elseif ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             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.');
                             return CRM_Import_Parser::ERROR;
                         }
                     }
                     $newMembership = civicrm_api3('membership', 'create', $formatted);
                     $this->_newMemberships[] = $newMembership['id'];
                     return CRM_Import_Parser::VALID;
                 }
             } else {
                 // Using new Dedupe rule.
                 $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
                 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
                 $disp = '';
                 foreach ($fieldsArray as $value) {
                     if (array_key_exists(trim($value), $params)) {
                         $paramValue = $params[trim($value)];
                         if (is_array($paramValue)) {
                             $disp .= $params[trim($value)][0][trim($value)] . " ";
                         } else {
                             $disp .= $params[trim($value)] . " ";
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('external_identifier', $params)) {
                     if ($disp) {
                         $disp .= "AND {$params['external_identifier']}";
                     } else {
                         $disp = $params['external_identifier'];
                     }
                 }
                 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
                 return CRM_Import_Parser::ERROR;
             }
         } else {
             if (CRM_Utils_Array::value('external_identifier', $formatValues)) {
                 $checkCid = new CRM_Contact_DAO_Contact();
                 $checkCid->external_identifier = $formatValues['external_identifier'];
                 $checkCid->find(TRUE);
                 if ($checkCid->id != $formatted['contact_id']) {
                     array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                     return CRM_Import_Parser::ERROR;
                 }
             }
             //to calculate dates
             $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
             self::formattedDates($calcDates, $formatted);
             //end of date calculation part
             //fix for CRM-3570, exclude the statuses those having is_admin = 1
             //now user can import is_admin if is override is true.
             $excludeIsAdmin = FALSE;
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
             }
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
             if (!CRM_Utils_Array::value('status_id', $formatted)) {
                 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
             } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     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.');
                     return CRM_Import_Parser::ERROR;
                 } elseif ($formatted['status_id'] != $calcStatus['id']) {
                     //Status Hold" is either NOT mapped or is FALSE
                     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.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
             $newMembership = civicrm_api3('membership', 'create', $formatted);
             $this->_newMemberships[] = $newMembership['id'];
             return CRM_Import_Parser::VALID;
         }
     } catch (Exception $e) {
         array_unshift($values, $e->getMessage());
         return CRM_Import_Parser::ERROR;
     }
 }
 /**
  * Build the form object.
  *
  * @return void
  */
 public function buildQuickForm()
 {
     if ($this->_addProfileBottom) {
         return self::buildMultipleProfileBottom($this, $this->_profileBottomNum);
     }
     if ($this->_addProfileBottomAdd) {
         return self::buildMultipleProfileBottom($this, $this->_profileBottomNumAdd, 'additional_', ts('Profile for Additional Participants'));
     }
     $this->applyFilter('__ALL__', 'trim');
     $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
     $this->addElement('checkbox', 'is_online_registration', ts('Allow Online Registration'), NULL, array('onclick' => "return showHideByValue('is_online_registration'," . "''," . "'registration_blocks'," . "'block'," . "'radio'," . "false );"));
     $this->add('text', 'registration_link_text', ts('Registration Link Text'));
     if (!$this->_isTemplate) {
         $this->addDateTime('registration_start_date', ts('Registration Start Date'), FALSE, array('formatType' => 'activityDateTime'));
         $this->addDateTime('registration_end_date', ts('Registration End Date'), FALSE, array('formatType' => 'activityDateTime'));
     }
     $params = array('used' => 'Supervised', 'contact_type' => 'Individual');
     $dedupeRuleFields = CRM_Dedupe_BAO_Rule::dedupeRuleFields($params);
     foreach ($dedupeRuleFields as $key => $fields) {
         $ruleFields[$key] = ucwords(str_replace('_', ' ', $fields));
     }
     $this->addElement('checkbox', 'is_multiple_registrations', ts('Register multiple participants?'));
     $this->addElement('checkbox', 'allow_same_participant_emails', ts('Same email address?'));
     $this->assign('ruleFields', json_encode($ruleFields));
     $dedupeRules = array('' => '- Unsupervised rule -');
     $dedupeRules += CRM_Dedupe_BAO_RuleGroup::getByType('Individual');
     $this->add('select', 'dedupe_rule_group_id', ts('Duplicate matching rule'), $dedupeRules);
     $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
     if (in_array('Awaiting approval', $participantStatuses) and in_array('Pending from approval', $participantStatuses) and in_array('Rejected', $participantStatuses)) {
         $this->addElement('checkbox', 'requires_approval', ts('Require participant approval?'), NULL, array('onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);"));
         $this->add('textarea', 'approval_req_text', ts('Approval message'), $attributes['approval_req_text']);
     }
     $this->add('text', 'expiration_time', ts('Pending participant expiration (hours)'));
     $this->addRule('expiration_time', ts('Please enter the number of hours (as an integer).'), 'integer');
     self::buildRegistrationBlock($this);
     self::buildConfirmationBlock($this);
     self::buildMailBlock($this);
     self::buildThankYouBlock($this);
     parent::buildQuickForm();
 }
Beispiel #28
0
 /**
  * Combine all the importable fields from the lower levels object.
  *
  * @param string $contactType
  *   Contact type.
  * @param bool $status
  *
  * @return array
  *   array of importable Fields
  */
 public static function &importableFields($contactType = 'Individual', $status = TRUE)
 {
     if (!self::$_importableFields) {
         if (!self::$_importableFields) {
             self::$_importableFields = array();
         }
         if (!$status) {
             $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
         } else {
             $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
         }
         $tmpFields = CRM_Member_DAO_Membership::import();
         $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
         // Using new Dedupe rule.
         $ruleParams = array('contact_type' => $contactType, 'used' => 'Unsupervised');
         $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
         $tmpContactField = array();
         if (is_array($fieldsArray)) {
             foreach ($fieldsArray as $value) {
                 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $value, 'id', 'column_name');
                 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
                 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
                 if (!$status) {
                     $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
                 } else {
                     $title = $tmpContactField[trim($value)]['title'];
                 }
                 $tmpContactField[trim($value)]['title'] = $title;
             }
         }
         $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
         $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
         $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');
         $fields = array_merge($fields, $tmpContactField);
         $fields = array_merge($fields, $tmpFields);
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
         self::$_importableFields = $fields;
     }
     return self::$_importableFields;
 }
Beispiel #29
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Contribute_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array();
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'cancel_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'receipt_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'thankyou_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'pledge_payment':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Contribute/DAO/Contribution.php';
         $tempIndieFields =& CRM_Contribute_DAO_Contribution::import();
         $indieFields = $tempIndieFields;
     }
     $paramValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $paramValues[$key] = $field;
     }
     //import contribution record according to select contact type
     if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_SKIP && ($paramValues['contribution_contact_id'] || $paramValues['external_identifier'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } else {
         if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE && ($paramValues['contribution_id'] || $values['trxn_id'] || $paramValues['invoice_id'])) {
             $paramValues['contact_type'] = $this->_contactType;
         } else {
             if (!empty($params['soft_credit'])) {
                 $paramValues['contact_type'] = $this->_contactType;
             } else {
                 if (CRM_Utils_Array::value('pledge_payment', $paramValues)) {
                     $paramValues['contact_type'] = $this->_contactType;
                 }
             }
         }
     }
     //need to pass $onDuplicate to check import mode.
     if (CRM_Utils_Array::value('pledge_payment', $paramValues)) {
         $paramValues['onDuplicate'] = $onDuplicate;
     }
     $formatError = _civicrm_contribute_formatted_param($paramValues, $formatted, true);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
         } else {
             if (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
                 return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
             }
         }
         return CRM_Contribute_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Contribute_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Contribution');
     } else {
         //fix for CRM-2219 - Update Contribution
         // onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE
         if ($paramValues['invoice_id'] || $paramValues['trxn_id'] || $paramValues['contribution_id']) {
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues));
             $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
             if ($ids['contribution']) {
                 $formatted['id'] = $ids['contribution'];
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatted['id'], 'Contribution');
                 //process note
                 if ($paramValues['note']) {
                     $noteID = array();
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
                     require_once 'CRM/Core/BAO/Note.php';
                     $daoNote =& new CRM_Core_BAO_Note();
                     $daoNote->entity_table = 'civicrm_contribution';
                     $daoNote->entity_id = $ids['contribution'];
                     if ($daoNote->find(true)) {
                         $noteID['id'] = $daoNote->id;
                     }
                     $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID);
                     CRM_Core_BAO_Note::add($noteParams, $noteID);
                     unset($formatted['note']);
                 }
                 //need to check existing soft credit contribution, CRM-3968
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     $dupeSoftCredit = array('contact_id' => $formatted['soft_credit_to'], 'contribution_id' => $ids['contribution']);
                     $existingSoftCredit = CRM_Contribute_BAO_Contribution::getSoftContribution($dupeSoftCredit);
                     if (CRM_Utils_Array::value('soft_credit_id', $existingSoftCredit)) {
                         $formatted['softID'] = $existingSoftCredit['soft_credit_id'];
                     }
                 }
                 $newContribution =& CRM_Contribute_BAO_Contribution::create($formatted, $ids);
                 $this->_newContributions[] = $newContribution->id;
                 //return soft valid since we need to show how soft credits were added
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Contribute_Import_Parser::VALID;
             } else {
                 $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID');
                 foreach ($dupeIds as $k => $v) {
                     if ($v) {
                         $errorMsg[] = "{$labels[$k]} {$v}";
                     }
                 }
                 $errorMsg = implode(' AND ', $errorMsg);
                 array_unshift($values, "Matching Contribution record not found for " . $errorMsg . ". Row was skipped.");
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         // set the contact type if its not set
         if (!isset($paramValues['contact_type'])) {
             $paramValues['contact_type'] = $this->_contactType;
         }
         //retrieve contact id using contact dedupe rule
         $error = civicrm_check_contact_dedupe($paramValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The contribution was not imported");
                 return CRM_Contribute_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = civicrm_contribution_format_create($formatted);
                 if (civicrm_error($newContribution)) {
                     if (is_array($newContribution['error_message'])) {
                         array_unshift($values, $newContribution['error_message']['message']);
                         if ($newContribution['error_message']['params'][0]) {
                             return CRM_Contribute_Import_Parser::DUPLICATE;
                         }
                     } else {
                         array_unshift($values, $newContribution['error_message']);
                         return CRM_Contribute_Import_Parser::ERROR;
                     }
                 }
                 $this->_newContributions[] = $newContribution['id'];
                 //return soft valid since we need to show how soft credits were added
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Contribute_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Contribute_Import_Parser::ERROR;
         }
     } else {
         if ($paramValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $paramValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $paramValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
         $newContribution = civicrm_contribution_format_create($formatted);
         if (civicrm_error($newContribution)) {
             if (is_array($newContribution['error_message'])) {
                 array_unshift($values, $newContribution['error_message']['message']);
                 if ($newContribution['error_message']['params'][0]) {
                     return CRM_Contribute_Import_Parser::DUPLICATE;
                 }
             } else {
                 array_unshift($values, $newContribution['error_message']);
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
         $this->_newContributions[] = $newContribution['id'];
         //return soft valid since we need to show how soft credits were added
         if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT;
         }
         // process pledge payment assoc w/ the contribution
         return self::processPledgePayments($formatted);
         return CRM_Contribute_Import_Parser::VALID;
     }
 }