/** * Create relationship type. * * @param array $params * Array per getfields metadata. * * @return array */ function civicrm_api3_relationship_type_create($params) { if (!isset($params['label_a_b'])) { $params['label_a_b'] = $params['name_a_b']; } if (!isset($params['label_b_a'])) { $params['label_b_a'] = $params['name_b_a']; } $ids = array(); if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) { return civicrm_api3_create_error('Invalid value for relationship type ID'); } else { $ids['relationshipType'] = CRM_Utils_Array::value('id', $params); } $relationType = CRM_Contact_BAO_RelationshipType::add($params, $ids); $relType = array(); _civicrm_api3_object_to_array($relationType, $relType[$relationType->id]); return civicrm_api3_create_success($relType, $params, 'RelationshipType', 'create', $relationType); }
/** * Get contact membership record. * * This api is used for finding an existing membership record. * This api will also return the mebership records for the contacts * having mebership based on the relationship with the direct members. * * @param Array $params key/value pairs for contact_id and some * options affecting the desired results; has legacy support * for just passing the contact_id itself as the argument * * @return Array of all found membership property values. * @access public */ function civicrm_membership_contact_get(&$params) { _civicrm_initialize(); $activeOnly = false; if (is_array($params)) { $contactID = CRM_Utils_Array::value('contact_id', $params); $activeOnly = CRM_Utils_Array::value('active_only', $params, false); if ($activeOnly == 1) { $activeOnly = true; } else { $activeOnly = false; } } elseif (CRM_Utils_Rule::integer($params)) { $contactID = $params; } else { return civicrm_create_error('Paramers can be only of type array or integer'); } if (empty($contactID)) { return civicrm_create_error('Invalid value for ContactID.'); } // get the membership for the given contact ID require_once 'CRM/Member/BAO/Membership.php'; $membership = array('contact_id' => $contactID); $membershipValues = array(); CRM_Member_BAO_Membership::getValues($membership, $membershipValues, $activeOnly); $recordCount = 0; if (empty($membershipValues)) { # No results is NOT an error! # return civicrm_create_error('No memberships for this contact.'); $membershipValues['record_count'] = $recordCount; return $membershipValues; } $members[$contactID] = array(); $relationships = array(); foreach ($membershipValues as $membershipId => $values) { // populate the membership type name for the membership type id require_once 'CRM/Member/BAO/MembershipType.php'; $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); $membershipValues[$membershipId]['membership_name'] = $membershipType['name']; if (CRM_Utils_Array::value('relationship_type_id', $membershipType)) { $relationships[$membershipType['relationship_type_id']] = $membershipId; } // populating relationship type name. require_once 'CRM/Contact/BAO/RelationshipType.php'; $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = CRM_Utils_Array::value('relationship_type_id', $membershipType); if ($relationshipType->find(true)) { $membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b; } require_once 'CRM/Core/BAO/CustomGroup.php'; $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Membership', CRM_Core_DAO::$_nullObject, $membershipId, false, $values['membership_type_id']); $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, CRM_Core_DAO::$_nullObject); $defaults = array(); CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults); if (!empty($defaults)) { foreach ($defaults as $key => $val) { $membershipValues[$membershipId][$key] = $val; } } $recordCount++; } $members[$contactID] = $membershipValues; // populating contacts in members array based on their relationship with direct members. require_once 'CRM/Contact/BAO/Relationship.php'; if (!empty($relationships)) { foreach ($relationships as $relTypeId => $membershipId) { // As members are not direct members, there should not be // membership id in the result array. unset($membershipValues[$membershipId]['id']); $relationship = new CRM_Contact_BAO_Relationship(); $relationship->contact_id_b = $contactID; $relationship->relationship_type_id = $relTypeId; if ($relationship->find()) { while ($relationship->fetch()) { clone $relationship; $membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a; $members[$contactID][$relationship->contact_id_a] = $membershipValues[$membershipId]; } } $recordCount++; } } $members['record_count'] = $recordCount; return $members; }
public function testRelCreateWithinDiffTypeStudentSponsor() { //check for Student to Sponcer $relTypeParams = array('name_a_b' => 'StudentToSponsor', 'name_b_a' => 'SponsorToStudent', 'contact_type_a' => 'Individual', 'contact_sub_type_a' => $this->student, 'contact_type_b' => 'Organization', 'contact_sub_type_b' => $this->sponsor); $relTypeIds = array(); $relType = CRM_Contact_BAO_RelationshipType::add($relTypeParams, $relTypeIds); $params = array('relationship_type_id' => $relType->id . '_a_b', 'is_active' => 1, 'contact_check' => array($this->organization_sponsor => 1)); $ids = array('contact' => $this->indivi_student); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::legacyCreateMultiple($params, $ids); $this->assertEquals($valid, 1); $this->assertEquals(empty($relationshipIds), FALSE); $this->relationshipTypeDelete($relType->id); }
/** * Function to create / update / delete membership for related contacts. * * This function will create/update/delete membership for related * contact based on 1) contact have active membership 2) that * membership is is extedned by the same relationship type to that * of the existing relationship. * * @param $contactId Int contact id * @param $params array array of values submitted by POST * @param $ids array array of ids * @param $action which action called this function * * @static * */ static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) { // Check the end date and set the status of the relationship // accrodingly. $status = self::CURRENT; if (!empty($params['end_date'])) { $endDate = CRM_Utils_Date::setDateDefaults(CRM_Utils_Date::format($params['end_date']), NULL, 'Ymd'); $today = date('Ymd'); if ($today > $endDate) { $status = self::PAST; } } if ($action & CRM_Core_Action::ADD && $status & self::PAST) { // if relationship is PAST and action is ADD, no qustion // of creating RELATED membership and return back to // calling method return; } $rel = explode('_', $params['relationship_type_id']); $relTypeId = $rel[0]; $relDirection = "_{$rel[1]}_{$rel[2]}"; $targetContact = array(); if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) { $contact = $contactId; $targetContact = CRM_Utils_Array::value('contact_check', $params); } elseif ($action & CRM_Core_Action::UPDATE) { $contact = $ids['contact']; $targetContact = array($ids['contactTarget'] => 1); } // Build the 'values' array for // 1. ContactA // 2. ContactB // This will allow us to check if either of the contacts in // relationship have active memberships. $values = array(); // 1. ContactA $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection); // 2. ContactB if (!empty($targetContact)) { foreach ($targetContact as $cid => $donCare) { $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId); $relTypeParams = array('id' => $relTypeId); $relTypeValues = array(); CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues); if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) { $values[$cid]['relationshipTypeDirection'] = '_a_b'; } else { $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b'; } } } // Now get the active memberships for all the contacts. // If contact have any valid membership(s), then add it to // 'values' array. foreach ($values as $cid => $subValues) { $memParams = array('contact_id' => $cid); $memberships = array(); CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active); if (empty($memberships)) { continue; } $values[$cid]['memberships'] = $memberships; } $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus()); // done with 'values' array. // Finally add / edit / delete memberships for the related contacts foreach ($values as $cid => $details) { if (!array_key_exists('memberships', $details)) { continue; } $mainRelatedContactId = key(CRM_Utils_Array::value('relatedContacts', $details, array())); foreach ($details['memberships'] as $membershipId => $membershipValues) { $relTypeIds = array(); if ($action & CRM_Core_Action::DELETE) { // Delete memberships of the related contacts only if relationship type exists for membership type $query = "\nSELECT relationship_type_id, relationship_direction\n FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}"; $dao = CRM_Core_DAO::executeQuery($query); $relTypeDirs = array(); while ($dao->fetch()) { $relTypeId = $dao->relationship_type_id; $relDirection = $dao->relationship_direction; } $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId); if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) { CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId); } continue; } if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) { // If relationship is PAST and action is UPDATE // then delete the RELATED membership CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']); continue; } // add / edit the memberships for related // contacts. // Get the Membership Type Details. $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']); // Check if contact's relationship type exists in membership type $relTypeDirs = array(); if (CRM_Utils_Array::value('relationship_type_id', $membershipType)) { $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']); } if (CRM_Utils_Array::value('relationship_direction', $membershipType)) { $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']); } foreach ($relTypeIds as $key => $value) { $relTypeDirs[] = $value . '_' . $relDirections[$key]; } $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection']; if (in_array($relTypeDir, $relTypeDirs)) { // Check if relationship being created/updated is // similar to that of membership type's // relationship. $membershipValues['owner_membership_id'] = $membershipId; unset($membershipValues['id']); unset($membershipValues['membership_contact_id']); unset($membershipValues['contact_id']); unset($membershipValues['membership_id']); foreach ($details['relatedContacts'] as $relatedContactId => $donCare) { $membershipValues['contact_id'] = $relatedContactId; if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) { $membershipValues['status_id'] = $deceasedStatusId; $membershipValues['skipStatusCal'] = TRUE; } foreach (array('join_date', 'start_date', 'end_date') as $dateField) { if (CRM_Utils_Array::value($dateField, $membershipValues)) { $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]); } } if ($action & CRM_Core_Action::UPDATE) { //delete the membership record for related //contact before creating new membership record. CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId); } // check whether we have some related memberships still available $query = "\nSELECT count(*)\n FROM civicrm_membership\n LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n AND is_current_member = 1"; $result = CRM_Core_DAO::singleValueQuery($query); if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) { CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray); } } } elseif ($action & CRM_Core_Action::UPDATE) { // if action is update and updated relationship do // not match with the existing // membership=>relationship then we need to // delete the membership record created for // previous relationship. if (self::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array::value('relationship_ids', $params))) { CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId); } } } } }
/** * Function to create / update / delete membership for related contacts. * * This function will create/update/delete membership for related * contact based on 1) contact have active membership 2) that * membership is is extedned by the same relationship type to that * of the existing relationship. * * @param $contactId Int contact id * @param $params array array of values submitted by POST * @param $ids array array of ids * @param $action which action called this function * * @static * */ static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = true) { // Check the end date and set the status of the relationship // accrodingly. $status = self::CURRENT; if (!empty($params['end_date'])) { $endDate = CRM_Utils_Date::setDateDefaults($params['end_date'], null, 'Ymd'); $today = date('Ymd'); if ($today > $endDate) { $status = self::PAST; } } if ($action & CRM_Core_Action::ADD && $status & self::PAST) { // if relationship is PAST and action is ADD, no qustion // of creating RELATED membership and return back to // calling method return; } $rel = explode("_", $params['relationship_type_id']); $relTypeId = $rel[0]; $relDirection = "_{$rel[1]}_{$rel[2]}"; $targetContact = array(); if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) { $contact = $contactId; $targetContact = CRM_Utils_Array::value('contact_check', $params); } else { if ($action & CRM_Core_Action::UPDATE) { $contact = $ids['contact']; $targetContact = array($ids['contactTarget'] => 1); } } // Build the 'values' array for // 1. ContactA // 2. ContactB // This will allow us to check if either of the contacts in // relationship have active memberships. $values = array(); // 1. ContactA $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection); // 2. ContactB if (!empty($targetContact)) { foreach ($targetContact as $cid => $donCare) { $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId); $relTypeParams = array('id' => $relTypeId); $relTypeValues = array(); require_once 'CRM/Contact/BAO/RelationshipType.php'; CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues); if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) { $values[$cid]['relationshipTypeDirection'] = '_a_b'; } else { $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b'; } } } // Now get the active memberships for all the contacts. // If contact have any valid membership(s), then add it to // 'values' array. foreach ($values as $cid => $subValues) { $memParams = array('contact_id' => $cid); $memberships = array(); require_once 'CRM/Member/BAO/Membership.php'; CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active); if (empty($memberships)) { continue; } $values[$cid]['memberships'] = $memberships; } // done with 'values' array. // Finally add / edit / delete memberships for the related contacts foreach ($values as $cid => $details) { if (!array_key_exists('memberships', $details)) { continue; } require_once 'CRM/Member/BAO/MembershipType.php'; foreach ($details['memberships'] as $membershipId => $membershipValues) { if ($action & CRM_Core_Action::DELETE) { // delete memberships of the related contacts. CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId); continue; } if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) { // If relationship is PAST and action is UPDATE // then delete the RELATED membership CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']); continue; } // add / edit the memberships for related // contacts. // Get the Membership Type Details. $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']); if ("{$details['relationshipTypeId']}{$details['relationshipTypeDirection']}" == CRM_Utils_Array::value('relationship_type_id', $membershipType) . "_" . CRM_Utils_Array::value('relationship_direction', $membershipType)) { // Check if relationship being created/updated is // similar to that of membership type's // relationship. $membershipValues['owner_membership_id'] = $membershipId; unset($membershipValues['id']); unset($membershipValues['membership_contact_id']); unset($membershipValues['contact_id']); unset($membershipValues['membership_id']); foreach ($details['relatedContacts'] as $relatedContactId => $donCare) { $membershipValues['contact_id'] = $relatedContactId; if ($action & CRM_Core_Action::UPDATE) { //delete the membership record for related //contact before creating new membership record. CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId); } CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray); } } else { if ($action & CRM_Core_Action::UPDATE) { // if action is update and updated relationship do // not match with the existing // membership=>relationship then we need to // delete the membership record created for // previous relationship. CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $ids['contactTarget']); } } } } }
/** * where / qill clause for relationship * * @return void * @access public */ function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; // also get values array for relation_target_name // for relatinship search we always do wildcard $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $targetGroup = $this->getWhereValues('relation_target_group', $grouping); $nameClause = $name = NULL; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rel = explode('_', $value); self::$_relType = $rel[1]; $params = array('id' => $rel[0]); $rTypeValues = array(); $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); if (!$rType) { return; } if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { self::$_relType = 'reciprocal'; } if ($nameClause) { $this->_where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); if ($nameClause || !$targetGroup) { $this->_qill[$grouping][] = "{$allRelationshipType[$value]} {$name}"; } //check to see if the target contact is in specified group if ($targetGroup) { //add contacts from static groups $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id"; $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") )"; //add contacts from saved searches $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b"); //set the group where clause if ($ssWhere) { $groupWhere[] = "( " . $ssWhere . " )"; } $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )"; //Get the names of the target groups for the qill $groupNames =& CRM_Core_PseudoConstant::group(); $qillNames = array(); foreach ($targetGroup[2] as $groupId) { if (array_key_exists($groupId, $groupNames)) { $qillNames[] = $groupNames[$groupId]; } } $this->_qill[$grouping][] = "{$allRelationshipType[$value]} ( " . implode(", ", $qillNames) . " )"; } //check for active, inactive and all relation status $today = date('Ymd'); if ($relStatus[2] == 0) { $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 1 AND\n( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND\n( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )\n)"; $this->_qill[$grouping][] = ts('Relationship - Active'); } elseif ($relStatus[2] == 1) { $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 0 OR\ncivicrm_relationship.end_date < {$today} OR\ncivicrm_relationship.start_date > {$today}\n)"; $this->_qill[$grouping][] = ts('Relationship - Inactive'); } $this->_where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0]; $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = TRUE; }
/** * Function to create relationship type * * @param array $params Associative array of property name/value pairs to insert in new relationship type. * * @return Newly created Relationship_type object * * @access public * */ function crm_create_relationship_type($params) { if (!isset($params['name_a_b']) and !isset($params['name_b_a']) and !isset($params['contact_type_a']) and !isset($params['contact_type_b'])) { return _crm_error('Return array is not properly set'); } require_once 'CRM/Contact/BAO/RelationshipType.php'; $relationType = CRM_Contact_BAO_RelationshipType::add($params, $ids); return $relationType; }
/** * Where / qill clause for relationship. * * @param array $values */ public function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; if ($this->_relationshipValuesAdded) { return; } // also get values array for relation_target_name // for relationship search we always do wildcard $relationType = $this->getWhereValues('relation_type_id', $grouping); $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $relPermission = $this->getWhereValues('relation_permission', $grouping); $targetGroup = $this->getWhereValues('relation_target_group', $grouping); $nameClause = $name = NULL; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rTypeValues = array(); if (!empty($relationType)) { $rel = explode('_', $relationType[2]); self::$_relType = $rel[1]; $params = array('id' => $rel[0]); $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); } if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { // if we don't know which end of the relationship we are dealing with we'll create a temp table //@todo unless we are dealing with a target group self::$_relType = 'reciprocal'; } // if we are creating a temp table we build our own where for the relationship table $relationshipTempTable = NULL; if (self::$_relType == 'reciprocal' && empty($targetGroup)) { $where = array(); self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel'); if ($nameClause) { $where[$grouping][] = " sort_name {$nameClause} "; } } else { $where =& $this->_where; if ($nameClause) { $where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } } $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE); if ($nameClause || !$targetGroup) { if (!empty($relationType)) { $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " {$name}"; } else { $this->_qill[$grouping][] = $name; } } //check to see if the target contact is in specified group if ($targetGroup) { //add contacts from static groups $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'"; $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") ) "; //add contacts from saved searches $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op); //set the group where clause if ($ssWhere) { $groupWhere[] = "( " . $ssWhere . " )"; } $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )"; //Get the names of the target groups for the qill $groupNames = CRM_Core_PseudoConstant::group(); $qillNames = array(); foreach ($targetGroup[2] as $groupId) { if (array_key_exists($groupId, $groupNames)) { $qillNames[] = $groupNames[$groupId]; } } if (!empty($relationType)) { $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )"; } else { $this->_qill[$grouping][] = implode(", ", $qillNames); } } // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way $today = date('Ymd'); //check for active, inactive and all relation status if ($relStatus[2] == 0) { $where[$grouping][] = "(\ncivicrm_relationship.is_active = 1 AND\n( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND\n( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )\n)"; $this->_qill[$grouping][] = ts('Relationship - Active and Current'); } elseif ($relStatus[2] == 1) { $where[$grouping][] = "(\ncivicrm_relationship.is_active = 0 OR\ncivicrm_relationship.end_date < {$today} OR\ncivicrm_relationship.start_date > {$today}\n)"; $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current'); } $onlyDeleted = 0; if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) { $onlyDeleted = 1; } $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})"; //check for permissioned, non-permissioned and all permissioned relations if ($relPermission[2] == 1) { $where[$grouping][] = "(\ncivicrm_relationship.is_permission_a_b = 1\n)"; $this->_qill[$grouping][] = ts('Relationship - Permissioned'); } elseif ($relPermission[2] == 2) { //non-allowed permission relationship. $where[$grouping][] = "(\ncivicrm_relationship.is_permission_a_b = 0\n)"; $this->_qill[$grouping][] = ts('Relationship - Non-permissioned'); } $this->addRelationshipDateClauses($grouping, $where); if (!empty($relationType) && !empty($rType) && isset($rType->id)) { $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id; } $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = TRUE; $this->_relationshipValuesAdded = TRUE; // it could be a or b, using an OR creates an unindexed join - better to create a temp table & // join on that, // @todo creating a temp table could be expanded to group filter // as even creating a temp table of all relationships is much much more efficient than // an OR in the join if ($relationshipTempTable) { $whereClause = ''; if (!empty($where[$grouping])) { $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]); $whereClause = str_replace('contact_b', 'c', $whereClause); } $sql = "\n CREATE TEMPORARY TABLE {$relationshipTempTable}\n (SELECT contact_id_b as contact_id, civicrm_relationship.id\n FROM civicrm_relationship\n INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id\n {$whereClause} )\n UNION\n (SELECT contact_id_a as contact_id, civicrm_relationship.id\n FROM civicrm_relationship\n INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id\n {$whereClause} )\n "; CRM_Core_DAO::executeQuery($sql); } }
/** * Get conatct membership record. * * This api is used for finding an existing membership record. * This api will also return the mebership records for the contacts * having mebership based on the relationship with the direct members. * * @param Int $contactID ID of a contact * * @return Array of all found membership property values. * @access public */ function crm_get_contact_memberships($contactID) { _crm_initialize(); if (empty($contactID)) { return _crm_error('Invalid value for ContactID.'); } // get the membership for the given contact ID require_once 'CRM/Member/BAO/Membership.php'; $membership = array('contact_id' => $contactID); $membershipValues = array(); CRM_Member_BAO_Membership::getValues($membership, $membershipValues); if (empty($membershipValues)) { return _crm_error('No memberships for this contact.'); } foreach ($membershipValues as $membershipId => $values) { // populate the membership type name for the membership type id require_once 'CRM/Member/BAO/MembershipType.php'; $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); $membershipValues[$membershipId]['membership_name'] = $membershipType['name']; $relationships[$membershipType['relationship_type_id']] = $membershipId; // populating relationship type name. require_once 'CRM/Contact/BAO/RelationshipType.php'; $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $membershipType['relationship_type_id']; if ($relationshipType->find(true)) { $membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b; } } $members[$contactID] = $membershipValues; // populating contacts in members array based on their relationship with direct members. require_once 'CRM/Contact/BAO/Relationship.php'; foreach ($relationships as $relTypeId => $membershipId) { // As members are not direct members, there should not be // membership id in the result array. unset($membershipValues[$membershipId]['id']); $relationship = new CRM_Contact_BAO_Relationship(); $relationship->contact_id_b = $contactID; $relationship->relationship_type_id = $relTypeId; if ($relationship->find()) { while ($relationship->fetch()) { clone $relationship; $membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a; $members[$contactID][$relationship->contact_id_a] = $membershipValues[$membershipId]; } } } return $members; }
/** * Where / qill clause for relationship_type * * @param $values * * @return void */ public function relationshipType(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; $clause = array(); foreach ($value as $k => $relationship_type_value) { // we gebruiken de key om relaties in 2 richtingen op te vangen. $relationship_type_id = substr_replace($relationship_type_value, "", -4); $relationship_type_params = array('id' => $relationship_type_id); CRM_Contact_BAO_RelationshipType::retrieve($relationship_type_params, $relationship_type); $clause[$relationship_type['label_a_b']] = $relationship_type_id; } $this->_where[$grouping][] = "relationship.relationship_type_id {$op} ('" . implode("', '", $clause) . "')"; $this->_qill[$grouping][] = ts('Relationship Type') . " {$op} " . implode(' ' . ts('or') . ' ', array_keys($clause)); }
/** * where / qill clause for relationship * * @return void * @access public */ function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; // also get values array for relation_target_name // for relatinship search we always do wildcard $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $nameClause = null; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rel = explode('_', $value); self::$_relType = $rel[1]; if ($nameClause) { require_once 'CRM/Contact/BAO/RelationshipType.php'; $params = array('id' => $rel[0]); $rTypeValues = array(); require_once "CRM/Contact/BAO/RelationshipType.php"; $rType =& CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); if (!$rType) { return; } // for relatinship search we always do wildcard if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { self::$_relType = 'reciprocal'; } $this->_where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } require_once 'CRM/Contact/BAO/Relationship.php'; $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); $this->_qill[$grouping][] = "{$allRelationshipType[$value]} {$name}"; //check for active, inactive and all relation status $today = date('Ymd'); if ($relStatus[2] == 0) { $this->_where[$grouping][] = "civicrm_relationship.is_active = 1 AND ( civicrm_relationship.end_date is NULL OR civicrm_relationship.end_date >= {$today} )"; $this->_qill[$grouping][] = ts('Relationship - Active'); } else { if ($relStatus[2] == 1) { $this->_where[$grouping][] = "(civicrm_relationship.is_active = 0 OR civicrm_relationship.end_date < {$today})"; $this->_qill[$grouping][] = ts('Relationship - Inactive'); } } $this->_where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0]; $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = true; }
/** * Function to process the form * * @access public * @return None */ function postProcess() { if ($this->_action & CRM_CORE_ACTION_DELETE) { CRM_Contact_BAO_RelationshipType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Relationship type has been deleted.')); } else { $params = array(); $ids = array(); // store the submitted values in an array $params = $this->exportValues(); $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false); if ($this->_action & CRM_CORE_ACTION_UPDATE) { $ids['relationshipType'] = $this->_id; } CRM_Contact_BAO_RelationshipType::add($params, $ids); CRM_Core_Session::setStatus(ts('The Relationship Type has been saved.')); } }
public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select_Relationship::RELATIONSHIP_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND') { $headerRows = $returnProperties = array(); $queryMode = CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS; //Welke velden exporteren, gezet bij een mapping, indien niet gezet, primary fields. if ($fields) { foreach ($fields as $key => $value) { $fieldName = CRM_Utils_Array::value(0, $value); if (!$fieldName) { continue; } $returnProperties[$fieldName] = 1; } } else { // Copied from CRM_Relationship_BAO_QUERY should be refactored to seperate // method. $fields = CRM_Contact_BAO_Relationship::fields(); // Add display_name for both contacts $contact_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE); $fields['contact_a'] = $contact_fields['display_name']; $fields['contact_a']['where'] = 'contact_a.display_name'; $fields['contact_b'] = $contact_fields['display_name']; $fields['contact_b']['where'] = 'contact_b.display_name'; // Add relationship type field $relationship_type_fields = CRM_Contact_BAO_RelationshipType::fields(); $fields['relationship_type'] = $relationship_type_fields['label_a_b']; $fields['relationship_type']['where'] = 'relationship_type.label_a_b'; // Add custom fields $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Relationship')); $returnProperties = CRM_Relationship_BAO_Query::defaultReturnProperties(); } if ($moreReturnProperties) { $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $query = new CRM_Relationship_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, FALSE, TRUE, $queryOperator); //sort by state //CRM-15301 $query->_sort = $order; list($select, $from, $where, $having) = $query->query(); $allRelContactArray = $relationQuery = array(); if (!$selectAll && $componentTable) { // TODO For not select all //$from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id "; } elseif ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } $queryString = "{$select} {$from} {$where} {$having}"; $groupBy = ""; if ($queryMode & CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS && $query->_useGroupBy) { $groupBy = " GROUP BY relationship.id"; } $queryString .= $groupBy; // always add relationship.id to the ORDER clause // so the order is deterministic if (strpos('relationship.id', $order) === FALSE) { $order .= ", relationship.id"; } if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (!empty($returnProperties[$field])) { //CRM-15301 $queryString .= " ORDER BY {$order}"; } } $componentDetails = $headerRows = $sqlColumns = array(); $setHeader = TRUE; $rowCount = self::EXPORT_ROW_COUNT; $offset = 0; // we write to temp table often to avoid using too much memory $tempRowCount = 100; $count = -1; // for CRM-3157 purposes $i18n = CRM_Core_I18n::singleton(); $outputColumns = array(); //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing foreach ($returnProperties as $key => $value) { $outputColumns[$key] = $value; } while (1) { $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; $dao = CRM_Core_DAO::executeQuery($limitQuery); if ($dao->N <= 0) { break; } while ($dao->fetch()) { $count++; $row = array(); //convert the pseudo constants // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned // temporary iterationDAO object to get around it. // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object // these additional properties are NOT reset when the $dao cycles through the while loop // nor are they overwritten as they are not in the loop // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the // relevant property is set. // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the // export class before tackling a better architectural fix $iterationDAO = clone $dao; //first loop through output columns so that we return what is required, and in same order. foreach ($outputColumns as $field => $value) { //we should set header only once if ($setHeader) { $sqlDone = FALSE; $headerRows[] = $query->_fields[$field]['title']; if (!$sqlDone) { self::sqlColumnDefn($query, $sqlColumns, $field); } } //build row values (data) $fieldValue = NULL; if (property_exists($iterationDAO, $field)) { $fieldValue = $iterationDAO->{$field}; } if ($field == 'id') { $row[$field] = $iterationDAO->relationship_id; } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options); } else { //normal fields with a touch of CRM-3157 $row[$field] = $fieldValue; } } else { // if field is empty or null $row[$field] = ''; } } if ($setHeader) { $exportTempTable = self::createTempTable($sqlColumns); } //build header only once $setHeader = FALSE; // add component info // write the row to a file $componentDetails[] = $row; // output every $tempRowCount rows if ($count % $tempRowCount == 0) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); $componentDetails = array(); } } $dao->free(); $offset += $rowCount; } if ($exportTempTable) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); // do merge same address and merge same household processing if ($mergeSameAddress) { self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams); } // merge the records if they have corresponding households if ($mergeSameHousehold) { self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH); self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH); } // call export hook CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode); // now write the CSV file self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); // delete the export temp table and component table $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; CRM_Core_DAO::executeQuery($sql); CRM_Utils_System::civiExit(); } else { CRM_Core_Error::fatal(ts('No records to export')); } }
/** * Delete a relationship type delete * * @param id of relationship type $id * * @return array API Result Array * {@getfields RelationshipType_delete} * @static void * @access public */ function civicrm_api3_relationship_type_delete($params) { require_once 'CRM/Utils/Rule.php'; if ($params['id'] != NULL && !CRM_Utils_Rule::integer($params['id'])) { return civicrm_api3_create_error('Invalid value for relationship type ID'); } $relationTypeBAO = new CRM_Contact_BAO_RelationshipType(); $result = $relationTypeBAO->del($params['id']); if (!$result) { return civicrm_api3_create_error('Could not delete relationship type'); } return civicrm_api3_create_success($result, $params, 'relationship_type', 'delete', $relationTypeBAO); }
/** * Delete a relationship type delete * * @param id of relationship type $id * * @return boolean true if success, else false * @static void * @access public */ function civicrm_relationship_type_delete(&$params) { if (!CRM_Utils_Array::value('id', $params)) { return civicrm_create_error('Missing required parameter'); } require_once 'CRM/Utils/Rule.php'; if ($params['id'] != null && !CRM_Utils_Rule::integer($params['id'])) { return civicrm_create_error('Invalid value for relationship type ID'); } $relationTypeBAO = new CRM_Contact_BAO_RelationshipType(); return $relationTypeBAO->del($params['id']) ? civicrm_create_success(ts('Deleted relationship type successfully')) : civicrm_create_error(ts('Could not delete relationship type')); }
/** * non-standard behaviour inherited from v2 * @param array $params parameters passed into get function * @return array result for calling function */ function _civicrm_api3_membership_relationsship_get_customv2behaviour(&$params, $membershipValues, $contactID) { $relationships = array(); foreach ($membershipValues as $membershipId => $values) { // populate the membership type name for the membership type id $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); $membershipValues[$membershipId]['membership_name'] = $membershipType['name']; if (!empty($membershipType['relationship_type_id'])) { $relationships[$membershipType['relationship_type_id']] = $membershipId; } // populating relationship type name. $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = CRM_Utils_Array::value('relationship_type_id', $membershipType); if ($relationshipType->find(TRUE)) { $membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b; } _civicrm_api3_custom_data_get($membershipValues[$membershipId], 'Membership', $membershipId, NULL, $values['membership_type_id']); } $members = $membershipValues; // populating contacts in members array based on their relationship with direct members. if (!empty($relationships)) { foreach ($relationships as $relTypeId => $membershipId) { // As members are not direct members, there should not be // membership id in the result array. unset($membershipValues[$membershipId]['id']); $relationship = new CRM_Contact_BAO_Relationship(); $relationship->contact_id_b = $contactID; $relationship->relationship_type_id = $relTypeId; if ($relationship->find()) { while ($relationship->fetch()) { clone $relationship; $membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a; $members[$membershipId]['related_contact_id'] = $relationship->contact_id_a; } } } } return $members; }
/** * Check if an error in custom data. * * @param array $params * @param string $errorMessage * A string containing all the error-fields. * * @param null $csType * @param null $relationships */ public static function isErrorInCustomData($params, &$errorMessage, $csType = NULL, $relationships = NULL) { $session = CRM_Core_Session::singleton(); $dateType = $session->get("dateTypes"); if (!empty($params['contact_sub_type'])) { $csType = CRM_Utils_Array::value('contact_sub_type', $params); } if (empty($params['contact_type'])) { $params['contact_type'] = 'Individual'; } $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, FALSE, $csType); $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address'); $customFields = $customFields + $addressCustomFields; foreach ($params as $key => $value) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { /* check if it's a valid custom field id */ if (!array_key_exists($customFieldID, $customFields)) { self::addToErrorMsg(ts('field ID'), $errorMessage); } // validate null values for required custom fields of type boolean if (!empty($customFields[$customFieldID]['is_required']) && (empty($params['custom_' . $customFieldID]) && !is_numeric($params['custom_' . $customFieldID])) && $customFields[$customFieldID]['data_type'] == 'Boolean') { self::addToErrorMsg($customFields[$customFieldID]['label'] . '::' . $customFields[$customFieldID]['groupTitle'], $errorMessage); } //For address custom fields, we do get actual custom field value as an inner array of //values so need to modify if (array_key_exists($customFieldID, $addressCustomFields)) { $value = $value[0][$key]; } /* validate the data against the CF type */ if ($value) { if ($customFields[$customFieldID]['data_type'] == 'Date') { if (array_key_exists($customFieldID, $addressCustomFields) && CRM_Utils_Date::convertToDefaultDate($params[$key][0], $dateType, $key)) { $value = $params[$key][0][$key]; } elseif (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { $value = $params[$key]; } else { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { if (CRM_Utils_String::strtoboolstr($value) === FALSE) { self::addToErrorMsg($customFields[$customFieldID]['label'] . '::' . $customFields[$customFieldID]['groupTitle'], $errorMessage); } } // need not check for label filed import $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio', 'Multi-Select State/Province', 'Multi-Select Country'); if (!in_array($customFields[$customFieldID]['html_type'], $htmlType) || $customFields[$customFieldID]['data_type'] == 'Boolean' || $customFields[$customFieldID]['data_type'] == 'ContactReference') { $valid = CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $value); if (!$valid) { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } // check for values for custom fields for checkboxes and multiselect if ($customFields[$customFieldID]['html_type'] == 'CheckBox' || $customFields[$customFieldID]['html_type'] == 'AdvMulti-Select' || $customFields[$customFieldID]['html_type'] == 'Multi-Select') { $value = trim($value); $value = str_replace('|', ',', $value); $mulValues = explode(',', $value); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE); foreach ($mulValues as $v1) { if (strlen($v1) == 0) { continue; } $flag = FALSE; foreach ($customOption as $v2) { if (strtolower(trim($v2['label'])) == strtolower(trim($v1)) || strtolower(trim($v2['value'])) == strtolower(trim($v1))) { $flag = TRUE; } } if (!$flag) { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } } elseif ($customFields[$customFieldID]['html_type'] == 'Select' || $customFields[$customFieldID]['html_type'] == 'Radio' && $customFields[$customFieldID]['data_type'] != 'Boolean') { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE); $flag = FALSE; foreach ($customOption as $v2) { if (strtolower(trim($v2['label'])) == strtolower(trim($value)) || strtolower(trim($v2['value'])) == strtolower(trim($value))) { $flag = TRUE; } } if (!$flag) { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select State/Province') { $mulValues = explode(',', $value); foreach ($mulValues as $stateValue) { if ($stateValue) { if (self::in_value(trim($stateValue), CRM_Core_PseudoConstant::stateProvinceAbbreviation()) || self::in_value(trim($stateValue), CRM_Core_PseudoConstant::stateProvince())) { continue; } else { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } } } elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select Country') { $mulValues = explode(',', $value); foreach ($mulValues as $countryValue) { if ($countryValue) { CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active'); CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code'); $config = CRM_Core_Config::singleton(); $limitCodes = $config->countryLimit(); $error = TRUE; foreach (array($countryNames, $countryIsoCodes, $limitCodes) as $values) { if (in_array(trim($countryValue), $values)) { $error = FALSE; break; } } if ($error) { self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage); } } } } } } elseif (is_array($params[$key]) && isset($params[$key]["contact_type"])) { //CRM-5125 //supporting custom data of related contact subtypes $relation = NULL; if ($relationships) { if (array_key_exists($key, $relationships)) { $relation = $key; } elseif (CRM_Utils_Array::key($key, $relationships)) { $relation = CRM_Utils_Array::key($key, $relationships); } } if (!empty($relation)) { list($id, $first, $second) = CRM_Utils_System::explode('_', $relation, 3); $direction = "contact_sub_type_{$second}"; $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $id; if ($relationshipType->find(TRUE)) { if (isset($relationshipType->{$direction})) { $params[$key]['contact_sub_type'] = $relationshipType->{$direction}; } } $relationshipType->free(); } self::isErrorInCustomData($params[$key], $errorMessage, $csType, $relationships); } } }
/** * Function to process the form * * @access public * @return None */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contact_BAO_RelationshipType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Relationship type has been deleted.')); } else { $params = array(); $ids = array(); // store the submitted values in an array $params = $this->exportValues(); $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false); if ($this->_action & CRM_Core_Action::UPDATE) { $ids['relationshipType'] = $this->_id; } $cTypeA = CRM_Utils_System::explode(CRM_Core_DAO::VALUE_SEPARATOR, $params['contact_types_a'], 2); $cTypeB = CRM_Utils_System::explode(CRM_Core_DAO::VALUE_SEPARATOR, $params['contact_types_b'], 2); $params['contact_type_a'] = $cTypeA[0]; $params['contact_type_b'] = $cTypeB[0]; $params['contact_sub_type_a'] = $cTypeA[1] ? $cTypeA[1] : 'NULL'; $params['contact_sub_type_b'] = $cTypeB[1] ? $cTypeB[1] : 'NULL'; CRM_Contact_BAO_RelationshipType::add($params, $ids); CRM_Core_Session::setStatus(ts('The Relationship Type has been saved.')); } }
/** * Build the mapping form. * * @param CRM_Core_Form $form * @param string $mappingType * (Export/Import/Search Builder). * @param int $mappingId * @param int $columnNo * @param int $blockCount * (no of blocks shown). * @param NULL $exportMode * * @return void */ public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) { if ($mappingType == 'Export') { $name = "Map"; $columnCount = array('1' => $columnNo); } elseif ($mappingType == 'Search Builder') { $name = "Builder"; $columnCount = $columnNo; } //get the saved mapping details if ($mappingType == 'Export') { $form->applyFilter('saveMappingName', 'trim'); //to save the current mappings if (!isset($mappingId)) { $saveDetailsName = ts('Save this field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } else { $form->assign('loadedMapping', $mappingId); $params = array('id' => $mappingId); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $form->assign('savedName', $mappingDetails->name); $form->add('hidden', 'mappingId', $mappingId); $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId')); } elseif ($mappingType == 'Search Builder') { $form->addElement('submit', 'addBlock', ts('Also include contacts where'), array('class' => 'submit-link')); } $defaults = array(); $hasLocationTypes = array(); $hasRelationTypes = array(); $fields = array(); if ($mappingType == 'Export') { $required = TRUE; } elseif ($mappingType == 'Search Builder') { $required = FALSE; } $contactType = array('Individual', 'Household', 'Organization'); foreach ($contactType as $value) { $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required); $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // exclude the address options disabled in the Address Settings $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields); ksort($fields[$value]); if ($mappingType == 'Export') { $relationships = array(); $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value); asort($relationshipTypes); foreach ($relationshipTypes as $key => $var) { list($type) = explode('_', $key); $relationships[$key]['title'] = $var; $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationships[$key]['export'] = TRUE; $relationships[$key]['relationship_type_id'] = $type; $relationships[$key]['related'] = TRUE; $relationships[$key]['hasRelationType'] = 1; } if (!empty($relationships)) { $fields[$value] = array_merge($fields[$value], array('related' => array('title' => ts('- related contact info -'))), $relationships); } } } //get the current employer for mapping. if ($required) { $fields['Individual']['current_employer']['title'] = ts('Current Employer'); } // add component fields $compArray = array(); //we need to unset groups, tags, notes for component export if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) { foreach (array('groups', 'tags', 'notes') as $value) { unset($fields['Individual'][$value]); unset($fields['Household'][$value]); unset($fields['Organization'][$value]); } } if ($mappingType == 'Search Builder') { //build the common contact fields array. $fields['Contact'] = array(); foreach ($fields['Individual'] as $key => $value) { if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) { $fields['Contact'][$key] = $value; unset($fields['Organization'][$key], $fields['Household'][$key], $fields['Individual'][$key]); } } if (array_key_exists('note', $fields['Contact'])) { $noteTitle = $fields['Contact']['note']['title']; $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject'); $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'); $fields['Contact']['note_subject'] = array('title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { if (CRM_Core_Permission::access('CiviContribute')) { $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields(); foreach (array('contribution_contact_id', 'contribution_soft_credit_name', 'contribution_soft_credit_amount', 'contribution_soft_credit_type', 'contribution_soft_credit_contribution_id') as $element) { unset($fields['Contribution'][$element]); } $compArray['Contribution'] = ts('Contribution'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { if (CRM_Core_Permission::access('CiviEvent')) { $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields(); //get the component payment fields if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $componentPaymentFields = array(); foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) { $componentPaymentFields[$payField] = array('title' => $payTitle); } $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields); } $compArray['Participant'] = ts('Participant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { if (CRM_Core_Permission::access('CiviMember')) { $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode); unset($fields['Membership']['membership_contact_id']); $compArray['Membership'] = ts('Membership'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { if (CRM_Core_Permission::access('CiviPledge')) { $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields(); unset($fields['Pledge']['pledge_contact_id']); $compArray['Pledge'] = ts('Pledge'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CASE_EXPORT) { if (CRM_Core_Permission::access('CiviCase')) { $fields['Case'] = CRM_Case_BAO_Case::exportableFields(); $compArray['Case'] = ts('Case'); $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case'); $compArray['Activity'] = ts('Case Activity'); unset($fields['Case']['case_contact_id']); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { if (CRM_Core_Permission::access('CiviGrant')) { $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields(); unset($fields['Grant']['grant_contact_id']); if ($mappingType == 'Search Builder') { unset($fields['Grant']['grant_type_id']); } $compArray['Grant'] = ts('Grant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity'); $compArray['Activity'] = ts('Activity'); } //Contact Sub Type For export $contactSubTypes = array(); $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $subType => $val) { //adding subtype specific relationships CRM-5256 $csRelationships = array(); if ($mappingType == 'Export') { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); foreach ($subTypeRelationshipTypes as $key => $var) { if (!array_key_exists($key, $fields[$val['parent']])) { list($type) = explode('_', $key); $csRelationships[$key]['title'] = $var; $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $csRelationships[$key]['export'] = TRUE; $csRelationships[$key]['relationship_type_id'] = $type; $csRelationships[$key]['related'] = TRUE; $csRelationships[$key]['hasRelationType'] = 1; } } } $fields[$subType] = $fields[$val['parent']] + $csRelationships; //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType); $fields[$subType] += $subTypeFields; if (!empty($subTypeFields) || !empty($csRelationships)) { $contactSubTypes[$subType] = $val['label']; } } unset($subTypes); foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $customGroupName = self::getCustomGroupName($key1); if ($customGroupName) { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title']; } else { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title']; } if (isset($value1['hasLocationType'])) { $hasLocationTypes[$key][$key1] = $value1['hasLocationType']; } if (isset($value1['hasRelationType'])) { $hasRelationTypes[$key][$key1] = $value1['hasRelationType']; unset($relatedMapperFields[$key][$key1]); } } if (array_key_exists('related', $relatedMapperFields[$key])) { unset($relatedMapperFields[$key]['related']); } } $mapperKeys = array_keys($mapperFields); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // FIXME: dirty hack to make the default option show up first. This // avoids a mozilla browser bug with defaults on dynamically constructed // selector widgets. if ($defaultLocationType) { $defaultLocation = $locationTypes[$defaultLocationType->id]; unset($locationTypes[$defaultLocationType->id]); $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes; } $locationTypes = array(' ' => ts('Primary')) + $locationTypes; // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE); if ($mappingType == 'Search Builder') { $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes; } $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray; foreach ($sel1 as $key => $sel) { if ($key) { // sort everything BUT the contactType which is sorted seperately by // an initial commit of CRM-13278 (check ksort above) if (!in_array($key, $contactType)) { asort($mapperFields[$key]); } $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key]; } } $sel3[''] = NULL; $sel5[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); asort($phoneTypes); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($locationTypes as $key => $value) { if (trim($key) != '') { $sel4[$k]['phone'][$key] =& $phoneTypes; $sel4[$k]['im'][$key] =& $imProviders; } } } } foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $key => $value) { if (isset($hasLocationTypes[$k][$key])) { $sel3[$k][$key] = $locationTypes; } else { $sel3[$key] = NULL; } } } } // Array for core fields and relationship custom data $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if ($mappingType == 'Export') { foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $field => $dontCare) { if (isset($hasRelationTypes[$k][$field])) { list($id, $first, $second) = explode('_', $field); // FIX ME: For now let's not expose custom data related to relationship $relationshipCustomFields = array(); //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id ); //asort($relationshipCustomFields); $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $id; if ($relationshipType->find(TRUE)) { $direction = "contact_sub_type_{$second}"; if (isset($relationshipType->{$direction})) { $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$direction}], (array) $relationshipCustomFields); } else { $target_type = 'contact_type_' . $second; $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$target_type}], (array) $relationshipCustomFields); } } $relationshipType->free(); asort($relatedFields); $sel5[$k][$field] = $relatedFields; } } } } //Location Type for relationship fields foreach ($sel5 as $k => $v) { if ($v) { foreach ($v as $rel => $fields) { foreach ($fields as $field => $fieldLabel) { if (isset($hasLocationTypes[$k][$field])) { $sel6[$k][$rel][$field] = $locationTypes; } } } } } //PhoneTypes for relationship fields $sel7[''] = NULL; foreach ($sel6 as $k => $rel) { if ($k) { foreach ($rel as $phonekey => $phonevalue) { foreach ($locationTypes as $locType => $loc) { if (trim($locType) != '') { $sel7[$k][$phonekey]['phone'][$locType] =& $phoneTypes; $sel7[$k][$phonekey]['im'][$locType] =& $imProviders; } } } } } } //special fields that have location, hack for primary location $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); if (isset($mappingId)) { $colCnt = 0; list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId); $blkCnt = count($mappingName); if ($blkCnt >= $blockCount) { $blockCount = $blkCnt + 1; } for ($x = 1; $x < $blockCount; $x++) { if (isset($mappingName[$x])) { $colCnt = count($mappingName[$x]); if ($colCnt >= $columnCount[$x]) { $columnCount[$x] = $colCnt; } } } } $form->_blockCount = $blockCount; $form->_columnCount = $columnCount; $form->set('blockCount', $form->_blockCount); $form->set('columnCount', $form->_columnCount); $defaults = $noneArray = $nullArray = array(); //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($x = 1; $x < $blockCount; $x++) { for ($i = 0; $i < $columnCount[$x]; $i++) { $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if (isset($mappingId)) { $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (isset($mappingName[$x][$i])) { if (is_array($mapperFields[$mappingContactType[$x][$i]])) { if (isset($mappingRelation[$x][$i])) { $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i])); $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) { $relLocationId = " "; } $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingRelation[$x][$i], $locationId, $phoneType, $mappingName[$x][$i], $relLocationId, $relPhoneType); if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 4); } if (!$relLocationId) { $noneArray[] = array($x, $i, 5); } if (!$relPhoneType) { $noneArray[] = array($x, $i, 6); } $noneArray[] = array($x, $i, 2); } else { $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL; if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) { $locationId = " "; } $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingName[$x][$i], $locationId, $phoneType); if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 1); } if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } $noneArray[] = array($x, $i, 4); $noneArray[] = array($x, $i, 5); $noneArray[] = array($x, $i, 6); } $jsSet = TRUE; if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) { $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]); } if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) { $defaults["value[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingValue[$x]); } } } } //Fix for Search Builder if ($mappingType == 'Export') { $j = 7; } else { $j = 4; } $formValues = $form->exportValues(); if (!$jsSet) { if (empty($formValues)) { // Incremented length for third select box(relationship type) for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } else { if (!empty($formValues['mapper'][$x])) { foreach ($formValues['mapper'][$x] as $value) { for ($k = 1; $k < $j; $k++) { if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) { $noneArray[] = array($x, $i, $k); } else { $nullArray[] = array($x, $i, $k); } } } } else { for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } } } //Fix for Search Builder if ($mappingType == 'Export') { if (!isset($mappingId) || $i >= count(reset($mappingName))) { if (isset($formValues['mapper']) && isset($formValues['mapper'][$x][$i][1]) && array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)) { $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4)); } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } if ($mappingType == 'Search Builder') { //CRM -2292, restricted array set $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(); $form->add('select', "operator[{$x}][{$i}]", '', $operatorArray); $form->add('text', "value[{$x}][{$i}]", ''); } } //end of columnCnt for if ($mappingType == 'Search Builder') { $title = ts('Another search field'); } else { $title = ts('Select more fields'); } $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link')); } //end of block for $js = "<script type='text/javascript'>\n"; $formName = "document.{$name}"; if (!empty($nullArray)) { $js .= "var nullArray = ["; $elements = array(); $seen = array(); foreach ($nullArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<nullArray.length;i++) {\n if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n }\n }\n"; } if (!empty($noneArray)) { $js .= "var noneArray = ["; $elements = array(); $seen = array(); foreach ($noneArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<noneArray.length;i++) {\n if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n }\n }\n"; } $js .= "</script>\n"; $form->assign('initHideBoxes', $js); $form->assign('columnCount', $columnCount); $form->assign('blockCount', $blockCount); $form->setDefaults($defaults); $form->setDefaultAction('refresh'); }
/** * Create / update / delete membership for related contacts. * * This function will create/update/delete membership for related * contact based on 1) contact have active membership 2) that * membership is is extedned by the same relationship type to that * of the existing relationship. * * @param int $contactId * contact id. * @param array $params * array of values submitted by POST. * @param array $ids * array of ids. * @param \const|int $action which action called this function * * @param bool $active * * @throws \CRM_Core_Exception */ public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) { // Check the end date and set the status of the relationship // accordingly. $status = self::CURRENT; $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, array()); $today = date('Ymd'); // If a relationship hasn't yet started, just return for now // TODO: handle edge-case of updating start_date of an existing relationship if (!empty($params['start_date'])) { $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8); if ($today < $startDate) { return; } } if (!empty($params['end_date'])) { $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8); if ($today > $endDate) { $status = self::PAST; } } if ($action & CRM_Core_Action::ADD && $status & self::PAST) { // If relationship is PAST and action is ADD, do nothing. return; } $rel = explode('_', $params['relationship_type_id']); $relTypeId = $rel[0]; if (!empty($rel[1])) { $relDirection = "_{$rel[1]}_{$rel[2]}"; } else { // this call is coming from somewhere where the direction was resolved early on (e.g an api call) // so we can assume _a_b $relDirection = "_a_b"; $targetContact = array($params['contact_id_b'] => 1); } if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) { $contact = $contactId; } elseif ($action & CRM_Core_Action::UPDATE) { $contact = $ids['contact']; $targetContact = array($ids['contactTarget'] => 1); } // Build the 'values' array for // 1. ContactA // 2. ContactB // This will allow us to check if either of the contacts in // relationship have active memberships. $values = array(); // 1. ContactA $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection); // 2. ContactB if (!empty($targetContact)) { foreach ($targetContact as $cid => $donCare) { $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId); $relTypeParams = array('id' => $relTypeId); $relTypeValues = array(); CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues); if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) { $values[$cid]['relationshipTypeDirection'] = '_a_b'; } else { $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b'; } } } // CRM-15829 UPDATES // If we're looking for active memberships we must consider pending (id: 5) ones too. // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships. // As suggested by @davecivicrm, the pending status id is fetched using the CRM_Member_PseudoConstant::membershipStatus() class and method, since these ids differ from system to system. $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus()); $query = 'SELECT * FROM `civicrm_membership_status`'; if ($active) { $query .= ' WHERE `is_current_member` = 1 OR `id` = %1 '; } $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($pendingStatusId, 'Integer'))); while ($dao->fetch()) { $membershipStatusRecordIds[$dao->id] = $dao->id; } // Now get the active memberships for all the contacts. // If contact have any valid membership(s), then add it to // 'values' array. foreach ($values as $cid => $subValues) { $memParams = array('contact_id' => $cid); $memberships = array(); // CRM-15829 UPDATES // Since we want PENDING memberships as well, the $active flag needs to be set to false so that this will return all memberships and we can then filter the memberships based on the status IDs recieved above. CRM_Member_BAO_Membership::getValues($memParams, $memberships, FALSE, TRUE); // CRM-15829 UPDATES // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462 foreach ($memberships as $key => $membership) { if (!isset($memberships[$key]['status_id'])) { continue; } $membershipStatusId = $memberships[$key]['status_id']; if (!isset($membershipStatusRecordIds[$membershipStatusId])) { unset($memberships[$key]); } } if (empty($memberships)) { continue; } //get ownerMembershipIds for related Membership //this is to handle memberships being deleted and recreated if (!empty($memberships['owner_membership_ids'])) { $ownerMemIds[$cid] = $memberships['owner_membership_ids']; unset($memberships['owner_membership_ids']); } $values[$cid]['memberships'] = $memberships; } $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus()); // done with 'values' array. // Finally add / edit / delete memberships for the related contacts foreach ($values as $cid => $details) { if (!array_key_exists('memberships', $details)) { continue; } $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, array())); $mainRelatedContactId = reset($relatedContacts); foreach ($details['memberships'] as $membershipId => $membershipValues) { $relTypeIds = array(); if ($action & CRM_Core_Action::DELETE) { // Delete memberships of the related contacts only if relationship type exists for membership type $query = "\nSELECT relationship_type_id, relationship_direction\n FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}"; $dao = CRM_Core_DAO::executeQuery($query); $relTypeDirs = array(); while ($dao->fetch()) { $relTypeId = $dao->relationship_type_id; $relDirection = $dao->relationship_direction; } $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId); if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) { CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']); } continue; } if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) { // If relationship is PAST and action is UPDATE // then delete the RELATED membership CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']); continue; } // add / edit the memberships for related // contacts. // Get the Membership Type Details. $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']); // Check if contact's relationship type exists in membership type $relTypeDirs = array(); if (!empty($membershipType['relationship_type_id'])) { $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']); } if (!empty($membershipType['relationship_direction'])) { $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']); } foreach ($relTypeIds as $key => $value) { $relTypeDirs[] = $value . '_' . $relDirections[$key]; } $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection']; if (in_array($relTypeDir, $relTypeDirs)) { // Check if relationship being created/updated is // similar to that of membership type's // relationship. $membershipValues['owner_membership_id'] = $membershipId; unset($membershipValues['id']); unset($membershipValues['membership_contact_id']); unset($membershipValues['contact_id']); unset($membershipValues['membership_id']); foreach ($details['relatedContacts'] as $relatedContactId => $donCare) { $membershipValues['contact_id'] = $relatedContactId; if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) { $membershipValues['status_id'] = $deceasedStatusId; $membershipValues['skipStatusCal'] = TRUE; } foreach (array('join_date', 'start_date', 'end_date') as $dateField) { if (!empty($membershipValues[$dateField])) { $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]); } } if ($action & CRM_Core_Action::UPDATE) { //if updated relationship is already related to contact don't delete existing inherited membership if (in_array($relTypeId, $relTypeIds) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) { continue; } //delete the membership record for related //contact before creating new membership record. CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId); } // check whether we have some related memberships still available $query = "\nSELECT count(*)\n FROM civicrm_membership\n LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n AND is_current_member = 1"; $result = CRM_Core_DAO::singleValueQuery($query); if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) { CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray); } } } elseif ($action & CRM_Core_Action::UPDATE) { // if action is update and updated relationship do // not match with the existing // membership=>relationship then we need to // change the status of the membership record to expired for // previous relationship -- CRM-12078. // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function if (empty($params['relationship_ids']) && !empty($params['id'])) { $relIds = array($params['id']); } else { $relIds = CRM_Utils_Array::value('relationship_ids', $params); } if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) { $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label'); $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id'); CRM_Member_BAO_Membership::add($membershipValues); CRM_Core_Session::setStatus(ts("Inherited membership {$type} status was changed to Expired due to the change in relationship type."), ts('Record Updated'), 'alert'); } } } } }
/** * Function to check the membership extended through relationship * * @param int $membershipId membership id * @param int $contactId contact id * * @return Array array of contact_id of all related contacts. * @static */ static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action::ADD) { $contacts = array(); $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id'); require_once 'CRM/Member/BAO/MembershipType.php'; $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); require_once 'CRM/Contact/BAO/Relationship.php'; $relationships = array(); if (isset($membershipType['relationship_type_id'])) { $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::CURRENT); if ($action & CRM_Core_Action::UPDATE) { $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::PAST); $relationships = array_merge($relationships, $pastRelationships); } } if (!empty($relationships)) { require_once "CRM/Contact/BAO/RelationshipType.php"; // check for each contact relationships foreach ($relationships as $values) { //get details of the relationship type $relType = array('id' => $values['civicrm_relationship_type_id']); $relValues = array(); CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues); // 1. Check if contact and membership type relationship type are same // 2. Check if relationship direction is same or name_a_b = name_b_a if ($values['civicrm_relationship_type_id'] == $membershipType['relationship_type_id'] && ($values['rtype'] == $membershipType['relationship_direction'] || $relValues['name_a_b'] == $relValues['name_b_a'])) { // $values['status'] is going to have value for // current or past relationships. $contacts[$values['cid']] = $values['status']; } } } return $contacts; }
/** * Check the membership extended through relationship. * * @param int $membershipId * Membership id. * @param int $contactId * Contact id. * * @param int $action * * @return array * array of contact_id of all related contacts. */ public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action::ADD) { $contacts = array(); $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id'); $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); $relationships = array(); if (isset($membershipType['relationship_type_id'])) { $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::CURRENT); if ($action & CRM_Core_Action::UPDATE) { $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::PAST); $relationships = array_merge($relationships, $pastRelationships); } } if (!empty($relationships)) { // check for each contact relationships foreach ($relationships as $values) { //get details of the relationship type $relType = array('id' => $values['civicrm_relationship_type_id']); $relValues = array(); CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues); // Check if contact's relationship type exists in membership type $relTypeDirs = array(); $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']); $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']); $bidirectional = FALSE; foreach ($relTypeIds as $key => $value) { $relTypeDirs[] = $value . '_' . $relDirections[$key]; if (in_array($value, $relType) && $relValues['name_a_b'] == $relValues['name_b_a']) { $bidirectional = TRUE; break; } } $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype']; if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) { // $values['status'] is going to have value for // current or past relationships. $contacts[$values['cid']] = $values['status']; } } } // Sort by contact_id ascending ksort($contacts); return $contacts; }
/** * Get contact membership record. * * This api will return the membership records for the contacts * having membership based on the relationship with the direct members. * * @param Array $params key/value pairs for contact_id and some * options affecting the desired results; has legacy support * for just passing the contact_id itself as the argument * * @return Array of all found membership property values. * @access public * @todo needs some love - basically only a get for a given contact right now * {@getfields membership_get} */ function civicrm_api3_membership_get($params) { $contactID = $activeOnly = $membershipTypeId = $membershipType = NULL; $contactID = CRM_Utils_Array::value('contact_id', $params); if (is_array(CRM_Utils_Array::value('filters', $params)) && !empty($params['filters'])) { $activeOnly = CRM_Utils_Array::value('is_current', $params['filters'], FALSE); } $activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly); //@todo replace this by handling in API layer - we should have enough info to do this // between pseudoconstant & fk - see comments in format_params $membershipTypeId = CRM_Utils_Array::value('membership_type_id', $params); if (!$membershipTypeId) { $membershipType = CRM_Utils_Array::value('membership_type', $params); if ($membershipType) { $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipType, 'id', 'name'); } } if (CRM_Utils_Array::value('contact_id', $params)) { $membershipValues = _civicrm_api3_membership_get_customv2behaviour($params, $contactID, $membershipTypeId, $activeOnly); } else { //legacy behaviour only ever worked when contact_id passed in - use standard api function otherwise $membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE); } if (empty($membershipValues)) { # No results is NOT an error! return civicrm_api3_create_success($membershipValues, $params); } $relationships = array(); foreach ($membershipValues as $membershipId => $values) { // populate the membership type name for the membership type id $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); $membershipValues[$membershipId]['membership_name'] = $membershipType['name']; if (CRM_Utils_Array::value('relationship_type_id', $membershipType)) { $relationships[$membershipType['relationship_type_id']] = $membershipId; } // populating relationship type name. $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = CRM_Utils_Array::value('relationship_type_id', $membershipType); if ($relationshipType->find(TRUE)) { $membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b; } _civicrm_api3_custom_data_get($membershipValues[$membershipId], 'Membership', $membershipId, NULL, $values['membership_type_id']); } $members = $membershipValues; // populating contacts in members array based on their relationship with direct members. if (!empty($relationships)) { foreach ($relationships as $relTypeId => $membershipId) { // As members are not direct members, there should not be // membership id in the result array. unset($membershipValues[$membershipId]['id']); $relationship = new CRM_Contact_BAO_Relationship(); $relationship->contact_id_b = $contactID; $relationship->relationship_type_id = $relTypeId; if ($relationship->find()) { while ($relationship->fetch()) { clone $relationship; $membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a; $members[$membershipId]['related_contact_id'] = $relationship->contact_id_a; } } } } return civicrm_api3_create_success($members, $params, 'membership', 'get'); }