/** * build all the data structures needed to build the form * * @return void * @access public */ function preProcess() { // reset action from the session $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'update'); $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE); $rcid = CRM_Utils_Request::retrieve('rcid', 'Positive', $this); $rcid = $rcid ? "&id={$rcid}" : ''; $session = CRM_Core_Session::singleton(); $session->pushUserContext(CRM_Utils_System::url('civicrm/user', "reset=1{$rcid}")); if ($this->_contactId) { $contact = new CRM_Contact_DAO_Contact(); $contact->id = $this->_contactId; if (!$contact->find(TRUE)) { CRM_Core_Error::statusBounce(ts('contact does not exist: %1', array(1 => $this->_contactId))); } $this->_contactType = $contact->contact_type; // check for permissions if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) { CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.')); } list($displayName, $contactImage) = CRM_Contact_BAO_Contact::getDisplayAndImage($this->_contactId); CRM_Utils_System::setTitle($displayName, $contactImage . ' ' . $displayName); } else { CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type')); } }
function validateData(&$input, &$ids, &$objects, $required = true) { // make sure contact exists and is valid require_once 'CRM/Contact/DAO/Contact.php'; $contact = new CRM_Contact_DAO_Contact(); $contact->id = $ids['contact']; if (!$contact->find(true)) { CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']}"); echo "Failure: Could not find contact record: {$ids['contact']}<p>"; return false; } // make sure contribution exists and is valid require_once 'CRM/Contribute/DAO/Contribution.php'; $contribution = new CRM_Contribute_DAO_Contribution(); $contribution->id = $ids['contribution']; if (!$contribution->find(true)) { CRM_Core_Error::debug_log_message("Could not find contribution record: {$contributionID}"); echo "Failure: Could not find contribution record for {$contributionID}<p>"; return false; } $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $objects['contact'] =& $contact; $objects['contribution'] =& $contribution; if (!$this->loadObjects($input, $ids, $objects, $required)) { return false; } return true; }
function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) { // make sure contact exists and is valid $contact = new CRM_Contact_DAO_Contact(); $contact->id = $ids['contact']; if (!$contact->find(TRUE)) { CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']}"); echo "Failure: Could not find contact record: {$ids['contact']}<p>"; return FALSE; } // make sure contribution exists and is valid $contribution = new CRM_Contribute_DAO_Contribution(); $contribution->id = $ids['contribution']; if (!$contribution->find(TRUE)) { CRM_Core_Error::debug_log_message("Could not find contribution record: " . $contribution->id); echo "Failure: Could not find contribution record for {$contribution->id}<p>"; return FALSE; } $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $objects['contact'] =& $contact; $objects['contribution'] =& $contribution; if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) { return FALSE; } return TRUE; }
/** * Both testDummy1 and testDummy2 have been created at some point (as part of the test runs), * but all the data was rolled-back * * @throws \Exception */ public static function tearDownAfterClass() { if (!is_numeric(self::$contactIds['testDummy1'])) { throw new \Exception("Uh oh! The static \$contactIds does not include testDummy1! Did the test fail to execute?"); } if (!is_numeric(self::$contactIds['testDummy2'])) { throw new \Exception("Uh oh! The static \$contactIds does not include testDummy2! Did the test fail to execute?"); } $dao = new \CRM_Contact_DAO_Contact(); $dao->id = self::$contactIds['testDummy1']; if ($dao->find()) { throw new \Exception("Uh oh! testDummy1 still exists!"); } $dao = new \CRM_Contact_DAO_Contact(); $dao->id = self::$contactIds['testDummy2']; if ($dao->find()) { throw new \Exception("Uh oh! testDummy2 still exists!"); } }
/** * Function to create navigation for CiviCRM Admin Menu * * @param int $contactID contact id * * @return string $navigation returns navigation html * @static */ static function createNavigation($contactID) { $config = CRM_Core_Config::singleton(); // if on frontend, do not create navigation menu items, CRM-5349 if ($config->userFrameworkFrontend) { return "<!-- {$config->lcMessages} -->"; } $navParams = array('contact_id' => $contactID); $navigation = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME, 'navigation', NULL, NULL, $contactID); // FIXME: hack for CRM-5027: we need to prepend the navigation string with // (HTML-commented-out) locale info so that we rebuild menu on locale changes if (!$navigation || substr($navigation, 0, 14) != "<!-- {$config->lcMessages} -->") { //retrieve navigation if it's not cached. $navigation = self::buildNavigation(); //add additional navigation items $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1'); $appendSring = "<li id=\"menu-logout\" class=\"menumain\"><a href=\"{$logoutURL}\">" . ts('Logout') . "</a></li>"; // get home menu from db $homeParams = array('name' => 'Home'); $homeNav = array(); self::retrieve($homeParams, $homeNav); if ($homeNav) { list($path, $q) = explode('&', $homeNav['url']); $homeURL = CRM_Utils_System::url($path, $q); $homeLabel = $homeNav['label']; // CRM-6804 (we need to special-case this as we don’t ts()-tag variables) if ($homeLabel == 'Home') { $homeLabel = ts('Home'); } } else { $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); $homeLabel = ts('Home'); } if ($config->userSystem->is_drupal && (module_exists('toolbar') && user_access('access toolbar') || module_exists('admin_menu') && user_access('access administration menu'))) { $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('Drupal Menu') . "</a></li></ul>"; } elseif ($config->userSystem->is_wordpress) { $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('WordPress Menu') . "</a></li></ul>"; } else { $prepandString = "<li class=\"menumain crm-link-home\"><a href=\"{$homeURL}\" title=\"" . $homeLabel . "\">" . $homeLabel . "</a>"; } // prepend the navigation with locale info for CRM-5027 $navigation = "<!-- {$config->lcMessages} -->" . $prepandString . $navigation . $appendSring; // before inserting check if contact id exists in db // this is to handle wierd case when contact id is in session but not in db $contact = new CRM_Contact_DAO_Contact(); $contact->id = $contactID; if ($contact->find(TRUE)) { CRM_Core_BAO_Setting::setItem($navigation, CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME, 'navigation', NULL, $contactID, $contactID); } } return $navigation; }
/** * This function is called when action is browse * * return null * @access public */ function browse() { $note =& new CRM_Core_DAO_Note(); $note->entity_table = 'civicrm_contact'; $note->entity_id = $this->_contactId; $note->orderBy('modified_date desc'); $values = array(); $links =& CRM_Contact_Page_View_Note::links(); $action = array_sum(array_keys($links)) & CRM_Core_Action::mask($this->_permission); $note->find(); while ($note->fetch()) { $values[$note->id] = array(); CRM_Core_DAO::storeValues($note, $values[$note->id]); $values[$note->id]['action'] = CRM_Core_Action::formLink($links, $action, array('id' => $note->id, 'cid' => $this->_contactId)); $contact = new CRM_Contact_DAO_Contact(); $contact->id = $note->contact_id; $contact->find(); $contact->fetch(); $values[$note->id]['createdBy'] = $contact->display_name; } $this->assign('notes', $values); }
private function addMembershipType() { $organizationDAO = new CRM_Contact_DAO_Contact(); $organizationDAO->id = 5; $organizationDAO->find(TRUE); $contact_id = $organizationDAO->contact_id; $membershipType = "INSERT INTO civicrm_membership_type\n (name, description, member_of_contact_id, financial_type_id, minimum_fee, duration_unit, duration_interval, period_type, fixed_period_start_day, fixed_period_rollover_day, relationship_type_id, relationship_direction, visibility, weight, is_active)\n VALUES\n ('General', 'Regular annual membership.', " . $contact_id . ", 2, 100, 'year', 1, 'rolling',null, null, 7, 'b_a', 'Public', 1, 1),\n ('Student', 'Discount membership for full-time students.', " . $contact_id . ", 2, 50, 'year', 1, 'rolling', null, null, 7, 'b_a', 'Public', 2, 1),\n ('Lifetime', 'Lifetime membership.', " . $contact_id . ", 2, 1200, 'lifetime', 1, 'rolling', null, null, 7, 'b_a', 'Admin', 3, 1);\n "; $this->_query($membershipType); }
/** * Function to build the form * * @return None * @access public */ function preProcess() { $this->_cdType = CRM_Utils_Array::value('type', $_GET); $this->assign('cdType', FALSE); if ($this->_cdType) { $this->assign('cdType', TRUE); return CRM_Custom_Form_CustomData::preProcess($this); } $this->_caseId = CRM_Utils_Request::retrieve('id', 'Positive', $this); $this->_currentlyViewedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this); if ($this->_action & CRM_Core_Action::ADD && !$this->_currentlyViewedContactId) { // check for add contacts permissions if (!CRM_Core_Permission::check('add contacts')) { CRM_Utils_System::permissionDenied(); return; } } //CRM-4418 if (!CRM_Core_Permission::checkActionPermission('CiviCase', $this->_action)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page')); } if ($this->_action & CRM_Core_Action::DELETE || $this->_action & CRM_Core_Action::RENEW) { return TRUE; } if (!$this->_caseId) { $caseAttributes = array('case_type' => CRM_Case_PseudoConstant::caseType(), 'case_status' => CRM_Case_PseudoConstant::caseStatus(), 'encounter_medium' => CRM_Case_PseudoConstant::encounterMedium()); foreach ($caseAttributes as $key => $values) { if (empty($values)) { CRM_Core_Error::fatal(ts('You do not have any active %1', array(1 => str_replace('_', ' ', $key)))); break; } } } if ($this->_action & CRM_Core_Action::ADD) { $this->_activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', 'Open Case', 'name'); if (!$this->_activityTypeId) { CRM_Core_Error::fatal(ts('The Open Case activity type is missing or disabled. Please have your site administrator check Administer > Option Lists > Activity Types for the CiviCase component.')); } } //check for case permissions. if (!CRM_Case_BAO_Case::accessCiviCase()) { CRM_Core_Error::fatal(ts('You are not authorized to access this page.')); } if ($this->_action & CRM_Core_Action::ADD && (!CRM_Core_Permission::check('access all cases and activities') && !CRM_Core_Permission::check('add cases'))) { CRM_Core_Error::fatal(ts('You are not authorized to access this page.')); } if ($this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, 'Case')) { $this->assign('activityTypeFile', $this->_activityTypeFile); } $details = CRM_Case_PseudoConstant::caseActivityType(FALSE); CRM_Utils_System::setTitle($details[$this->_activityTypeId]['label']); $this->assign('activityType', $details[$this->_activityTypeId]['label']); $this->assign('activityTypeDescription', $details[$this->_activityTypeId]['description']); if (isset($this->_currentlyViewedContactId)) { $contact = new CRM_Contact_DAO_Contact(); $contact->id = $this->_currentlyViewedContactId; if (!$contact->find(TRUE)) { CRM_Core_Error::statusBounce(ts('Client contact does not exist: %1', array(1 => $this->_currentlyViewedContactId))); } $this->assign('clientName', $contact->display_name); } $session = CRM_Core_Session::singleton(); $this->_currentUserId = $session->get('userID'); //when custom data is included in this page CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeId, 1, 'Activity'); eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}::preProcess( \$this );"); $activityGroupTree = $this->_groupTree; // for case custom fields to populate with defaults if (CRM_Utils_Array::value('hidden_custom', $_POST)) { CRM_Custom_Form_CustomData::preProcess($this); CRM_Custom_Form_CustomData::buildQuickForm($this); } // so that grouptree is not populated with case fields, since the grouptree is used // for populating activity custom fields. $this->_groupTree = $activityGroupTree; }
/** * 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; }
/** * Recursive function to get all descendent notes of the note with given ID. * * @param int $parentId * ID of the note to start from. * @param int $maxDepth * Maximum number of levels to descend into the tree; if not given, will include all descendents. * @param bool $snippet * If TRUE, returned values will be pre-formatted for display in a table of notes. * @param array $tree * (Reference) Variable to store all found descendents. * @param int $depth * Depth of current iteration within the descendent tree (used for comparison against maxDepth). * * @return array * Nested associative array beginning with direct children of given note. */ private static function buildNoteTree($parentId, $maxDepth = 0, $snippet = FALSE, &$tree = array(), $depth = 0) { if ($maxDepth && $depth > $maxDepth) { return FALSE; } // get direct children of given parentId note $note = new CRM_Core_DAO_Note(); $note->entity_table = 'civicrm_note'; $note->entity_id = $parentId; $note->orderBy('modified_date asc'); $note->find(); while ($note->fetch()) { // foreach child, call this function, unless the child is private/hidden if (!self::getNotePrivacyHidden($note)) { CRM_Core_DAO::storeValues($note, $tree[$note->id]); // get name of user that created this note $contact = new CRM_Contact_DAO_Contact(); $createdById = $note->contact_id; $contact->id = $createdById; $contact->find(); $contact->fetch(); $tree[$note->id]['createdBy'] = $contact->display_name; $tree[$note->id]['createdById'] = $createdById; $tree[$note->id]['modified_date'] = CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']); // paper icon view for attachments part $paperIconAttachmentInfo = CRM_Core_BAO_File::paperIconAttachment('civicrm_note', $note->id); $tree[$note->id]['attachment'] = $paperIconAttachmentInfo ? implode('', $paperIconAttachmentInfo) : ''; if ($snippet) { $tree[$note->id]['note'] = nl2br($tree[$note->id]['note']); $tree[$note->id]['note'] = smarty_modifier_mb_truncate($tree[$note->id]['note'], 80, '...', TRUE); CRM_Utils_Date::customFormat($tree[$note->id]['modified_date']); } self::buildNoteTree($note->id, $maxDepth, $snippet, $tree[$note->id]['child'], $depth + 1); } } return $tree; }
/** * 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; } }
/** * Required params * * From import record usually: * 'contact_id', * 'contact_display_name', * 'net_amount', * 'received_date', * * This usually goes from the form: * 'payment_instrument_id', * 'contribution_type_id', * 'campaign_id', * * And from the code: * 'batch_id', * 'weight', * * Optional: * 'transaction_id' * * @param array $params * @return type */ protected function createBatchEntry(array $params) { //preload what we can // if(isset($params['VARef'])) { // require_once 'CRM/Contact/DAO/Contact.php'; // $contact = new CRM_Contact_DAO_Contact(); // $contact->external_identifier = $params['VARef']; // $contact->find(); // if($contact->fetch() === false) { // throw new Exception("Can't load contact using extenal_id = '{$params['VARef']}'"); // } // // $params['contact_id'] = $contact->id; // $params['contactDisplayName'] = $contact->display_name; // } //check mandatory $params - others are checked in CRM_Batch_BAO_Batch::createContribution() foreach (array() as $param) { if (empty($params[$param])) { throw new InvalidArgumentException("No param[{$param}] when creating the batch entry"); } } if (!isset($params['contact_display_name']) && isset($params['contact_id'])) { require_once 'CRM/Contact/DAO/Contact.php'; $contact = new CRM_Contact_DAO_Contact(); $contact->id = $params['contact_id']; $contact->find(); if ($contact->fetch() === false) { throw new Exception("Can't find user with id = '{$params['contact_id']}'"); } //$params['contact_id'] = $contact->id; $params['contact_display_name'] = $contact->display_name; } try { require_once 'CRM/Finance/BAO/Batch.php'; return CRM_Finance_BAO_Batch::createContribution($params); } catch (RuntimeException $e) { throw new CRM_Finance_BAO_Import_ProcessException($e->getMessage(), $e->getCode(), $e); } }
/** * 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; }
/** * updates contacts affected by the option value passed. * * @param Integer $optionValueId the option value id. * @param int $action the action describing whether prefix/suffix was UPDATED or DELETED * * @return void */ static function updateRecords(&$optionValueId, $action) { //finding group name $optionValue =& new CRM_Core_DAO_OptionValue(); $optionValue->id = $optionValueId; $optionValue->find(true); $optionGroup =& new CRM_Core_DAO_OptionGroup(); $optionGroup->id = $optionValue->option_group_id; $optionGroup->find(true); $gName = $optionGroup->name; //group name $value = $optionValue->value; //value // get the proper group name & affected field name $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id'); $contributions = array('payment_instrument' => 'payment_instrument_id'); $activities = array('activity_type' => 'activity_type_id'); $participant = array('participant_role' => 'role_id'); $eventType = array('event_type' => 'event_type_id'); $aclRole = array('acl_role' => 'acl_role_id'); $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole); $fieldName = ''; foreach ($all as $name => $id) { if ($gName == $name) { $fieldName = $id; } } if ($fieldName == '') { return true; } if (array_key_exists($gName, $individuals)) { require_once 'CRM/Contact/BAO/Contact.php'; $contactDAO =& new CRM_Contact_DAO_Contact(); $contactDAO->{$fieldName} = $value; $contactDAO->find(); while ($contactDAO->fetch()) { if ($action == CRM_Core_Action::DELETE) { $contact = new CRM_Contact_DAO_Contact(); $contact->id = $contactDAO->id; $contact->find(true); // make sure dates doesn't get reset $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); $contact->{$fieldName} = 'NULL'; $contact->save(); } } return true; } if (array_key_exists($gName, $contributions)) { require_once 'CRM/Contribute/DAO/Contribution.php'; $contribution =& new CRM_Contribute_DAO_Contribution(); $contribution->{$fieldName} = $value; $contribution->find(); while ($contribution->fetch()) { if ($action == CRM_Core_Action::DELETE) { $contribution->{$fieldName} = 'NULL'; $contribution->save(); } } return true; } if (array_key_exists($gName, $activities)) { require_once 'CRM/Activity/DAO/Activity.php'; $activity =& new CRM_Activity_DAO_Activity(); $activity->{$fieldName} = $value; $activity->find(); while ($activity->fetch()) { $activity->delete(); } return true; } //delete participant role, type and event type option value if (array_key_exists($gName, $participant)) { require_once 'CRM/Event/DAO/Participant.php'; $participantValue =& new CRM_Event_DAO_Participant(); $participantValue->{$fieldName} = $value; if ($participantValue->find(true)) { return false; } return true; } //delete event type option value if (array_key_exists($gName, $eventType)) { require_once 'CRM/Event/DAO/Event.php'; $event =& new CRM_Event_DAO_Event(); $event->{$fieldName} = $value; if ($event->find(true)) { return false; } return true; } //delete acl_role option value if (array_key_exists($gName, $aclRole)) { require_once 'CRM/ACL/DAO/EntityRole.php'; require_once 'CRM/ACL/DAO/ACL.php'; $entityRole =& new CRM_ACL_DAO_EntityRole(); $entityRole->{$fieldName} = $value; $aclDAO =& new CRM_ACL_DAO_ACL(); $aclDAO->entity_id = $value; if ($entityRole->find(true) || $aclDAO->find(true)) { return false; } return true; } }
function revert($tables) { // FIXME: split off the table → DAO mapping to a GenCode-generated class $daos = array('civicrm_address' => 'CRM_Core_DAO_Address', 'civicrm_contact' => 'CRM_Contact_DAO_Contact', 'civicrm_email' => 'CRM_Core_DAO_Email', 'civicrm_im' => 'CRM_Core_DAO_IM', 'civicrm_openid' => 'CRM_Core_DAO_OpenID', 'civicrm_phone' => 'CRM_Core_DAO_Phone', 'civicrm_website' => 'CRM_Core_DAO_Website', 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution', 'civicrm_note' => 'CRM_Core_DAO_Note', 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship'); // get custom data tables, columns and types $ctypes = array(); $dao = CRM_Core_DAO::executeQuery('SELECT table_name, column_name, data_type FROM civicrm_custom_group cg JOIN civicrm_custom_field cf ON (cf.custom_group_id = cg.id)'); while ($dao->fetch()) { if (!isset($ctypes[$dao->table_name])) { $ctypes[$dao->table_name] = array('entity_id' => 'Integer'); } $ctypes[$dao->table_name][$dao->column_name] = $dao->data_type; } $differ = new CRM_Logging_Differ($this->log_conn_id, $this->log_date); $diffs = $differ->diffsInTables($tables); $deletes = array(); $reverts = array(); foreach ($diffs as $table => $changes) { foreach ($changes as $change) { switch ($change['action']) { case 'Insert': if (!isset($deletes[$table])) { $deletes[$table] = array(); } $deletes[$table][] = $change['id']; break; case 'Delete': case 'Update': if (!isset($reverts[$table])) { $reverts[$table] = array(); } if (!isset($reverts[$table][$change['id']])) { $reverts[$table][$change['id']] = array('log_action' => $change['action']); } $reverts[$table][$change['id']][$change['field']] = $change['from']; break; } } } // revert inserts by deleting foreach ($deletes as $table => $ids) { CRM_Core_DAO::executeQuery("DELETE FROM `{$table}` WHERE id IN (" . implode(', ', array_unique($ids)) . ')'); } // revert updates by updating to previous values foreach ($reverts as $table => $row) { switch (TRUE) { // DAO-based tables case in_array($table, array_keys($daos)): require_once str_replace('_', DIRECTORY_SEPARATOR, $daos[$table]) . '.php'; eval("\$dao = new {$daos[$table]};"); foreach ($row as $id => $changes) { $dao->id = $id; foreach ($changes as $field => $value) { if ($field == 'log_action') { continue; } if (empty($value) and $value !== 0 and $value !== '0') { $value = 'null'; } $dao->{$field} = $value; } $changes['log_action'] == 'Delete' ? $dao->insert() : $dao->update(); $dao->reset(); } break; // custom data tables // custom data tables case in_array($table, array_keys($ctypes)): foreach ($row as $id => $changes) { $inserts = array('id' => '%1'); $updates = array(); $params = array(1 => array($id, 'Integer')); $counter = 2; foreach ($changes as $field => $value) { // don’t try reverting a field that’s no longer there if (!isset($ctypes[$table][$field])) { continue; } switch ($ctypes[$table][$field]) { case 'Date': $value = substr(CRM_Utils_Date::isoToMysql($value), 0, 8); break; case 'Timestamp': $value = CRM_Utils_Date::isoToMysql($value); break; } $inserts[$field] = "%{$counter}"; $updates[] = "{$field} = %{$counter}"; $params[$counter] = array($value, $ctypes[$table][$field]); $counter++; } if ($changes['log_action'] == 'Delete') { $sql = "INSERT INTO `{$table}` (" . implode(', ', array_keys($inserts)) . ') VALUES (' . implode(', ', $inserts) . ')'; } else { $sql = "UPDATE `{$table}` SET " . implode(', ', $updates) . ' WHERE id = %1'; } CRM_Core_DAO::executeQuery($sql, $params); } break; } } // CRM-7353: if nothing altered civicrm_contact, touch it; this will // make sure there’s an entry in log_civicrm_contact for this revert if (empty($diffs['civicrm_contact'])) { $query = "\n SELECT id FROM `{$this->db}`.log_civicrm_contact\n WHERE log_conn_id = %1 AND log_date BETWEEN DATE_SUB(%2, INTERVAL 10 SECOND) AND DATE_ADD(%2, INTERVAL 10 SECOND)\n ORDER BY log_date DESC LIMIT 1\n "; $params = array(1 => array($this->log_conn_id, 'Integer'), 2 => array($this->log_date, 'String')); $cid = CRM_Core_DAO::singleValueQuery($query, $params); if (!$cid) { return; } $dao = new CRM_Contact_DAO_Contact(); $dao->id = $cid; if ($dao->find(TRUE)) { // CRM-8102: MySQL can’t parse its own dates $dao->birth_date = CRM_Utils_Date::isoToMysql($dao->birth_date); $dao->deceased_date = CRM_Utils_Date::isoToMysql($dao->deceased_date); $dao->save(); } } }
/** * 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) { $ei = CRM_Appraisals_ExportImportValuesConverter::singleton(); $response = $this->summary($values); $this->formatDateParams(); $this->_params['skipRecentView'] = TRUE; $this->_params['check_permissions'] = TRUE; $params = $this->getActiveFieldParams(); $rowParams = array(); $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } $importedAppraisalCycleId = null; if (!empty($params['appraisal_cycle_id'])) { $importedAppraisalCycleId = (int) $params['appraisal_cycle_id']; } if (!$importedAppraisalCycleId) { $importedAppraisalCycleId = $this->_appraisalCycleIdIncremental++; } if (empty($params['contact_id']) && !empty($params['email'])) { $checkEmail = new CRM_Core_BAO_Email(); $checkEmail->email = $params['email']; $checkEmail->find(TRUE); if (!empty($checkEmail->contact_id)) { $params['contact_id'] = $checkEmail->contact_id; } } if (!empty($formatValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if (!empty($params['contact_id']) && $params['contact_id'] != $checkCid->id) { array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $params['contact_id']); return CRM_Import_Parser::ERROR; } if (!empty($checkCid->id)) { $params['contact_id'] = $checkCid->id; } } if (empty($params['contact_id']) && (int) $params['status_id']) { $error = 'Missing "contact_id" / "email" / "external_identifier" value.'; array_unshift($values, $error); return CRM_Import_Parser::ERROR; } foreach ($this->_entity as $tableName => $entity) { $rowParams[$entity] = $this->getEntityParams($entity); if ($entity === 'AppraisalCycle' && $importedAppraisalCycleId) { $rowParams[$entity]['id'] = $importedAppraisalCycleId; } foreach ($rowParams[$entity] as $key => $value) { $rowParams[$entity][$key] = $ei->import($tableName, $key, $value); } } if (empty($this->_appraisalCycleIds[$importedAppraisalCycleId])) { try { unset($rowParams['AppraisalCycle']['id']); $appraisalCycleCreateResponse = civicrm_api3('AppraisalCycle', 'create', $rowParams['AppraisalCycle']); } catch (CiviCRM_API3_Exception $e) { $error = $e->getMessage(); array_unshift($values, $error); return CRM_Import_Parser::ERROR; } $this->_appraisalCycleIds[$importedAppraisalCycleId] = (int) $appraisalCycleCreateResponse['id']; } $localAppraisalCycleId = $this->_appraisalCycleIds[$importedAppraisalCycleId]; if (!empty($params['contact_id']) && (int) $params['contact_id']) { try { unset($rowParams['Appraisal']['id']); unset($rowParams['Appraisal']['external_identifier']); unset($rowParams['Appraisal']['email']); $rowParams['Appraisal']['appraisal_cycle_id'] = $localAppraisalCycleId; civicrm_api3('Appraisal', 'create', $rowParams['Appraisal']); } catch (CiviCRM_API3_Exception $e) { $error = $e->getMessage(); array_unshift($values, $error); return CRM_Import_Parser::ERROR; } } }
/** * Set default values for the form. */ public function setDefaultValues() { $defaults = array(); if ($this->_action & CRM_Core_Action::UPDATE) { if (!empty($this->_values)) { $defaults['relationship_type_id'] = $this->_rtypeId; if (!empty($this->_values['start_date'])) { list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']); } if (!empty($this->_values['end_date'])) { list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']); } $defaults['description'] = CRM_Utils_Array::value('description', $this->_values); $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values); // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_' . $this->_rtype, $this->_values); $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_' . strrev($this->_rtype), $this->_values); $defaults['is_current_employer'] = $this->_isCurrentEmployer; // Load info about the related contact $contact = new CRM_Contact_DAO_Contact(); if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) { $contact->id = $this->_values['contact_id_b']; } else { $contact->id = $this->_values['contact_id_a']; } if ($contact->find(TRUE)) { $defaults['related_contact_id'] = $contact->id; $this->_display_name_b = $contact->display_name; $this->assign('display_name_b', $this->_display_name_b); } $noteParams = array('entity_id' => $this->_relationshipId, 'entity_table' => 'civicrm_relationship', 'limit' => 1, 'version' => 3); $note = civicrm_api('Note', 'getsingle', $noteParams); $defaults['note'] = CRM_Utils_Array::value('note', $note); } } else { $defaults['is_active'] = $defaults['is_current_employer'] = 1; $defaults['relationship_type_id'] = $this->_rtypeId; } $this->_enabled = $defaults['is_active']; return $defaults; }
public function getContactById($id) { $contactId = null; // id: if (!empty($id)) { $checkId = new CRM_Contact_DAO_Contact(); $checkId->id = $id; $checkId->find(TRUE); if (!empty($checkId->id)) { $contactId = $checkId->id; } } return $contactId; }
/** * Delete a contact and all its associated records. * * @param int $id * Id of the contact to delete. * @param bool $restore * Whether to actually restore, not delete. * @param bool $skipUndelete * Whether to force contact delete or not. * * @return bool * Was contact deleted? */ public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) { if (!$id) { return FALSE; } // If trash is disabled in system settings then we always skip if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_undelete', NULL, 1)) { $skipUndelete = TRUE; } // make sure we have edit permission for this contact // before we delete if ($skipUndelete && !CRM_Core_Permission::check('delete contacts') || $restore && !CRM_Core_Permission::check('access deleted contacts')) { return FALSE; } // CRM-12929 // Restrict contact to be delete if contact has financial trxns $error = NULL; if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) { return FALSE; } // make sure this contact_id does not have any membership types $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $id, 'id', 'member_of_contact_id'); if ($membershipTypeID) { return FALSE; } $contact = new CRM_Contact_DAO_Contact(); $contact->id = $id; if (!$contact->find(TRUE)) { return FALSE; } $contactType = $contact->contact_type; // currently we only clear employer cache. // we are now deleting inherited membership if any. if ($contact->contact_type == 'Organization') { $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE; $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id); if (!empty($relationshipDtls)) { foreach ($relationshipDtls as $rId => $details) { CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action); } } CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id); } if ($restore) { return self::contactTrashRestore($contact, TRUE); } // start a new transaction $transaction = new CRM_Core_Transaction(); if ($skipUndelete) { CRM_Utils_Hook::pre('delete', $contactType, $id, CRM_Core_DAO::$_nullArray); //delete billing address if exists. CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id); // delete the log entries since we dont have triggers enabled as yet $logDAO = new CRM_Core_DAO_Log(); $logDAO->entity_table = 'civicrm_contact'; $logDAO->entity_id = $id; $logDAO->delete(); // delete contact participants CRM-12155 CRM_Event_BAO_Participant::deleteContactParticipant($id); // delete contact contributions CRM-12155 CRM_Contribute_BAO_Contribution::deleteContactContribution($id); // do activity cleanup, CRM-5604 CRM_Activity_BAO_Activity::cleanupActivity($id); // delete all notes related to contact CRM_Core_BAO_Note::cleanContactNotes($id); // delete cases related to contact $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id); if (!empty($contactCases)) { foreach ($contactCases as $caseId) { //check if case is associate with other contact or not. $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId); if (count($caseContactId) <= 1) { CRM_Case_BAO_Case::deleteCase($caseId); } } } $contact->delete(); } else { self::contactTrashRestore($contact); } //delete the contact id from recently view CRM_Utils_Recent::delContact($id); // Update the group contact cache if ($restore) { CRM_Contact_BAO_GroupContactCache::remove(); } else { CRM_Contact_BAO_GroupContactCache::removeContact($id); } // delete any dupe cache entry CRM_Core_BAO_PrevNextCache::deleteItem($id); $transaction->commit(); if ($skipUndelete) { CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact); } // also reset the DB_DO global array so we can reuse the memory // http://issues.civicrm.org/jira/browse/CRM-4387 CRM_Core_DAO::freeResult(); return TRUE; }
/** * Reset navigation for all contacts or a specified contact. * * @param int $contactID * Reset only entries belonging to that contact ID. * * @return string */ public static function resetNavigation($contactID = NULL) { $newKey = CRM_Utils_String::createRandom(self::CACHE_KEY_STRLEN, CRM_Utils_String::ALPHANUMERIC); if (!$contactID) { $query = "UPDATE civicrm_setting SET value = '{$newKey}' WHERE name='navigation' AND contact_id IS NOT NULL"; CRM_Core_DAO::executeQuery($query); CRM_Core_BAO_Cache::deleteGroup('navigation'); } else { // before inserting check if contact id exists in db // this is to handle weird case when contact id is in session but not in db $contact = new CRM_Contact_DAO_Contact(); $contact->id = $contactID; if ($contact->find(TRUE)) { CRM_Core_BAO_Setting::setItem($newKey, CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME, 'navigation', NULL, $contactID, $contactID); } } // also reset the dashlet cache in case permissions have changed etc // FIXME: decouple this CRM_Core_BAO_Dashboard::resetDashletCache($contactID); return $newKey; }
/** * 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; } }
/** * This function is called when action is browse * * return null * @access public */ function browse() { $note = new CRM_Core_DAO_Note(); $note->entity_table = 'civicrm_contact'; $note->entity_id = $this->_contactId; $note->orderBy('modified_date desc'); //CRM-4418, handling edit and delete separately. $permissions = array($this->_permission); if ($this->_permission == CRM_Core_Permission::EDIT) { //previously delete was subset of edit //so for consistency lets grant delete also. $permissions[] = CRM_Core_Permission::DELETE; } $mask = CRM_Core_Action::mask($permissions); $values = array(); $links = self::links(); $action = array_sum(array_keys($links)) & $mask; $note->find(); while ($note->fetch()) { if (!CRM_Core_BAO_Note::getNotePrivacyHidden($note)) { CRM_Core_DAO::storeValues($note, $values[$note->id]); $values[$note->id]['action'] = CRM_Core_Action::formLink($links, $action, array('id' => $note->id, 'cid' => $this->_contactId)); $contact = new CRM_Contact_DAO_Contact(); $contact->id = $note->contact_id; $contact->find(); $contact->fetch(); $values[$note->id]['createdBy'] = $contact->display_name; $values[$note->id]['comment_count'] = CRM_Core_BAO_Note::getChildCount($note->id); } } $this->assign('notes', $values); $commentLinks = self::commentLinks(); $action = array_sum(array_keys($commentLinks)) & $mask; $commentAction = CRM_Core_Action::formLink($commentLinks, $action, array('id' => $note->id, 'pid' => $note->entity_id, 'cid' => $note->entity_id)); $this->assign('commentAction', $commentAction); }
/** * This function sets the default values for the form. Relationship that in edit/view mode * the default values are retrieved from the database * * @access public * @return None */ function setDefaultValues() { if ($this->_cdType) { return CRM_Custom_Form_CustomData::setDefaultValues($this); } $defaults = array(); if ($this->_action & CRM_Core_Action::UPDATE) { if (!empty($this->_values)) { $defaults['relationship_type_id'] = $this->_rtypeId; if (CRM_Utils_Array::value('start_date', $this->_values)) { list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']); } if (CRM_Utils_Array::value('end_date', $this->_values)) { list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']); } $defaults['description'] = CRM_Utils_Array::value('description', $this->_values); $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values); $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $this->_values); $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $this->_values); $contact = new CRM_Contact_DAO_Contact(); if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) { $contact->id = $this->_values['contact_id_b']; } else { $contact->id = $this->_values['contact_id_a']; } if ($contact->find(true)) { $this->_display_name_b = $contact->display_name; $this->assign('sort_name_b', $this->_display_name_b); //is current employee/employer. if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of' && $contact->id == CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'employer_id')) { $defaults['is_current_employer'] = 1; $this->_values['current_employee_id'] = $this->_contactId; $this->_values['current_employer_id'] = $contact->id; } else { if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of' && $this->_contactId == $contact->employer_id) { $defaults['is_current_employer'] = 1; $this->_values['current_employee_id'] = $contact->id; $this->_values['current_employer_id'] = $this->_contactId; } } } $relationshipID = $this->_values['id']; $query = "SELECT id, note FROM civicrm_note where entity_table = 'civicrm_relationship' and entity_id = {$relationshipID} order by modified_date desc"; $dao = new CRM_Core_DAO(); $dao->query($query); if ($dao->fetch($query)) { $defaults['note'] = $dao->note; } } } else { $defaults['is_active'] = 1; $defaults['relationship_type_id'] = $this->_rtypeId; } return $defaults; }
static function clearCurrentEmployer($id, $action) { $relationship = new CRM_Contact_DAO_Relationship(); $relationship->id = $id; $relationship->find(TRUE); //to delete relationship between household and individual \ //or between individual and orgnization if ($action & CRM_Core_Action::DISABLE || $action & CRM_Core_Action::DELETE) { if ($relationship->relationship_type_id == 4 || $relationship->relationship_type_id == 7) { $sharedContact = new CRM_Contact_DAO_Contact(); $sharedContact->id = $relationship->contact_id_a; $sharedContact->find(TRUE); if ($relationship->relationship_type_id == 4 && $relationship->contact_id_b == $sharedContact->employer_id) { CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a); } } } return $relationship; }
/** * Delete current employer relationship. * * @param int $id * @param int $action * * @return CRM_Contact_DAO_Relationship */ public static function clearCurrentEmployer($id, $action) { $relationship = new CRM_Contact_DAO_Relationship(); $relationship->id = $id; $relationship->find(TRUE); //to delete relationship between household and individual \ //or between individual and organization if ($action & CRM_Core_Action::DISABLE || $action & CRM_Core_Action::DELETE) { $relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name')); if (isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id'] || isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id']) { $sharedContact = new CRM_Contact_DAO_Contact(); $sharedContact->id = $relationship->contact_id_a; $sharedContact->find(TRUE); // CRM-15881 UPDATES // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..." // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4) // As suggested by @davecivicrm, the employee relationship type id is fetched using the CRM_Core_DAO::getFieldValue() class and method, since these ids differ from system to system. $employerRelTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'); if ($relationship->relationship_type_id == $employerRelTypeId && $relationship->contact_id_b == $sharedContact->employer_id) { CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a); } } } return $relationship; }
/** * Return dupes of a given contact, using the default rule group (of a provided level). * * @param int $cid contact id of the given contact * @param string $level dedupe rule group level ('Fuzzy' or 'Strict') * @param string $ctype contact type of the given contact * * @return array array of dupe contact_ids */ static function dupesOfContact($cid, $level = 'Strict', $ctype = NULL) { // if not provided, fetch the contact type from the database if (!$ctype) { $dao = new CRM_Contact_DAO_Contact(); $dao->id = $cid; if (!$dao->find(TRUE)) { CRM_Core_Error::fatal("contact id of {$cid} does not exist"); } $ctype = $dao->contact_type; } $rgBao = new CRM_Dedupe_BAO_RuleGroup(); $rgBao->level = $level; $rgBao->contact_type = $ctype; $rgBao->is_default = 1; if (!$rgBao->find(TRUE)) { CRM_Core_Error::fatal("{$level} rule for {$ctype} does not exist"); } $dupes = self::dupes($rgBao->id, array($cid)); // get the dupes for this cid $result = array(); foreach ($dupes as $dupe) { if ($dupe[0] == $cid) { $result[] = $dupe[1]; } elseif ($dupe[1] == $cid) { $result[] = $dupe[0]; } } return $result; }
/** * Updates contacts affected by the option value passed. * * @param int $optionValueId * The option value id. * @param int $action * The action describing whether prefix/suffix was UPDATED or DELETED. * * @return bool */ public static function updateRecords(&$optionValueId, $action) { //finding group name $optionValue = new CRM_Core_DAO_OptionValue(); $optionValue->id = $optionValueId; $optionValue->find(TRUE); $optionGroup = new CRM_Core_DAO_OptionGroup(); $optionGroup->id = $optionValue->option_group_id; $optionGroup->find(TRUE); // group name $gName = $optionGroup->name; // value $value = $optionValue->value; // get the proper group name & affected field name // todo: this may no longer be needed for individuals - check inputs $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id', 'communication_style' => 'communication_style_id'); $contributions = array('payment_instrument' => 'payment_instrument_id'); $activities = array('activity_type' => 'activity_type_id'); $participant = array('participant_role' => 'role_id'); $eventType = array('event_type' => 'event_type_id'); $aclRole = array('acl_role' => 'acl_role_id'); $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole); $fieldName = ''; foreach ($all as $name => $id) { if ($gName == $name) { $fieldName = $id; } } if ($fieldName == '') { return TRUE; } if (array_key_exists($gName, $individuals)) { $contactDAO = new CRM_Contact_DAO_Contact(); $contactDAO->{$fieldName} = $value; $contactDAO->find(); while ($contactDAO->fetch()) { if ($action == CRM_Core_Action::DELETE) { $contact = new CRM_Contact_DAO_Contact(); $contact->id = $contactDAO->id; $contact->find(TRUE); // make sure dates doesn't get reset $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); $contact->{$fieldName} = 'NULL'; $contact->save(); } } return TRUE; } if (array_key_exists($gName, $contributions)) { $contribution = new CRM_Contribute_DAO_Contribution(); $contribution->{$fieldName} = $value; $contribution->find(); while ($contribution->fetch()) { if ($action == CRM_Core_Action::DELETE) { $contribution->{$fieldName} = 'NULL'; $contribution->save(); } } return TRUE; } if (array_key_exists($gName, $activities)) { $activity = new CRM_Activity_DAO_Activity(); $activity->{$fieldName} = $value; $activity->find(); while ($activity->fetch()) { $activity->delete(); } return TRUE; } //delete participant role, type and event type option value if (array_key_exists($gName, $participant)) { $participantValue = new CRM_Event_DAO_Participant(); $participantValue->{$fieldName} = $value; if ($participantValue->find(TRUE)) { return FALSE; } return TRUE; } //delete event type option value if (array_key_exists($gName, $eventType)) { $event = new CRM_Event_DAO_Event(); $event->{$fieldName} = $value; if ($event->find(TRUE)) { return FALSE; } return TRUE; } //delete acl_role option value if (array_key_exists($gName, $aclRole)) { $entityRole = new CRM_ACL_DAO_EntityRole(); $entityRole->{$fieldName} = $value; $aclDAO = new CRM_ACL_DAO_ACL(); $aclDAO->entity_id = $value; if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) { return FALSE; } return TRUE; } }
static function clearCurrentEmployer($id, $action) { $relationship = new CRM_Contact_DAO_Relationship(); $relationship->id = $id; $relationship->find(TRUE); //to delete relationship between household and individual \ //or between individual and orgnization if ($action & CRM_Core_Action::DISABLE || $action & CRM_Core_Action::DELETE) { $relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name')); if ($relationship->relationship_type_id == $relTypes['Employee of']['id'] || $relationship->relationship_type_id == $relTypes['Household Member of']['id']) { $sharedContact = new CRM_Contact_DAO_Contact(); $sharedContact->id = $relationship->contact_id_a; $sharedContact->find(TRUE); if ($relationship->relationship_type_id == 4 && $relationship->contact_id_b == $sharedContact->employer_id) { CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a); } } } return $relationship; }
/** * 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; } }
/** * * @param array $params * * @return array * <type> */ function _civicrm_api3_deprecated_duplicate_formatted_contact($params) { $id = CRM_Utils_Array::value('id', $params); $externalId = CRM_Utils_Array::value('external_identifier', $params); if ($id || $externalId) { $contact = new CRM_Contact_DAO_Contact(); $contact->id = $id; $contact->external_identifier = $externalId; if ($contact->find(TRUE)) { if ($params['contact_type'] != $contact->contact_type) { return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types"); } $error = CRM_Core_Error::createError("Found matching contacts: {$contact->id}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $contact->id); return civicrm_api3_create_error($error->pop()); } } else { require_once 'CRM/Dedupe/Finder.php'; $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']); $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised'); if (!empty($ids)) { $ids = implode(',', $ids); $error = CRM_Core_Error::createError("Found matching contacts: {$ids}", CRM_Core_Error::DUPLICATE_CONTACT, 'Fatal', $ids); return civicrm_api3_create_error($error->pop()); } } return civicrm_api3_create_success(TRUE); }