Пример #1
0
 /**
  * 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();
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     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;
 }
 /**
  * Test the opportunistic refresh cache function does refresh expired entries if mode is deterministic.
  */
 public function testOpportunisticRefreshNoChangeWithDeterministicSetting()
 {
     list($group, $living, $deceased) = $this->setupSmartGroup();
     $this->callAPISuccess('Setting', 'create', array('smart_group_cache_refresh_mode' => 'deterministic'));
     $this->callAPISuccess('Contact', 'create', array('id' => $deceased[0]->id, 'is_deceased' => 0));
     $this->makeCacheStale($group);
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     $this->assertCacheNotRefreshed($deceased, $group);
     $this->callAPISuccess('Setting', 'create', array('smart_group_cache_refresh_mode' => 'opportunistic'));
 }
Пример #3
0
 /**
  * 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);
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     CRM_Utils_System::civiExit();
 }
Пример #4
0
 /**
  * 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);
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     if ($editHook) {
         CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
     } else {
         CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
     }
     return $contactID;
 }
Пример #5
0
 /**
  * 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();
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
 }
Пример #6
0
 /**
  * Process the form.
  */
 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();
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     $this->response();
 }
Пример #7
0
 /**
  * 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);
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved);
 }
Пример #8
0
 /**
  * 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);
         }
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     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;
 }
Пример #9
0
 /**
  * Given an array of contact ids, add all the contacts to the group
  *
  * @param array $contactIds
  *   The array of contact ids to be added.
  * @param int $groupId
  *   The id of the group.
  * @param string $method
  * @param string $status
  * @param int $tracking
  *
  * @return array
  *   (total, added, notAdded) count of contacts added to group
  */
 public static function addContactsToGroup($contactIds, $groupId, $method = 'Admin', $status = 'Added', $tracking = NULL)
 {
     CRM_Utils_Hook::pre('create', 'GroupContact', $groupId, $contactIds);
     list($numContactsAdded, $numContactsNotAdded) = self::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
     // 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::opportunisticCacheFlush();
     CRM_Utils_Hook::post('create', 'GroupContact', $groupId, $contactIds);
     return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
 }
Пример #10
0
 /**
  * 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());
     }
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     //if contribution is created with cancelled or refunded status, add credit note id
     if (!empty($params['contribution_status_id'])) {
         // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
         if ($params['contribution_status_id'] == array_search('Refunded', $contributionStatus) || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus)) {
             if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
                 $params['creditnote_id'] = self::createCreditNoteId();
             }
         }
     } else {
         // Since the fee amount is expecting this (later on) ensure it is always set.
         // It would only not be set for an update where it is unchanged.
         $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
     }
     if (!$contributionID && CRM_Utils_Array::value('membership_id', $params) && self::checkContributeSettings('deferred_revenue_enabled')) {
         $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
         if ($memberStartDate) {
             $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
         }
     }
     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 && $setPrevContribution) {
         $params['prevContribution'] = self::getOriginalContribution($contributionID);
     }
     // CRM-16189
     CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($params, $contributionID);
     if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution']) && !($contributionStatus[$params['prevContribution']->contribution_status_id] == 'Pending') && !self::allowUpdateRevenueRecognitionDate($contributionID)) {
         unset($params['revenue_recognition_date']);
     }
     if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) || isset($params['financial_type_id']))) {
         $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
     }
     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)) {
             $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
         }
     }
     $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);
     if (self::isUpdateToRecurringContribution($params)) {
         CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id, $contributionStatus[$params['contribution_status_id']]);
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
     if ($contributionID) {
         CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
     } else {
         CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
     }
     return $result;
 }
Пример #11
0
 /**
  * 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);
     }
     CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
 }
Пример #12
0
 /**
  * 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::opportunisticCacheFlush();
     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;
 }