/** * process the form * * @return void * @access public */ public function postProcess() { // Process / save custom data // Get the form values and groupTree $params = $this->controller->exportValues($this->_name); CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_contactId, $this->_entityType); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); $customGroupResult = civicrm_api3('CustomGroup', 'get', array('id' => $this->_groupID, 'sequential' => 1)); if ($customGroupResult['count']) { $customGroup = CRM_Utils_Array::first($customGroupResult['values']); if ($customGroup['name'] === 'HRJobContract_Summary') { $jobContractsResult = civicrm_api3('HRJobContract', 'get', array('sequential' => 1, 'contact_id' => $this->_contactId, 'return' => "period_start_date,period_end_date")); foreach ($jobContractsResult['values'] as $jobContract) { if ($jobContract['is_current'] && !$jobContract['deleted']) { $jobContractSummaryDates = $this->_getJobContractSummaryDates($this->_groupTree[$this->_groupID]['fields'], $params); $createParams = array('sequential' => 1, 'jobcontract_id' => $jobContract['id']); if (empty($jobContract['period_start_date']) && !empty($jobContractSummaryDates['startDate'])) { $createParams['period_start_date'] = $jobContractSummaryDates['startDate']; } if ((empty($jobContract['period_end_date']) || $jobContract['period_end_date'] > $jobContractSummaryDates['endDate']) && !empty($jobContractSummaryDates['endDate'])) { $createParams['period_end_date'] = $jobContractSummaryDates['endDate']; } $result = civicrm_api3('HRJobDetails', 'create', $createParams); } } } } $this->response(); }
/** * Process the activities. * * @param array $params * Associated array of the submitted values. * * @throws CRM_Core_Exception * * @return CRM_Activity_BAO_Activity|null|object */ public static function create(&$params) { // check required params if (!self::dataExists($params)) { throw new CRM_Core_Exception('Not enough data to create activity object'); } $activity = new CRM_Activity_DAO_Activity(); if (isset($params['id']) && empty($params['id'])) { unset($params['id']); } if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) { if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) { $params['status_id'] = 2; } else { $params['status_id'] = 1; } } // Set priority to Normal for Auto-populated activities (for Cases) if (CRM_Utils_Array::value('priority_id', $params) === NULL && !CRM_Utils_Array::value('id', $params)) { $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'); $params['priority_id'] = array_search('Normal', $priority); } if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) { $params['target_contact_id'] = array_unique($params['target_contact_id']); } if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) { $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']); } // CRM-9137 if (!empty($params['id'])) { CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params); } else { CRM_Utils_Hook::pre('create', 'Activity', NULL, $params); } $activity->copyValues($params); if (isset($params['case_id'])) { // CRM-8708, preserve case ID even though it's not part of the SQL model $activity->case_id = $params['case_id']; } elseif (is_numeric($activity->id)) { // CRM-8708, preserve case ID even though it's not part of the SQL model $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id); } // start transaction $transaction = new CRM_Core_Transaction(); $result = $activity->save(); if (is_a($result, 'CRM_Core_Error')) { $transaction->rollback(); return $result; } $activityId = $activity->id; $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); if (isset($params['source_contact_id'])) { $acParams = array('activity_id' => $activityId, 'contact_id' => $params['source_contact_id'], 'record_type_id' => $sourceID); self::deleteActivityContact($activityId, $sourceID); CRM_Activity_BAO_ActivityContact::create($acParams); } // check and attach and files as needed CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId); // attempt to save activity assignment $resultAssignment = NULL; if (!empty($params['assignee_contact_id'])) { $assignmentParams = array('activity_id' => $activityId); if (is_array($params['assignee_contact_id'])) { if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) { // first delete existing assignments if any self::deleteActivityContact($activityId, $assigneeID); } $values = array(); foreach ($params['assignee_contact_id'] as $acID) { if ($acID) { $values[] = "( {$activityId}, {$acID}, {$assigneeID} )"; } } while (!empty($values)) { $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT); $str = implode(',', $input); $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};"; CRM_Core_DAO::executeQuery($sql); } } else { $assignmentParams['contact_id'] = $params['assignee_contact_id']; $assignmentParams['record_type_id'] = $assigneeID; if (!empty($params['id'])) { $assignment = new CRM_Activity_BAO_ActivityContact(); $assignment->activity_id = $activityId; $assignment->record_type_id = $assigneeID; $assignment->find(TRUE); if ($assignment->contact_id != $params['assignee_contact_id']) { $assignmentParams['id'] = $assignment->id; $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams); } } else { $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams); } } } else { if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) { self::deleteActivityContact($activityId, $assigneeID); } } if (is_a($resultAssignment, 'CRM_Core_Error')) { $transaction->rollback(); return $resultAssignment; } // attempt to save activity targets $resultTarget = NULL; if (!empty($params['target_contact_id'])) { $targetParams = array('activity_id' => $activityId); $resultTarget = array(); if (is_array($params['target_contact_id'])) { if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) { // first delete existing targets if any self::deleteActivityContact($activityId, $targetID); } $values = array(); foreach ($params['target_contact_id'] as $tid) { if ($tid) { $values[] = "( {$activityId}, {$tid}, {$targetID} )"; } } while (!empty($values)) { $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT); $str = implode(',', $input); $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};"; CRM_Core_DAO::executeQuery($sql); } } else { $targetParams['contact_id'] = $params['target_contact_id']; $targetParams['record_type_id'] = $targetID; if (!empty($params['id'])) { $target = new CRM_Activity_BAO_ActivityContact(); $target->activity_id = $activityId; $target->record_type_id = $targetID; $target->find(TRUE); if ($target->contact_id != $params['target_contact_id']) { $targetParams['id'] = $target->id; $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams); } } else { $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams); } } } else { if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) { self::deleteActivityContact($activityId, $targetID); } } // write to changelog before transaction is committed/rolled // back (and prepare status to display) if (!empty($params['id'])) { $logMsg = "Activity (id: {$result->id} ) updated with "; } else { $logMsg = "Activity created for "; } $msgs = array(); if (isset($params['source_contact_id'])) { $msgs[] = "source={$params['source_contact_id']}"; } if (!empty($params['target_contact_id'])) { if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) { $msgs[] = "target=" . implode(',', $params['target_contact_id']); // take only first target // will be used for recently viewed display $t = array_slice($params['target_contact_id'], 0, 1); $recentContactId = $t[0]; } elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) { $msgs[] = "target={$params['target_contact_id']}"; // will be used for recently viewed display $recentContactId = $params['target_contact_id']; } } else { // at worst, take source for recently viewed display $recentContactId = CRM_Utils_Array::value('source_contact_id', $params); } if (isset($params['assignee_contact_id'])) { if (is_array($params['assignee_contact_id'])) { $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']); } else { $msgs[] = "assignee={$params['assignee_contact_id']}"; } } $logMsg .= implode(', ', $msgs); self::logActivityAction($result, $logMsg); if (!empty($params['custom']) && is_array($params['custom'])) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id); } $transaction->commit(); if (empty($params['skipRecentView'])) { $recentOther = array(); if (!empty($params['case_id'])) { $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id'); $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"); } else { $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"; if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) { $url = CRM_Utils_System::url('civicrm/activity', $q); if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"); } else { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"); } if (CRM_Core_Permission::check("delete activities")) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"); } } else { $url = CRM_Utils_System::url('civicrm/activity/view', $q); if (CRM_Core_Permission::check('delete activities')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home"); } } } if (!isset($activity->parent_id)) { $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId); // add the recently created Activity $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE); $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject'); $title = ""; if (isset($activitySubject)) { $title = $activitySubject . ' - '; } $title = $title . $recentContactDisplay; if (!empty($activityTypes[$activity->activity_type_id])) { $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')'; } CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther); } } // reset the group contact cache since smart groups might be affected due to this CRM_Contact_BAO_GroupContactCache::remove(); if (!empty($params['id'])) { CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity); } else { CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity); } // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916) $matches = array(); if (preg_match('/\\[case #([0-9a-h]{7})\\]/', CRM_Utils_Array::value('subject', $params), $matches)) { $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY); $hash = $matches[1]; $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'"; $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query)); if ($caseParams['case_id']) { CRM_Case_BAO_Case::processCaseActivity($caseParams); } else { self::logActivityAction($activity, "unknown case hash encountered: {$hash}"); } } return $result; }
/** * takes an associative array and creates a contribution object * * the function extract all the params it needs to initialize the create a * contribution object. the params array could contain additional unused name/value * pairs * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * * @return object CRM_Contribute_BAO_Contribution object * @access public * @static */ static function add(&$params, &$ids) { if (empty($params)) { return; } $duplicates = array(); if (self::checkDuplicate($params, $duplicates, CRM_Utils_Array::value('contribution', $ids))) { $error =& CRM_Core_Error::singleton(); $d = implode(', ', $duplicates); $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: {$d}"); return $error; } // first clean up all the money fields $moneyFields = array('total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'); //if priceset is used, no need to cleanup money if (CRM_UTils_Array::value('skipCleanMoney', $params)) { unset($moneyFields[0]); } foreach ($moneyFields as $field) { if (isset($params[$field])) { $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); } } if (CRM_Utils_Array::value('payment_instrument_id', $params)) { require_once 'CRM/Contribute/PseudoConstant.php'; $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { $params['check_number'] = 'null'; } } require_once 'CRM/Utils/Hook.php'; if (CRM_Utils_Array::value('contribution', $ids)) { CRM_Utils_Hook::pre('edit', 'Contribution', $ids['contribution'], $params); } else { CRM_Utils_Hook::pre('create', 'Contribution', null, $params); } $contribution = new CRM_Contribute_BAO_Contribution(); $contribution->copyValues($params); $contribution->id = CRM_Utils_Array::value('contribution', $ids); // also add financial_trxn details as part of fix for CRM-4724 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); require_once 'CRM/Utils/Rule.php'; if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { require_once 'CRM/Core/Config.php'; $config = CRM_Core_Config::singleton(); $contribution->currency = $config->defaultCurrency; } $result = $contribution->save(); // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); if (CRM_Utils_Array::value('contribution', $ids)) { CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); } else { CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); } return $result; }
/** * Clear the contact cache so things are kosher. We started off being super aggressive with clearing * caches, but are backing off from this with every release. Compromise between ease of coding versus * performance versus being accurate at that very instant * * @param $contactID * The contactID that was edited / deleted. */ public static function clearContactCaches($contactID = NULL) { // clear acl cache if any. CRM_ACL_BAO_Cache::resetCache(); if (empty($contactID)) { // also clear prev/next dedupe cache - if no contactID passed in CRM_Core_BAO_PrevNextCache::deleteItem(); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); }
/** * Takes an associative array and creates a participant object. * * the function extract all the params it needs to initialize the create a * participant object. the params array could contain additional unused name/value * pairs * * @param array $params * (reference ) an assoc array of name/value pairs. * * @return CRM_Event_BAO_Participant */ public static function &add(&$params) { if (!empty($params['id'])) { CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params); } else { CRM_Utils_Hook::pre('create', 'Participant', NULL, $params); } // converting dates to mysql format if (!empty($params['register_date'])) { $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']); } if (!empty($params['participant_fee_amount'])) { $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']); } if (!empty($params['fee_amount'])) { $params['fee_amount'] = CRM_Utils_Rule::cleanMoney($params['fee_amount']); } // ensure that role ids are encoded as a string if (isset($params['role_id']) && is_array($params['role_id'])) { if (in_array(key($params['role_id']), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { $op = key($params['role_id']); $params['role_id'] = $params['role_id'][$op]; } else { $params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']); } } $participantBAO = new CRM_Event_BAO_Participant(); if (!empty($params['id'])) { $participantBAO->id = CRM_Utils_Array::value('id', $params); $participantBAO->find(TRUE); $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date); } $participantBAO->copyValues($params); //CRM-6910 //1. If currency present, it should be valid one. //2. We should have currency when amount is not null. $currency = $participantBAO->fee_currency; if ($currency || !CRM_Utils_System::isNull($participantBAO->fee_amount)) { if (!CRM_Utils_Rule::currencyCode($currency)) { $config = CRM_Core_Config::singleton(); $currency = $config->defaultCurrency; } } $participantBAO->fee_currency = $currency; $participantBAO->save(); $session = CRM_Core_Session::singleton(); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if (!empty($params['id'])) { CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO); } else { CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO); } return $participantBAO; }
/** * takes an associative array and creates a membership object * * the function extract all the params it needs to initialize the create a * membership object. the params array could contain additional unused name/value * pairs * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * * @return object CRM_Member_BAO_Membership object * @access public * @static */ static function &add(&$params, &$ids) { require_once 'CRM/Utils/Hook.php'; if (CRM_Utils_Array::value('membership', $ids)) { CRM_Utils_Hook::pre('edit', 'Membership', $ids['membership'], $params); } else { CRM_Utils_Hook::pre('create', 'Membership', null, $params); } // converting dates to mysql format if (isset($params['join_date'])) { $params['join_date'] = CRM_Utils_Date::isoToMysql($params['join_date']); } if (isset($params['start_date'])) { $params['start_date'] = CRM_Utils_Date::isoToMysql($params['start_date']); } if (CRM_Utils_Array::value('end_date', $params)) { $params['end_date'] = CRM_Utils_Date::isoToMysql($params['end_date']); } else { $params['end_date'] = 'null'; } if (CRM_Utils_Array::value('reminder_date', $params)) { $params['reminder_date'] = CRM_Utils_Date::isoToMysql($params['reminder_date']); } else { $params['reminder_date'] = 'null'; } if (!CRM_Utils_Array::value('is_override', $params)) { $params['is_override'] = 'null'; } $membership = new CRM_Member_BAO_Membership(); $membership->copyValues($params); $membership->id = CRM_Utils_Array::value('membership', $ids); $membership->save(); $membership->free(); $session =& CRM_Core_Session::singleton(); //get the log start date. //it is set during renewal of membership. $logStartDate = CRM_Utils_array::value('log_start_date', $params); $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $membership->start_date; $membershipLog = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => $logStartDate, 'end_date' => $membership->end_date, 'renewal_reminder_date' => $membership->reminder_date, 'modified_id' => CRM_Utils_Array::value('userId', $ids), 'modified_date' => date('Ymd')); require_once 'CRM/Member/BAO/MembershipLog.php'; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); // reset the group contact cache since smart groups might be affected due to this require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); if (CRM_Utils_Array::value('membership', $ids)) { CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); } else { CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership); } return $membership; }
/** * Function to delete custom value * */ function deleteCustomValue(&$config) { $customValueID = CRM_Utils_Type::escape($_POST['valueID'], 'Positive'); $customGroupID = CRM_Utils_Type::escape($_POST['groupID'], 'Positive'); require_once "CRM/Core/BAO/CustomValue.php"; CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID); if ($contactId = CRM_Utils_Array::value('contactId', $_POST)) { require_once 'CRM/Contact/BAO/Contact.php'; echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_POST['groupID'], $contactId); } // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); }
/** * function to add/edit/register contacts through profile. * * @params array $params Array of profile fields to be edited/added. * @params int $contactID contact_id of the contact to be edited/added. * @params array $fields array of fields from UFGroup * @params int $addToGroupID specifies the default group to which contact is added. * @params int $ufGroupId uf group id (profile id) * @param string $ctype contact type * * @return int contact id created/edited * @static * @access public */ static function createProfileContact(&$params, &$fields, $contactID = null, $addToGroupID = null, $ufGroupId = null, $ctype = null, $visibility = false) { // add ufGroupID to params array ( CRM-2012 ) if ($ufGroupId) { $params['uf_group_id'] = $ufGroupId; } require_once 'CRM/Utils/Hook.php'; if ($contactID) { $editHook = true; CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params); } else { $editHook = false; CRM_Utils_Hook::pre('create', 'Profile', null, $params); } $data = $contactDetails = array(); // get the contact details (hier) if ($contactID) { list($details, $options) = self::getHierContactDetails($contactID, $fields); $contactDetails = $details[$contactID]; $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails); } else { //we should get contact type only if contact if ($ufGroupId) { require_once "CRM/Core/BAO/UFField.php"; $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId); //special case to handle profile with only contact fields if ($data['contact_type'] == 'Contact') { $data['contact_type'] = 'Individual'; } else { if (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) { $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']); } } } else { if ($ctype) { $data['contact_type'] = $ctype; } else { $data['contact_type'] = 'Individual'; } } } //fix contact sub type CRM-5125 if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) { $data['contact_sub_type'] = $subType; } else { if ($ufGroupId) { $data['contact_sub_type'] = CRM_Core_BAO_UFField::getProfileSubType($ufGroupId, $data['contact_type']); } } if ($ctype == "Organization") { $data["organization_name"] = $contactDetails["organization_name"]; } else { if ($ctype == "Household") { $data["household_name"] = $contactDetails["household_name"]; } } $locationType = array(); $count = 1; if ($contactID) { //add contact id $data['contact_id'] = $contactID; $primaryLocationType = self::getPrimaryLocationType($contactID); } else { require_once "CRM/Core/BAO/LocationType.php"; $defaultLocation =& CRM_Core_BAO_LocationType::getDefault(); $defaultLocationId = $defaultLocation->id; } // get the billing location type $locationTypes =& CRM_Core_PseudoConstant::locationType(); $billingLocationTypeId = array_search('Billing', $locationTypes); $blocks = array('email', 'phone', 'im', 'openid'); // prevent overwritten of formatted array, reset all block from // params if it is not in valid format (since import pass valid format) foreach ($blocks as $blk) { if (array_key_exists($blk, $params) && !is_array($params[$blk])) { unset($params[$blk]); } } $primaryPhoneLoc = null; foreach ($params as $key => $value) { $fieldName = $locTypeId = $typeId = null; list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3); //store original location type id $actualLocTypeId = $locTypeId; if ($locTypeId == 'Primary') { if ($contactID) { $locTypeId = $primaryLocationType; } else { $locTypeId = $defaultLocationId; } } if (is_numeric($locTypeId)) { $index = $locTypeId; if (is_numeric($typeId)) { $index .= '-' . $typeId; } if (!in_array($index, $locationType)) { $locationType[$count] = $index; $count++; } require_once 'CRM/Utils/Array.php'; $loc = CRM_Utils_Array::key($index, $locationType); $blockName = 'address'; if (in_array($fieldName, $blocks)) { $blockName = $fieldName; } $data[$blockName][$loc]['location_type_id'] = $locTypeId; //set is_billing true, for location type "Billing" if ($locTypeId == $billingLocationTypeId) { $data[$blockName][$loc]['is_billing'] = 1; } if ($contactID) { //get the primary location type if ($locTypeId == $primaryLocationType) { $data[$blockName][$loc]['is_primary'] = 1; } } else { if (($locTypeId == $defaultLocationId || $locTypeId == $billingLocationTypeId) && ($loc == 1 || !CRM_Utils_Array::retrieveValueRecursive($data['location'][$loc - 1], 'is_primary'))) { $data[$blockName][$loc]['is_primary'] = 1; } } if ($fieldName == 'phone') { if ($typeId) { $data['phone'][$loc]['phone_type_id'] = $typeId; } else { $data['phone'][$loc]['phone_type_id'] = ''; } $data['phone'][$loc]['phone'] = $value; //special case to handle primary phone with different phone types // in this case we make first phone type as primary if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) { $primaryPhoneLoc = $loc; } if ($loc != $primaryPhoneLoc) { unset($data['phone'][$loc]['is_primary']); } } else { if ($fieldName == 'email') { $data['email'][$loc]['email'] = $value; } else { if ($fieldName == 'im') { if (isset($params[$key . '-provider_id'])) { $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id']; } $data['im'][$loc]['name'] = $value; } else { if ($fieldName == 'openid') { # $value should be a hash of the OpenID fields foreach ($value as $key => $val) { $data['openid'][$loc][$key] = $val; } } else { if ($fieldName === 'state_province') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['state_province_id'] = $value; } else { $data['address'][$loc]['state_province'] = $value; } } else { if ($fieldName === 'country') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['country_id'] = $value; } else { $data['address'][$loc]['country'] = $value; } } else { if ($fieldName === 'county') { $data['address'][$loc]['address']['county_id'] = $value; } else { if ($fieldName == 'address_name') { $data['address'][$loc]['name'] = $value; } else { $data['address'][$loc][$fieldName] = $value; } } } } } } } } } else { if ($key === 'individual_suffix') { $data['suffix_id'] = $value; } else { if ($key === 'individual_prefix') { $data['prefix_id'] = $value; } else { if ($key === 'gender') { $data['gender_id'] = $value; } else { if ($key === 'email_greeting') { //save email/postal greeting and addressee values if any, CRM-4575 $data['email_greeting_id'] = $value; } else { if ($key === 'postal_greeting') { $data['postal_greeting_id'] = $value; } else { if ($key === 'addressee') { $data['addressee_id'] = $value; } else { if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) { // for autocomplete transfer hidden value instead of label if (isset($params[$key . '_id'])) { $value = $params[$key . '_id']; } $type = CRM_Utils_Array::value('contact_sub_type', $data) ? $data['contact_sub_type'] : $data['contact_type']; CRM_Core_BAO_CustomField::formatCustomField($customFieldId, $data['custom'], $value, $type, null, $contactID); } else { if ($key == 'edit') { continue; } else { if ($key == 'location') { foreach ($value as $locationTypeId => $field) { foreach ($field as $block => $val) { if ($block == 'address' && array_key_exists('address_name', $val)) { $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name']; } } } } $data[$key] = $value; } } } } } } } } } } // FIX ME: need to check if we need this code // //make sure primary location is at first position in location array // if ( isset( $data['location'] ) && count( $data['location'] ) > 1 ) { // // if first location is primary skip manipulation // if ( !isset($data['location'][1]['is_primary']) ) { // //find the key for primary location // foreach ( $data['location'] as $primaryLocationKey => $value ) { // if ( isset( $value['is_primary'] ) ) { // break; // } // } // // // swap first location with primary location // $tempLocation = $data['location'][1]; // $data['location'][1] = $data['location'][$primaryLocationKey]; // $data['location'][$primaryLocationKey] = $tempLocation; // } // } if (!isset($data['contact_type'])) { $data['contact_type'] = 'Individual'; } if (CRM_Core_Permission::access('Quest')) { $studentFieldPresent = 0; foreach ($fields as $name => $field) { // check if student fields present require_once 'CRM/Quest/BAO/Student.php'; if (!$studentFieldPresent && array_key_exists($name, CRM_Quest_BAO_Student::exportableFields())) { $studentFieldPresent = 1; } } } //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone) $privacy = CRM_Core_SelectValues::privacy(); foreach ($privacy as $key => $value) { if (array_key_exists($key, $fields)) { if ($params[$key]) { $data[$key] = $params[$key]; } else { $data[$key] = 0; } } } // manage is_opt_out if (array_key_exists('is_opt_out', $fields)) { $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, false); $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, false); $data['is_opt_out'] = $isOptOut; // on change, create new civicrm_subscription_history entry if ($wasOptOut != $isOptOut && CRM_Utils_Array::value('contact_id', $contactDetails)) { $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web'); CRM_Contact_BAO_SubscriptionHistory::create($shParams); } } require_once 'CRM/Contact/BAO/Contact.php'; if ($data['contact_type'] != 'Student') { $contact =& self::create($data); } // contact is null if the profile does not have any contact fields if ($contact) { $contactID = $contact->id; } if (!$contactID) { CRM_Core_Error::fatal('Cannot proceed without a valid contact id'); } // Process group and tag if (CRM_Utils_Array::value('group', $fields)) { $method = 'Admin'; // this for sure means we are coming in via profile since i added it to fix // removing contacts from user groups -- lobo if ($visibility) { $method = 'Web'; } CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method); } if (CRM_Utils_Array::value('tag', $fields)) { require_once 'CRM/Core/BAO/EntityTag.php'; CRM_Core_BAO_EntityTag::create($params['tag'], $contactID); } //to add profile in default group if (is_array($addToGroupID)) { $contactIds = array($contactID); foreach ($addToGroupID as $groupId) { CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); } } else { if ($addToGroupID) { $contactIds = array($contactID); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID); } } //to update student record if (CRM_Core_Permission::access('Quest') && $studentFieldPresent) { $ids = array(); $dao =& new CRM_Quest_DAO_Student(); $dao->contact_id = $contactID; if ($dao->find(true)) { $ids['id'] = $dao->id; } $ssids = array(); $studentSummary =& new CRM_Quest_DAO_StudentSummary(); $studentSummary->contact_id = $contactID; if ($studentSummary->find(true)) { $ssids['id'] = $studentSummary->id; } $params['contact_id'] = $contactID; //fixed for check boxes $specialFields = array('educational_interest', 'college_type', 'college_interest', 'test_tutoring'); foreach ($specialFields as $field) { if ($params[$field]) { $params[$field] = implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_keys($params[$field])); } } CRM_Quest_BAO_Student::create($params, $ids); CRM_Quest_BAO_Student::createStudentSummary($params, $ssids); } // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); if ($editHook) { CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params); } else { CRM_Utils_Hook::post('create', 'Profile', $contactID, $params); } return $contactID; }
/** * Given an array of contact ids, remove all the contacts from the group * * @param array $contactIds * (reference ) the array of contact ids to be removed. * @param int $groupId * The id of the group. * * @param string $method * @param string $status * @param NULL $tracking * * @return array * (total, removed, notRemoved) count of contacts removed to group */ public static function removeContactsFromGroup(&$contactIds, $groupId, $method = 'Admin', $status = 'Removed', $tracking = NULL) { if (!is_array($contactIds)) { return array(0, 0, 0); } if ($status == 'Removed' || $status == 'Deleted') { $op = 'delete'; } else { $op = 'edit'; } CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds); $date = date('YmdHis'); $numContactsRemoved = 0; $numContactsNotRemoved = 0; $group = new CRM_Contact_DAO_Group(); $group->id = $groupId; $group->find(TRUE); foreach ($contactIds as $contactId) { if ($status == 'Deleted') { $query = "DELETE FROM civicrm_group_contact WHERE contact_id={$contactId} AND group_id={$groupId}"; $dao = CRM_Core_DAO::executeQuery($query); $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); } else { $groupContact = new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $groupId; $groupContact->contact_id = $contactId; // check if the selected contact id already a member, or if this is // an opt-out of a smart group. // if not a member remove to groupContact else keep the count of contacts that are not removed if ($groupContact->find(TRUE) || $group->saved_search_id) { // remove the contact from the group $numContactsRemoved++; } else { $numContactsNotRemoved++; } //now we grant the negative membership to contact if not member. CRM-3711 $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); $groupContact->status = $status; $groupContact->save(); } } // also reset the acl cache $config = CRM_Core_Config::singleton(); if (!$config->doNotResetCache) { CRM_ACL_BAO_Cache::resetCache(); } // reset the group contact cache for all group(s) // if this group is being used as a smart group // @todo consider what to do here - it feels like we should either // 1) just invalidate the specific group's cache(& perhaps any parents) & let cron do it's thing or // possibly clear this specific groups cache, or just call opportunisticCacheFlush() - which would have the // same effect as the remove call. The reservation about that is that it is no more aggressive for the group that // we know is altered than for all the others, or perhaps, more the point with it's parents & groups that use it in // their criteria. CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * Test the group contact clause does not contain an OR. * * The search should return 3 contacts - 2 households in the smart group of * Contact Type = Household and one Individual hard-added to it. The * Household that meets both criteria should be returned once. */ public function testGroupClause() { $this->householdCreate(); $householdID = $this->householdCreate(); $individualID = $this->individualCreate(); $groupID = $this->smartGroupCreate(); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $individualID, 'status' => 'Added')); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $householdID, 'status' => 'Added')); // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache. CRM_Contact_BAO_GroupContactCache::remove($groupID, FALSE); $sql = CRM_Contact_BAO_Query::getQuery(array(array('group', 'IN', array($groupID), 0, 0)), array('contact_id')); $dao = CRM_Core_DAO::executeQuery($sql); $this->assertEquals(3, $dao->N); $this->assertFalse(strstr($sql, ' OR ')); $sql = CRM_Contact_BAO_Query::getQuery(array(array('group', 'IN', array($groupID), 0, 0)), array('contact_id' => 1, 'group' => 1)); $dao = CRM_Core_DAO::executeQuery($sql); $this->assertEquals(3, $dao->N); $this->assertFalse(strstr($sql, ' OR '), 'Query does not include or'); while ($dao->fetch()) { $this->assertTrue($dao->groups == $groupID || $dao->groups == ',' . $groupID, $dao->groups . ' includes ' . $groupID); } }
/** * Given an array of contact ids, remove contact(s) tags * * @param array $contactIds (reference ) the array of contact ids to be added * @param int $tagId the id of the tag * * @return array (total, removed, notRemoved) count of contacts removed from tags * @access public * @static */ static function removeContactsFromTag(&$contactIds, $tagId) { $numContactsRemoved = 0; $numContactsNotRemoved = 0; foreach ($contactIds as $contactId) { $tag =& new CRM_Core_DAO_EntityTag(); $tag->contact_id = $contactId; $tag->tag_id = $tagId; if ($tag->find()) { $tag->delete(); $numContactsRemoved++; } else { $numContactsNotRemoved++; } } // reset the group contact cache for all groups // if tags are being used in a smart group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * process the form * * @return void * @access public */ public function postProcess() { // need to process / save custom data // Get the form values and groupTree $params = $this->controller->exportValues($this->_name); CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_contactId, $this->_entityType); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); $response = array('status' => 'save'); $this->postProcessHook(); echo json_encode($response); CRM_Utils_System::civiExit(); }
/** * Set up a smart group for testing. * * The smart group includes all Households by filter. In addition an individual * is created and hard-added and an individual is created that is not added. * * One household is hard-added as well as being in the filter. * * This gives us a range of scenarios for testing contacts are included only once * whenever they are hard-added or in the criteria. * * @return int */ public function setUpPopulatedGroup() { $individual1ID = $this->individualCreate(); $individualID = $this->individualCreate(); $individualIDRemoved = $this->individualCreate(); $groupID = $this->groupCreate(array('name' => uniqid(), 'title' => uniqid())); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $individualIDRemoved, 'status' => 'Removed')); $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupID, 'contact_id' => $individualID, 'status' => 'Added')); foreach (array($individual1ID, $individualID, $individualIDRemoved) as $contactID) { $this->contributionCreate(array('contact_id' => $contactID, 'invoice_id' => '', 'trxn_id' => '')); } // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache. CRM_Contact_BAO_GroupContactCache::remove($groupID, FALSE); return $groupID; }
static function clearContactCaches() { // clear acl cache if any. CRM_ACL_BAO_Cache::resetCache(); // also clear prev/next dedupe cache CRM_Core_BAO_PrevNextCache::deleteItem(); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); }
/** * takes an associative array and creates a participant object * * the function extract all the params it needs to initialize the create a * participant object. the params array could contain additional unused name/value * pairs * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * * @return object CRM_Event_BAO_Participant object * @access public * @static */ static function &add(&$params) { require_once 'CRM/Utils/Hook.php'; if (CRM_Utils_Array::value('id', $params)) { CRM_Utils_Hook::pre('edit', 'Participant', $params['id'], $params); } else { CRM_Utils_Hook::pre('create', 'Participant', null, $params); } // converting dates to mysql format if (CRM_Utils_Array::value('register_date', $params)) { $params['register_date'] = CRM_Utils_Date::isoToMysql($params['register_date']); } if (CRM_Utils_Array::value('participant_fee_amount', $params)) { $params['participant_fee_amount'] = CRM_Utils_Rule::cleanMoney($params['participant_fee_amount']); } if (CRM_Utils_Array::value('participant_fee_amount', $params)) { $params['fee_amount'] = CRM_Utils_Rule::cleanMoney($params['fee_amount']); } $participantBAO = new CRM_Event_BAO_Participant(); if (CRM_Utils_Array::value('id', $params)) { $participantBAO->id = CRM_Utils_Array::value('id', $params); $participantBAO->find(true); $participantBAO->register_date = CRM_Utils_Date::isoToMysql($participantBAO->register_date); } $participantBAO->copyValues($params); //CRM-6910 //1. If currency present, it should be valid one. //2. We should have currency when amount is not null. require_once 'CRM/Utils/Rule.php'; $currency = $participantBAO->fee_currency; if ($currency || !CRM_Utils_System::isNull($participantBAO->fee_amount)) { if (!CRM_Utils_Rule::currencyCode($currency)) { $config = CRM_Core_Config::singleton(); $currency = $config->defaultCurrency; } } $participantBAO->fee_currency = $currency; $participantBAO->save(); $session =& CRM_Core_Session::singleton(); // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); if (CRM_Utils_Array::value('id', $params)) { CRM_Utils_Hook::post('edit', 'Participant', $participantBAO->id, $participantBAO); } else { CRM_Utils_Hook::post('create', 'Participant', $participantBAO->id, $participantBAO); } return $participantBAO; }
/** * Given an array of entity ids and entity table, remove entity(s)tags. * * @param array $entityIds * (reference ) the array of entity ids to be removed. * @param int $tagId * The id of the tag. * @param string $entityTable * Name of entity table default:civicrm_contact. * @param bool $applyPermissions * Should permissions be applied in this function. * * @return array * (total, removed, notRemoved) count of entities removed from tags */ public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable, $applyPermissions) { $numEntitiesRemoved = 0; $numEntitiesNotRemoved = 0; $entityIdsRemoved = array(); foreach ($entityIds as $entityId) { // CRM-17350 - check if we have permission to edit the contact // that this tag belongs to. if ($applyPermissions && !self::checkPermissionOnEntityTag($entityId, $entityTable)) { $numEntitiesNotRemoved++; continue; } $tag = new CRM_Core_DAO_EntityTag(); $tag->entity_id = $entityId; $tag->tag_id = $tagId; $tag->entity_table = $entityTable; if ($tag->find()) { $tag->delete(); $entityIdsRemoved[] = $entityId; $numEntitiesRemoved++; } else { $numEntitiesNotRemoved++; } } //invoke post hook on entityTag $object = array($entityIdsRemoved, $entityTable); CRM_Utils_Hook::post('delete', 'EntityTag', $tagId, $object); // reset the group contact cache for all groups // if tags are being used in a smart group CRM_Contact_BAO_GroupContactCache::remove(); return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved); }
/** * Process the user submitted custom data values. */ public function postProcess() { // Get the form values and groupTree //CRM-18183 $params = $this->controller->exportValues($this->_name); CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contact', $this->_tableID, $this->_entityType); $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_groupID, 'table_name'); $cgcount = CRM_Core_BAO_CustomGroup::customGroupDataExistsForEntity($this->_tableID, $table, TRUE); $cgcount += 1; $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->getButtonName('upload', 'new')) { CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/contact/view/cd/edit', "reset=1&type={$this->_contactType}&groupID={$this->_groupID}&entityID={$this->_tableID}&cgcount={$cgcount}&multiRecordDisplay=single&mode=add")); } // Add entry in the log table CRM_Core_BAO_Log::register($this->_tableID, 'civicrm_contact', $this->_tableID); if (CRM_Core_Resources::isAjaxMode()) { $this->ajaxResponse += CRM_Contact_Form_Inline::renderFooter($this->_tableID); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); }
/** * takes an associative array and creates a contribution object * * the function extract all the params it needs to initialize the create a * contribution object. the params array could contain additional unused name/value * pairs * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * * @return object CRM_Contribute_BAO_Contribution object * @access public * @static */ static function add(&$params, $ids = array()) { if (empty($params)) { return; } //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params)); $duplicates = array(); if (self::checkDuplicate($params, $duplicates, $contributionID)) { $error = CRM_Core_Error::singleton(); $d = implode(', ', $duplicates); $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: {$d}"); return $error; } // first clean up all the money fields $moneyFields = array('total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'); //if priceset is used, no need to cleanup money if (CRM_Utils_Array::value('skipCleanMoney', $params)) { unset($moneyFields[0]); } foreach ($moneyFields as $field) { if (isset($params[$field])) { $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); } } // CRM-13420, set payment instrument to default if payment_instrument_id is empty if (!$contributionID && !CRM_Utils_Array::value('payment_instrument_id', $params)) { $params['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')); } if (CRM_Utils_Array::value('payment_instrument_id', $params)) { $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { $params['check_number'] = 'null'; } } // contribution status is missing, choose Completed as default status // do this for create mode only if (!$contributionID && !CRM_Utils_Array::value('contribution_status_id', $params)) { $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); } if ($contributionID) { CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params); } else { CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params); } $contribution = new CRM_Contribute_BAO_Contribution(); $contribution->copyValues($params); $contribution->id = $contributionID; if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { $config = CRM_Core_Config::singleton(); $contribution->currency = $config->defaultCurrency; } if ($contributionID) { $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); } $result = $contribution->save(); // Add financial_trxn details as part of fix for CRM-4724 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); //add Account details $params['contribution'] = $contribution; self::recordFinancialAccounts($params); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if ($contributionID) { CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); } else { CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); } return $result; }
/** * Add/edit/register contacts through profile. * * @param array $params * Array of profile fields to be edited/added. * @param array $fields * Array of fields from UFGroup. * @param int $contactID * Id of the contact to be edited/added. * @param int $addToGroupID * Specifies the default group to which contact is added. * @param int $ufGroupId * Uf group id (profile id). * @param string $ctype * @param bool $visibility * Basically lets us know where this request is coming from. * if via a profile from web, we restrict what groups are changed * * @return int * contact id created/edited */ public static function createProfileContact(&$params, &$fields, $contactID = NULL, $addToGroupID = NULL, $ufGroupId = NULL, $ctype = NULL, $visibility = FALSE) { // add ufGroupID to params array ( CRM-2012 ) if ($ufGroupId) { $params['uf_group_id'] = $ufGroupId; } if ($contactID) { $editHook = TRUE; CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params); } else { $editHook = FALSE; CRM_Utils_Hook::pre('create', 'Profile', NULL, $params); } list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype); // manage is_opt_out if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) { $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE); $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE); $data['is_opt_out'] = $isOptOut; // on change, create new civicrm_subscription_history entry if ($wasOptOut != $isOptOut && !empty($contactDetails['contact_id'])) { $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web'); CRM_Contact_BAO_SubscriptionHistory::create($shParams); } } $contact = self::create($data); // contact is null if the profile does not have any contact fields if ($contact) { $contactID = $contact->id; } if (empty($contactID)) { CRM_Core_Error::fatal('Cannot proceed without a valid contact id'); } // Process group and tag if (!empty($fields['group'])) { $method = 'Admin'; // this for sure means we are coming in via profile since i added it to fix // removing contacts from user groups -- lobo if ($visibility) { $method = 'Web'; } CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method); } if (!empty($fields['tag'])) { CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID); } //to add profile in default group if (is_array($addToGroupID)) { $contactIds = array($contactID); foreach ($addToGroupID as $groupId) { CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); } } elseif ($addToGroupID) { $contactIds = array($contactID); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if ($editHook) { CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params); } else { CRM_Utils_Hook::post('create', 'Profile', $contactID, $params); } return $contactID; }
/** * Add/edit/register contacts through profile. * * @param array $params * Array of profile fields to be edited/added. * @param array $fields * Array of fields from UFGroup. * @param int $contactID * Id of the contact to be edited/added. * @param int $addToGroupID * Specifies the default group to which contact is added. * @param int $ufGroupId * Uf group id (profile id). * @param string $ctype * @param bool $visibility * Basically lets us know where this request is coming from. * if via a profile from web, we restrict what groups are changed * * @return int * contact id created/edited */ public static function createProfileContact(&$params, &$fields, $contactID = NULL, $addToGroupID = NULL, $ufGroupId = NULL, $ctype = NULL, $visibility = FALSE) { // add ufGroupID to params array ( CRM-2012 ) if ($ufGroupId) { $params['uf_group_id'] = $ufGroupId; } self::addBillingNameFieldsIfOtherwiseNotSet($params); // If a user has logged in, or accessed via a checksum // Then deliberately 'blanking' a value in the profile should remove it from their record $session = CRM_Core_Session::singleton(); $params['updateBlankLocInfo'] = TRUE; if (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0) { $params['updateBlankLocInfo'] = FALSE; } if ($contactID) { $editHook = TRUE; CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params); } else { $editHook = FALSE; CRM_Utils_Hook::pre('create', 'Profile', NULL, $params); } list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype); // manage is_opt_out if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) { $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE); $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE); $data['is_opt_out'] = $isOptOut; // on change, create new civicrm_subscription_history entry if ($wasOptOut != $isOptOut && !empty($contactDetails['contact_id'])) { $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web'); CRM_Contact_BAO_SubscriptionHistory::create($shParams); } } $contact = self::create($data); // contact is null if the profile does not have any contact fields if ($contact) { $contactID = $contact->id; } if (empty($contactID)) { CRM_Core_Error::fatal('Cannot proceed without a valid contact id'); } // Process group and tag if (!empty($fields['group'])) { $method = 'Admin'; // this for sure means we are coming in via profile since i added it to fix // removing contacts from user groups -- lobo if ($visibility) { $method = 'Web'; } CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method); } if (!empty($fields['tag'])) { CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID); } //to add profile in default group if (is_array($addToGroupID)) { $contactIds = array($contactID); foreach ($addToGroupID as $groupId) { CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); } } elseif ($addToGroupID) { $contactIds = array($contactID); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if ($editHook) { CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params); } else { CRM_Utils_Hook::post('create', 'Profile', $contactID, $params); } return $contactID; }
/** * Given an array of contact ids, remove all the contacts from the group * * @param array $contactIds (reference ) the array of contact ids to be removed * @param int $groupId the id of the group * * @return array (total, removed, notRemoved) count of contacts removed to group * @access public * @static */ static function removeContactsFromGroup(&$contactIds, $groupId, $method = 'Admin', $status = 'Removed', $tracking = null) { if (!is_array($contactIds)) { return array(0, 0, 0); } require_once 'CRM/Utils/Hook.php'; if ($status == 'Removed') { $op = 'delete'; } else { $op = 'edit'; } CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds); $date = date('YmdHis'); $numContactsRemoved = 0; $numContactsNotRemoved = 0; require_once "CRM/Contact/DAO/Group.php"; $group =& new CRM_Contact_DAO_Group(); $group->id = $groupId; $group->find(true); foreach ($contactIds as $contactId) { $groupContact =& new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $groupId; $groupContact->contact_id = $contactId; // check if the selected contact id already a member, or if this is // an opt-out of a smart group. // if not a member remove to groupContact else keep the count of contacts that are not removed if ($groupContact->find(true) || $group->saved_search_id) { // remove the contact from the group $numContactsRemoved++; } else { $numContactsNotRemoved++; } //now we grant the negative membership to contact if not member. CRM-3711 $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); $groupContact->status = $status; $groupContact->save(); } // also reset the acl cache require_once 'CRM/ACL/BAO/Cache.php'; CRM_ACL_BAO_Cache::resetCache(); // reset the group contact cache for all group(s) // if this group is being used as a smart group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * Process the user submitted custom data values. * * @access public * @return void */ public function postProcess() { // Get the form values and groupTree $params = $this->controller->exportValues($this->_name); require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::postProcess($params, $this->_groupTree[$this->_groupID]['fields'], 'civicrm_contact', $this->_tableID, $this->_entityType); // reset the group contact cache for this group require_once 'CRM/Contact/BAO/GroupContactCache.php'; CRM_Contact_BAO_GroupContactCache::remove(); }
/** * Takes an associative array and creates a contribution object. * * the function extract all the params it needs to initialize the create a * contribution object. the params array could contain additional unused name/value * pairs * * @param array $params * (reference ) an assoc array of name/value pairs. * @param array $ids * The array that holds all the db ids. * * @return CRM_Contribute_BAO_Contribution|void */ public static function add(&$params, $ids = array()) { if (empty($params)) { return NULL; } //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params)); $duplicates = array(); if (self::checkDuplicate($params, $duplicates, $contributionID)) { $error = CRM_Core_Error::singleton(); $d = implode(', ', $duplicates); $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, 'Fatal', array($d), "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: {$d}"); return $error; } // first clean up all the money fields $moneyFields = array('total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'); //if priceset is used, no need to cleanup money if (!empty($params['skipCleanMoney'])) { unset($moneyFields[0]); } foreach ($moneyFields as $field) { if (isset($params[$field])) { $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); } } //set defaults in create mode if (!$contributionID) { CRM_Core_DAO::setCreateDefaults($params, self::getDefaults()); } self::calculateMissingAmountParams($params, $contributionID); if (!empty($params['payment_instrument_id'])) { $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { $params['check_number'] = 'null'; } } $setPrevContribution = TRUE; // CRM-13964 partial payment if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { $partialAmtTotal = $params['partial_payment_total']; $partialAmtPay = $params['partial_amount_pay']; $params['total_amount'] = $partialAmtTotal; if ($partialAmtPay < $partialAmtTotal) { $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name'); $params['is_pay_later'] = 0; $setPrevContribution = FALSE; } } if ($contributionID) { CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params); } else { CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params); } $contribution = new CRM_Contribute_BAO_Contribution(); $contribution->copyValues($params); $contribution->id = $contributionID; if (empty($contribution->id)) { // (only) on 'create', make sure that a valid currency is set (CRM-16845) if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { $config = CRM_Core_Config::singleton(); $contribution->currency = $config->defaultCurrency; } } if ($contributionID && $setPrevContribution) { $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); } $result = $contribution->save(); // Add financial_trxn details as part of fix for CRM-4724 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); //add Account details $params['contribution'] = $contribution; self::recordFinancialAccounts($params); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if ($contributionID) { CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); } else { CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); } return $result; }
/** * Given an array of entity ids and entity table, remove entity(s) tags * * @param array $entityIds * (reference ) the array of entity ids to be removed. * @param int $tagId * The id of the tag. * @param string $entityTable * Name of entity table default:civicrm_contact. * * @return array * (total, removed, notRemoved) count of entities removed from tags */ public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable = 'civicrm_contact') { $numEntitiesRemoved = 0; $numEntitiesNotRemoved = 0; $entityIdsRemoved = array(); foreach ($entityIds as $entityId) { $tag = new CRM_Core_DAO_EntityTag(); $tag->entity_id = $entityId; $tag->tag_id = $tagId; $tag->entity_table = $entityTable; if ($tag->find()) { $tag->delete(); $entityIdsRemoved[] = $entityId; $numEntitiesRemoved++; } else { $numEntitiesNotRemoved++; } } //invoke post hook on entityTag $object = array($entityIdsRemoved, $entityTable); CRM_Utils_Hook::post('delete', 'EntityTag', $tagId, $object); // reset the group contact cache for all groups // if tags are being used in a smart group CRM_Contact_BAO_GroupContactCache::remove(); return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved); }
/** * Given an array of contact ids, remove all the contacts from the group * * @param array $contactIds * (reference ) the array of contact ids to be removed. * @param int $groupId * The id of the group. * * @param string $method * @param string $status * @param NULL $tracking * * @return array * (total, removed, notRemoved) count of contacts removed to group */ public static function removeContactsFromGroup(&$contactIds, $groupId, $method = 'Admin', $status = 'Removed', $tracking = NULL) { if (!is_array($contactIds)) { return array(0, 0, 0); } if ($status == 'Removed' || $status == 'Deleted') { $op = 'delete'; } else { $op = 'edit'; } CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds); $date = date('YmdHis'); $numContactsRemoved = 0; $numContactsNotRemoved = 0; $group = new CRM_Contact_DAO_Group(); $group->id = $groupId; $group->find(TRUE); foreach ($contactIds as $contactId) { if ($status == 'Deleted') { $query = "DELETE FROM civicrm_group_contact WHERE contact_id={$contactId} AND group_id={$groupId}"; $dao = CRM_Core_DAO::executeQuery($query); $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); } else { $groupContact = new CRM_Contact_DAO_GroupContact(); $groupContact->group_id = $groupId; $groupContact->contact_id = $contactId; // check if the selected contact id already a member, or if this is // an opt-out of a smart group. // if not a member remove to groupContact else keep the count of contacts that are not removed if ($groupContact->find(TRUE) || $group->saved_search_id) { // remove the contact from the group $numContactsRemoved++; } else { $numContactsNotRemoved++; } //now we grant the negative membership to contact if not member. CRM-3711 $historyParams = array('group_id' => $groupId, 'contact_id' => $contactId, 'status' => $status, 'method' => $method, 'date' => $date, 'tracking' => $tracking); CRM_Contact_BAO_SubscriptionHistory::create($historyParams); $groupContact->status = $status; $groupContact->save(); } } // also reset the acl cache $config = CRM_Core_Config::singleton(); if (!$config->doNotResetCache) { CRM_ACL_BAO_Cache::resetCache(); } // reset the group contact cache for all group(s) // if this group is being used as a smart group CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds); return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved); }
/** * Process the form. * * @return void */ public function postProcess() { // Process / save custom data // Get the form values and groupTree $params = $this->controller->exportValues($this->_name); CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contact', $this->_contactId, $this->_entityType); $this->log(); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); $this->response(); }
/** * Delete custom value. */ public static function deleteCustomValue() { CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain'); $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive'); $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive'); $contactId = CRM_Utils_Request::retrieve('contactId', 'Positive', CRM_Core_DAO::$_nullObject); CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID); if ($contactId) { echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $customGroupID, $contactId); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_System::civiExit(); }
/** * Function to delete custom value * */ static function deleteCustomValue() { $customValueID = CRM_Utils_Type::escape($_POST['valueID'], 'Positive'); $customGroupID = CRM_Utils_Type::escape($_POST['groupID'], 'Positive'); CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID); if ($contactId = CRM_Utils_Array::value('contactId', $_POST)) { echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_POST['groupID'], $contactId); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); CRM_Utils_System::civiExit(); }
/** * Takes an associative array and creates a membership object. * * the function extracts all the params it needs to initialize the created * membership object. The params array could contain additional unused name/value * pairs * * @param array $params * (reference ) an assoc array of name/value pairs. * @param array $ids * The array that holds all the db ids. * * @return CRM_Member_BAO_Membership */ public static function add(&$params, $ids = array()) { $oldStatus = $oldType = NULL; $params['id'] = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('membership', $ids)); if ($params['id']) { CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params); } else { CRM_Utils_Hook::pre('create', 'Membership', NULL, $params); } $id = $params['id']; // we do this after the hooks are called in case it has been altered if ($id) { $membershipObj = new CRM_Member_DAO_Membership(); $membershipObj->id = $id; $membershipObj->find(); while ($membershipObj->fetch()) { $oldStatus = $membershipObj->status_id; $oldType = $membershipObj->membership_type_id; } } if (array_key_exists('is_override', $params) && !$params['is_override']) { $params['is_override'] = 'null'; } $membership = new CRM_Member_BAO_Membership(); $membership->copyValues($params); $membership->id = $id; $membership->save(); $membership->free(); if (empty($membership->contact_id) || empty($membership->status_id)) { // this means we are in renewal mode and are just updating the membership // record or this is an API update call and all fields are not present in the update record // however the hooks don't care and want all data CRM-7784 $tempMembership = new CRM_Member_DAO_Membership(); $tempMembership->id = $membership->id; $tempMembership->find(TRUE); $membership = $tempMembership; } //get the log start date. //it is set during renewal of membership. $logStartDate = CRM_Utils_Array::value('log_start_date', $params); $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date); $values = self::getStatusANDTypeValues($membership->id); $membershipLog = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => $logStartDate, 'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date), 'modified_date' => date('Ymd'), 'membership_type_id' => $values[$membership->id]['membership_type_id'], 'max_related' => $membership->max_related); $session = CRM_Core_Session::singleton(); // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id if ($session->get('userID')) { $membershipLog['modified_id'] = $session->get('userID'); } elseif (!empty($ids['userId'])) { $membershipLog['modified_id'] = $ids['userId']; } else { $membershipLog['modified_id'] = $membership->contact_id; } CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); // reset the group contact cache since smart groups might be affected due to this CRM_Contact_BAO_GroupContactCache::remove(); if ($id) { if ($membership->status_id != $oldStatus) { $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get'); $activityParam = array('subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}", 'source_contact_id' => $membershipLog['modified_id'], 'target_contact_id' => $membership->contact_id, 'source_record_id' => $membership->id, 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'), 'status_id' => 2, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s')); civicrm_api3('activity', 'create', $activityParam); } if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) { $membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get'); $activityParam = array('subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}", 'source_contact_id' => $membershipLog['modified_id'], 'target_contact_id' => $membership->contact_id, 'source_record_id' => $membership->id, 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'), 'status_id' => 2, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s')); civicrm_api3('activity', 'create', $activityParam); } CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); } else { CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership); } return $membership; }
/** * function to add/edit/register contacts through profile. * * @params array $params Array of profile fields to be edited/added. * @params int $contactID contact_id of the contact to be edited/added. * @params array $fields array of fields from UFGroup * @params int $addToGroupID specifies the default group to which contact is added. * @params int $ufGroupId uf group id (profile id) * @param string $ctype contact type * @param boolean $visibility basically lets us know where this request is coming from * if via a profile from web, we restrict what groups are changed * * @return int contact id created/edited * @static * @access public */ static function createProfileContact(&$params, &$fields, $contactID = NULL, $addToGroupID = NULL, $ufGroupId = NULL, $ctype = NULL, $visibility = FALSE) { // add ufGroupID to params array ( CRM-2012 ) if ($ufGroupId) { $params['uf_group_id'] = $ufGroupId; } if ($contactID) { $editHook = TRUE; CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params); } else { $editHook = FALSE; CRM_Utils_Hook::pre('create', 'Profile', NULL, $params); } list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype); // manage is_opt_out if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) { $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE); $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE); $data['is_opt_out'] = $isOptOut; // on change, create new civicrm_subscription_history entry if ($wasOptOut != $isOptOut && CRM_Utils_Array::value('contact_id', $contactDetails)) { $shParams = array('contact_id' => $contactDetails['contact_id'], 'status' => $isOptOut ? 'Removed' : 'Added', 'method' => 'Web'); CRM_Contact_BAO_SubscriptionHistory::create($shParams); } } if ($data['contact_type'] != 'Student') { $contact = self::create($data); } // contact is null if the profile does not have any contact fields if ($contact) { $contactID = $contact->id; } if (!$contactID) { CRM_Core_Error::fatal('Cannot proceed without a valid contact id'); } // Process group and tag if (CRM_Utils_Array::value('group', $fields)) { $method = 'Admin'; // this for sure means we are coming in via profile since i added it to fix // removing contacts from user groups -- lobo if ($visibility) { $method = 'Web'; } CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method); } if (CRM_Utils_Array::value('tag', $fields)) { CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $contactID); } //to add profile in default group if (is_array($addToGroupID)) { $contactIds = array($contactID); foreach ($addToGroupID as $groupId) { CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); } } elseif ($addToGroupID) { $contactIds = array($contactID); CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID); } //to update student record if (CRM_Core_Permission::access('Quest') && $studentFieldPresent) { $ids = array(); $dao = new CRM_Quest_DAO_Student(); $dao->contact_id = $contactID; if ($dao->find(TRUE)) { $ids['id'] = $dao->id; } $ssids = array(); $studentSummary = new CRM_Quest_DAO_StudentSummary(); $studentSummary->contact_id = $contactID; if ($studentSummary->find(TRUE)) { $ssids['id'] = $studentSummary->id; } $params['contact_id'] = $contactID; //fixed for check boxes $specialFields = array('educational_interest', 'college_type', 'college_interest', 'test_tutoring'); foreach ($specialFields as $field) { if ($params[$field]) { $params[$field] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params[$field])); } } CRM_Quest_BAO_Student::create($params, $ids); CRM_Quest_BAO_Student::createStudentSummary($params, $ssids); } // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); if ($editHook) { CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params); } else { CRM_Utils_Hook::post('create', 'Profile', $contactID, $params); } return $contactID; }