function processCaseTags() { $caseId = CRM_Utils_Type::escape($_POST['case_id'], 'Integer'); $tags = CRM_Utils_Type::escape($_POST['tag'], 'String'); if (empty($caseId)) { echo 'false'; CRM_Utils_System::civiExit(); } $tagIds = array(); if ($tags) { $tagIds = explode(',', $tags); } $params = array('entity_id' => $caseId, 'entity_table' => 'civicrm_case'); CRM_Core_BAO_EntityTag::del($params); foreach ($tagIds as $tagid) { if (is_numeric($tagid)) { $params['tag_id'] = $tagid; CRM_Core_BAO_EntityTag::add($params); } } $session = CRM_Core_Session::singleton(); $activityParams = array(); $activityParams['source_contact_id'] = $session->get('userID'); $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Change Case Tags', 'name'); $activityParams['activity_date_time'] = date('YmdHis'); $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'); $activityParams['case_id'] = $caseId; $activityParams['is_auto'] = 0; $activityParams['subject'] = 'Change Case Tags'; $activity = CRM_Activity_BAO_Activity::create($activityParams); $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId); CRM_Case_BAO_Case::processCaseActivity($caseParams); echo 'true'; CRM_Utils_System::civiExit(); }
protected function contactHasOneOfTags($contact_id, $tag_ids) { $isValid = false; $tags = CRM_Core_BAO_EntityTag::getTag($contact_id); foreach ($tag_ids as $tag_id) { if (in_array($tag_id, $tags)) { $isValid = true; break; } } return $isValid; }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ function postProcess() { $tagId = $this->controller->exportValue('RemoveFromTag', 'tag_id'); $this->_name = $this->_tags[$tagId]; list($total, $removed, $notRemoved) = CRM_Core_BAO_EntityTag::removeContactsFromTag($this->_contactIds, $tagId); $status = array('Contact(s) tagged as: ' . $this->_name, 'Total Selected Contact(s): ' . $total); if ($removed) { $status[] = 'Total Contact(s) to be removed from tag: ' . $removed; } if ($notRemoved) { $status[] = 'Total Contact(s) already removed: ' . $notRemoved; } CRM_Core_Session::setStatus($status); }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ function postProcess() { $tagId = $this->controller->exportValue('AddToTag', 'tag_id'); $this->_name = $this->_tags[$tagId]; list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addContactsToTag($this->_contactIds, $tagId); $status = array('Contact(s) tagged as: ' . $this->_name, 'Total Selected Contact(s): ' . $total); if ($added) { $status[] = 'Total Contact(s) tagged: ' . $added; } if ($notAdded) { $status[] = 'Total Contact(s) already tagged: ' . $notAdded; } CRM_Core_Session::setStatus($status); }
/** * Form submission of new/edit contact is processed. */ public function postProcess() { // check if dedupe button, if so return. $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->_dedupeButtonName) { return; } //get the submitted values in an array $params = $this->controller->exportValues($this->_name); $group = CRM_Utils_Array::value('group', $params); if (!empty($group) && is_array($group)) { unset($params['group']); foreach ($group as $key => $value) { $params['group'][$value] = 1; } } CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues); if (!empty($params['image_URL'])) { CRM_Contact_BAO_Contact::processImageParams($params); } if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) { $params['current_employer'] = $params['current_employer_id']; } // don't carry current_employer_id field, // since we don't want to directly update DAO object without // handling related business logic ( eg related membership ) if (isset($params['current_employer_id'])) { unset($params['current_employer_id']); } $params['contact_type'] = $this->_contactType; if (empty($params['contact_sub_type']) && $this->_isContactSubType) { $params['contact_sub_type'] = array($this->_contactSubType); } if ($this->_contactId) { $params['contact_id'] = $this->_contactId; } //make deceased date null when is_deceased = false if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) { $params['is_deceased'] = FALSE; $params['deceased_date'] = NULL; } if (isset($params['contact_id'])) { // process membership status for deceased contact $deceasedParams = array('contact_id' => CRM_Utils_Array::value('contact_id', $params), 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE), 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL)); $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams); } // action is taken depending upon the mode if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params); } else { CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params); } $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE); //CRM-5143 //if subtype is set, send subtype as extend to validate subtype customfield $customFieldExtends = CRM_Utils_Array::value('contact_sub_type', $params) ? $params['contact_sub_type'] : $params['contact_type']; $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_contactId, $customFieldExtends, TRUE); if ($this->_contactId && !empty($this->_oldSubtypes)) { CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId, $params['contact_type'], $this->_oldSubtypes, $params['contact_sub_type']); } if (array_key_exists('CommunicationPreferences', $this->_editOptions)) { // this is a chekbox, so mark false if we dont get a POST value $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE); } // process shared contact address. CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']); if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) { unset($params['group']); } if (!empty($params['contact_id']) && $this->_action & CRM_Core_Action::UPDATE && !empty($params['group'])) { // figure out which all groups are intended to be removed $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added'); if (is_array($contactGroupList)) { foreach ($contactGroupList as $key) { if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) { $params['group'][$key['group_id']] = -1; } } } } // parse street address, CRM-5450 $parseStatusMsg = NULL; if ($this->_parseStreetAddress) { $parseResult = self::parseAddress($params); $parseStatusMsg = self::parseAddressStatusMsg($parseResult); } // Allow un-setting of location info, CRM-5969 $params['updateBlankLocInfo'] = TRUE; $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE); // status message if ($this->_contactId) { $message = ts('%1 has been updated.', array(1 => $contact->display_name)); } else { $message = ts('%1 has been created.', array(1 => $contact->display_name)); } // set the contact ID $this->_contactId = $contact->id; if (array_key_exists('TagsAndGroups', $this->_editOptions)) { //add contact to tags CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']); //save free tags if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) { CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this); } } if (!empty($parseStatusMsg)) { $message .= "<br />{$parseStatusMsg}"; } if (!empty($updateMembershipMsg)) { $message .= "<br />{$updateMembershipMsg}"; } $session = CRM_Core_Session::singleton(); $session->setStatus($message, ts('Contact Saved'), 'success'); // add the recently viewed contact $recentOther = array(); if ($session->get('userID') == $contact->id || CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id); } if ($session->get('userID') != $this->_contactId && CRM_Core_Permission::check('delete contacts')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id); } CRM_Utils_Recent::add($contact->display_name, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $contact->display_name, $recentOther); // here we replace the user context with the url to view this contact $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->getButtonName('upload', 'new')) { $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType)); $resetStr = "reset=1&ct={$contact->contact_type}"; $resetStr .= count($contactSubTypes) == 1 ? "&cst=" . array_pop($contactSubTypes) : ''; $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr)); } else { $context = CRM_Utils_Request::retrieve('context', 'String', $this); $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this); //validate the qfKey $urlParams = 'reset=1&cid=' . $contact->id; if ($context) { $urlParams .= "&context={$context}"; } if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&key={$qfKey}"; } $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams)); } // now invoke the post hook if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact); } else { CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact); } }
/** * Test case for createProfileContact. */ public function testCreateProfileContact() { $fields = CRM_Contact_BAO_Contact::exportableFields('Individual'); //current employer field for individual $fields['organization_name'] = array('name' => 'organization_name', 'where' => 'civicrm_organization.organization_name', 'title' => 'Current Employer'); //get the common params $contactParams = $this->contactParams(); $unsetParams = array('location', 'privacy'); foreach ($unsetParams as $param) { unset($contactParams[$param]); } $profileParams = array('organization_name' => 'Yahoo', 'gender_id' => '2', 'prefix_id' => '3', 'suffix_id' => '2', 'city-Primary' => 'Newark', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '18.219023', 'geo_code_2-Primary' => '-105.00973', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.smith', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '303443689', 'phone-Primary-2' => '9833910234', 'postal_code-Primary' => '01903', 'postal_code_suffix-Primary' => '12345', 'state_province-Primary' => '1029', 'street_address-Primary' => 'Saint Helier St', 'supplemental_address_1-Primary' => 'Hallmark Ct', 'supplemental_address_2-Primary' => 'Jersey Village', 'user_unique_id' => '123456789', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('3' => '1', '4' => '1', '1' => '1')); $createParams = array_merge($contactParams, $profileParams); //create the contact using create profile contact. $contactId = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, NULL, NULL, NULL, NULL, TRUE); //get the parameters to compare. $params = $this->contactParams(); //check the values in DB. foreach ($params as $key => $val) { if (!is_array($params[$key])) { if ($key == 'contact_source') { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $params[$key], "Check for {$key} creation."); } else { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params[$key], "Check for {$key} creation."); } } } //check privacy options. foreach ($params['privacy'] as $key => $value) { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params['privacy'][$key], 'Check for do_not_email creation.'); } $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $profileParams['contact_type'], 'Check for contact type creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $profileParams['user_unique_id'], 'Check for user_unique_id creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $params['birth_date'], 'Check for birth_date creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $params['deceased_date'], 'Check for deceased_date creation.'); $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE)); $checkPrefComm = array(); foreach ($dbPrefComm as $key => $value) { if ($value) { $checkPrefComm[$value] = 1; } } $this->assertAttributesEquals($checkPrefComm, $params['preferred_communication_method']); //Now check DB for Address $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1); $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $profileParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $profileParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $profileParams), 'city' => CRM_Utils_Array::value('city-Primary', $profileParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $profileParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $profileParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $profileParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $profileParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $profileParams)); $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams); //Now check DB for Email $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $profileParams)); $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams); //Now check DB for IM $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $profileParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $profileParams)); $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams); //Now check DB for Phone $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1); $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $profileParams)); $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams); //Now check DB for Mobile $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2])); $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $profileParams)); $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams); //get the value of relationship $values = array(); $searchParams = array('contact_id' => $contactId); $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values); //Now check values of Relationship Count. $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count'); foreach ($values['relationship']['data'] as $key => $val) { //Now check values of Relationship organization. $this->assertEquals($profileParams['organization_name'], $val['name'], 'Check for organization'); //Now check values of Relationship type. $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type'); //delete the organization. $this->contactDelete(CRM_Utils_Array::value('cid', $val)); } //Now check values of tag ids. $tags = CRM_Core_BAO_EntityTag::getTag($contactId); foreach ($tags as $key => $val) { $tagIds[$key] = 1; } $this->assertAttributesEquals($profileParams['tag'], $tagIds); //update Contact mode $updateCParams = array('first_name' => 'john', 'last_name' => 'doe', 'contact_type' => 'Individual', 'middle_name' => 'abc', 'prefix_id' => 2, 'suffix_id' => 3, 'nick_name' => 'Nick Name Updated', 'job_title' => 'software Developer', 'gender_id' => 1, 'is_deceased' => 1, 'website' => array(1 => array('website_type_id' => 1, 'url' => 'http://civicrmUpdate.org')), 'contact_source' => 'test contact', 'external_identifier' => 111222333, 'preferred_mail_format' => 'Both', 'is_opt_out' => 0, 'legal_identifier' => '123123123123', 'image_URL' => 'http://imageupdate.com', 'deceased_date' => '1981-10-10', 'birth_date' => '1951-11-11', 'privacy' => array('do_not_phone' => 1, 'do_not_email' => 1), 'preferred_communication_method' => array('1' => 0, '2' => 1, '3' => 0, '4' => 1, '5' => 0)); $updatePfParams = array('organization_name' => 'Google', 'city-Primary' => 'Mumbai', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '31.694842', 'geo_code_2-Primary' => '-106.29998', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.doe', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '02115245336', 'phone-Primary-2' => '9766323895', 'postal_code-Primary' => '12345', 'postal_code_suffix-Primary' => '123', 'state_province-Primary' => '1004', 'street_address-Primary' => 'Oberoi Garden', 'supplemental_address_1-Primary' => 'A-wing:3037', 'supplemental_address_2-Primary' => 'Andhery', 'user_unique_id' => '1122334455', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('2' => '1', '5' => '1')); $createParams = array_merge($updateCParams, $updatePfParams); //create the contact using create profile contact. $contactID = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, $contactId, NULL, NULL, NULL, TRUE); //check the contact ids $this->assertEquals($contactId, $contactID, 'check for Contact ids'); //check the values in DB. foreach ($updateCParams as $key => $val) { if (!is_array($updateCParams[$key])) { if ($key == 'contact_source') { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $updateCParams[$key], "Check for {$key} creation."); } else { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams[$key], "Check for {$key} creation."); } } } //check privacy options. foreach ($updateCParams['privacy'] as $key => $value) { $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams['privacy'][$key], 'Check for do_not_email creation.'); } $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $updatePfParams['contact_type'], 'Check for contact type creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $updatePfParams['user_unique_id'], 'Check for user_unique_id creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $updateCParams['birth_date'], 'Check for birth_date creation.'); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $updateCParams['deceased_date'], 'Check for deceased_date creation.'); $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE)); $checkPrefComm = array(); foreach ($dbPrefComm as $key => $value) { if ($value) { $checkPrefComm[$value] = 1; } } $this->assertAttributesEquals($checkPrefComm, $updateCParams['preferred_communication_method']); //Now check DB for Address $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1); $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $updatePfParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $updatePfParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $updatePfParams), 'city' => CRM_Utils_Array::value('city-Primary', $updatePfParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $updatePfParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $updatePfParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $updatePfParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $updatePfParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $updatePfParams)); $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams); //Now check DB for Email $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $updatePfParams)); $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams); //Now check DB for IM $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $updatePfParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $updatePfParams)); $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams); //Now check DB for Phone $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1); $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $updatePfParams)); $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams); //Now check DB for Mobile $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2])); $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $updatePfParams)); $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams); //get the value of relationship $values = array(); $searchParams = array('contact_id' => $contactId); $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values); //Now check values of Relationship Count. $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count'); foreach ($values['relationship']['data'] as $key => $val) { //Now check values of Relationship organization. $this->assertEquals($updatePfParams['organization_name'], $val['name'], 'Check for organization'); //Now check values of Relationship type. $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type'); //delete the organization. $this->contactDelete(CRM_Utils_Array::value('cid', $val)); } //Now check values of tag ids. $tags = CRM_Core_BAO_EntityTag::getTag($contactId); foreach ($tags as $key => $val) { $tagIds[$key] = 1; } $this->assertAttributesEquals($updatePfParams['tag'], $tagIds); //cleanup DB by deleting the contact $this->contactDelete($contactId); }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { //get the submitted values in an array $params = $this->controller->exportValues($this->_name); $contactTags = $tagList = array(); // check if contact tags exists if (!empty($params['tag'])) { $contactTags = $params['tag']; } // check if tags are selected from taglists if (!empty($params['contact_taglist'])) { foreach ($params['contact_taglist'] as $val) { if ($val) { if (is_numeric($val)) { $tagList[$val] = 1; } else { $tagIDs = explode(',', $val); if (!empty($tagIDs)) { foreach ($tagIDs as $tagID) { if (is_numeric($tagID)) { $tagList[$tagID] = 1; } } } } } } } $tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_contact', FALSE, TRUE); foreach ($tagSets as $key => $value) { $this->_tags[$key] = $value['name']; } // merge contact and taglist tags $allTags = CRM_Utils_Array::crmArrayMerge($contactTags, $tagList); $this->_name = array(); foreach ($allTags as $key => $dnc) { $this->_name[] = $this->_tags[$key]; list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_contactIds, $key); $status = array(ts('%count contact tagged', array('count' => $added, 'plural' => '%count contacts tagged'))); if ($notAdded) { $status[] = ts('%count contact already had this tag', array('count' => $notAdded, 'plural' => '%count contacts already had this tag')); } $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>'; CRM_Core_Session::setStatus($status, ts("Added Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0)); } }
/** * Process the mapped fields and map it into the uploaded file * preview the file and extract some summary statistics * * @return void * @access public */ public function postProcessOld() { $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress'); $invalidRowCount = $this->get('invalidRowCount'); $conflictRowCount = $this->get('conflictRowCount'); $onDuplicate = $this->get('onDuplicate'); $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName'); $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc'); $groups = $this->controller->exportValue($this->_name, 'groups'); $allGroups = $this->get('groups'); $newTagName = $this->controller->exportValue($this->_name, 'newTagName'); $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc'); $tag = $this->controller->exportValue($this->_name, 'tag'); $allTags = $this->get('tag'); $mapper = $this->controller->exportValue('MapField', 'mapper'); $mapperKeys = array(); $mapperLocTypes = array(); $mapperPhoneTypes = array(); $mapperRelated = array(); $mapperRelatedContactType = array(); $mapperRelatedContactDetails = array(); $mapperRelatedContactLocType = array(); $mapperRelatedContactPhoneType = array(); foreach ($mapper as $key => $value) { $mapperKeys[$key] = $mapper[$key][0]; if (is_numeric($mapper[$key][1])) { $mapperLocTypes[$key] = $mapper[$key][1]; } else { $mapperLocTypes[$key] = NULL; } if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') { $mapperPhoneTypes[$key] = $mapper[$key][2]; } else { $mapperPhoneTypes[$key] = NULL; } list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $fieldName = "contact_type_{$second}"; $mapperRelatedContactType[$key] = $relationType->{$fieldName}; $mapperRelated[$key] = $mapper[$key][0]; $mapperRelatedContactDetails[$key] = $mapper[$key][1]; $mapperRelatedContactLocType[$key] = $mapper[$key][2]; $mapperRelatedContactPhoneType[$key] = $mapper[$key][3]; } else { $mapperRelated[$key] = NULL; $mapperRelatedContactType[$key] = NULL; $mapperRelatedContactDetails[$key] = NULL; $mapperRelatedContactLocType[$key] = NULL; $mapperRelatedContactPhoneType[$key] = NULL; } } $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType); $mapFields = $this->get('fields'); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); foreach ($mapper as $key => $value) { $header = array(); list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $header[] = $relationType->name_a_b; $header[] = ucwords(str_replace("_", " ", $mapper[$key][1])); if (isset($mapper[$key][2])) { $header[] = $locationTypes[$mapper[$key][2]]; } if (isset($mapper[$key][3])) { $header[] = $phoneTypes[$mapper[$key][3]]; } } else { if (isset($mapFields[$mapper[$key][0]])) { $header[] = $mapFields[$mapper[$key][0]]; if (isset($mapper[$key][1])) { $header[] = $locationTypes[$mapper[$key][1]]; } if (isset($mapper[$key][2])) { $header[] = $phoneTypes[$mapper[$key][2]]; } } } $mapperFields[] = implode(' - ', $header); } $tableName = $this->get('importTableName'); //print "Running parser on table: $tableName<br/>"; $parser->run($tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->get('contactType'), $this->get('primaryKeyName'), $this->get('statusFieldName'), $onDuplicate, $this->get('statusID'), $this->get('totalRowCount'), $doGeocodeAddress, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe')); // add the new contacts to selected groups $contactIds =& $parser->getImportedContacts(); // add the new related contacts to selected groups $relatedContactIds =& $parser->getRelatedImportedContacts(); $this->set('relatedCount', count($relatedContactIds)); $newGroupId = NULL; //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {" if ($newGroupName) { /* Create a new group */ $gParams = array('name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE); $group = CRM_Contact_BAO_Group::create($gParams); $groups[] = $newGroupId = $group->id; } if (is_array($groups)) { $groupAdditions = array(); foreach ($groups as $groupId) { $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); if (!empty($relatedContactIds)) { $addRelCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId); } $totalCount = $addCount[1] + $addRelCount[1]; if ($groupId == $newGroupId) { $name = $newGroupName; $new = TRUE; } else { $name = $allGroups[$groupId]; $new = FALSE; } $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2] + $addRelCount[2], 'new' => $new); } $this->set('groupAdditions', $groupAdditions); } $newTagId = NULL; if ($newTagName) { /* Create a new Tag */ $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_active' => TRUE); $id = array(); $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id); $tag[$addedTag->id] = 1; } //add Tag to Import if (is_array($tag)) { $tagAdditions = array(); foreach ($tag as $tagId => $val) { $addTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId); if (!empty($relatedContactIds)) { $addRelTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId); } $totalTagCount = $addTagCount[1] + $addRelTagCount[1]; if ($tagId == $addedTag->id) { $tagName = $newTagName; $new = TRUE; } else { $tagName = $allTags[$tagId]; $new = FALSE; } $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2] + $addRelTagCount[2], 'new' => $new); } $this->set('tagAdditions', $tagAdditions); } // add all the necessary variables to the form $parser->set($this, CRM_Import_Parser::MODE_IMPORT); // check if there is any error occured $errorStack = CRM_Core_Error::singleton(); $errors = $errorStack->getErrors(); $errorMessage = array(); if (is_array($errors)) { foreach ($errors as $key => $value) { $errorMessage[] = $value['message']; } // there is no fileName since this is a sql import // so fudge it $config = CRM_Core_Config::singleton(); $errorFile = $config->uploadDir . "sqlImport.error.log"; if ($fd = fopen($errorFile, 'w')) { fwrite($fd, implode('\\n', $errorMessage)); } fclose($fd); $this->set('errorFile', $errorFile); $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams)); $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); } }
/** * * @param <type> $params * @param <type> $op * * @return <type> */ function civicrm_entity_tag_common(&$params, $op = 'add') { $entityIDs = array(); $tagsIDs = array(); $entityTable = 'civicrm_contact'; if (is_array($params)) { foreach ($params as $n => $v) { if (substr($n, 0, 10) == 'contact_id' || substr($n, 0, 9) == 'entity_id') { $entityIDs[] = $v; } elseif (substr($n, 0, 6) == 'tag_id') { $tagIDs[] = $v; } elseif (substr($n, 0, 12) == 'entity_table') { $entityTable = $v; } } } if (empty($entityIDs)) { return civicrm_create_error(ts('contact_id is a required field')); } if (empty($tagIDs)) { return civicrm_create_error(ts('tag_id is a required field')); } require_once 'CRM/Core/BAO/EntityTag.php'; $values = array('is_error' => 0); if ($op == 'add') { $values['total_count'] = $values['added'] = $values['not_added'] = 0; foreach ($tagIDs as $tagID) { list($te, $a, $na) = CRM_Core_BAO_EntityTag::addEntitiesToTag($entityIDs, $tagID, $entityTable); $values['total_count'] += $te; $values['added'] += $a; $values['not_added'] += $na; } } else { $values['total_count'] = $values['removed'] = $values['not_removed'] = 0; foreach ($tagIDs as $tagID) { list($te, $r, $nr) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($entityIDs, $tagID, $entityTable); $values['total_count'] += $te; $values['removed'] += $r; $values['not_removed'] += $nr; } } return $values; }
/** * Given a contact id and a field set, return the values from the db * for this contact * * @param int $cid * @param array $fields * The profile fields of interest. * @param array $values * The values for the above fields. * @param bool $searchable * Searchable or not. * @param array $componentWhere * Component condition. * @param bool $absolute * Return urls in absolute form (useful when sending an email). * @param null $additionalWhereClause */ public static function getValues($cid, &$fields, &$values, $searchable = TRUE, $componentWhere = NULL, $absolute = FALSE, $additionalWhereClause = NULL) { if (empty($cid) && empty($componentWhere)) { return NULL; } // get the contact details (hier) $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); $params = $cid ? array(array('contact_id', '=', $cid, 0, 0)) : array(); // add conditions specified by components. eg partcipant_id etc if (!empty($componentWhere)) { $params = array_merge($params, $componentWhere); } $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $details = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $additionalWhereClause); if (!$details->fetch()) { return; } $query->convertToPseudoNames($details); $config = CRM_Core_Config::singleton(); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $multipleFields = array('url'); //start of code to set the default values foreach ($fields as $name => $field) { // fix for CRM-3962 if ($name == 'id') { $name = 'contact_id'; } // skip fields that should not be displayed separately if (!empty($field['skipDisplay'])) { continue; } // Create a unique, non-empty index for each field. $index = $field['title']; if ($index === '') { $index = ' '; } while (array_key_exists($index, $values)) { $index .= ' '; } $params[$index] = $values[$index] = ''; $customFieldName = NULL; // hack for CRM-665 if (isset($details->{$name}) || $name == 'group' || $name == 'tag') { // to handle gender / suffix / prefix if (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix'))) { $params[$index] = $details->{$name}; $values[$index] = $details->{$name}; } elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)) { $dname = $name . '_display'; $values[$index] = $details->{$dname}; $name = $name . '_id'; $params[$index] = $details->{$name}; } elseif (in_array($name, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$name}; $idx = $name . '_id'; $params[$index] = $details->{$idx}; } elseif ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $compref = array(); $pref = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}); foreach ($pref as $k) { if ($k) { $compref[] = $communicationFields[$k]; } } $params[$index] = $details->{$name}; $values[$index] = implode(',', $compref); } elseif ($name === 'preferred_language') { $params[$index] = $details->{$name}; $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $details->{$name}); } elseif ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', NULL, FALSE, TRUE); $title = $ids = array(); foreach ($groups as $g) { // CRM-8362: User and User Admin visibility groups should be included in display if user has // VIEW permission on that group $groupPerm = CRM_Contact_BAO_Group::checkPermission($g['group_id'], $g['title']); if ($g['visibility'] != 'User and User Admin Only' || CRM_Utils_Array::key(CRM_Core_Permission::VIEW, $groupPerm)) { $title[] = $g['title']; if ($g['visibility'] == 'Public Pages') { $ids[] = $g['group_id']; } } } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $ids); } elseif ($name == 'tag') { $entityTags = CRM_Core_BAO_EntityTag::getTag($cid); $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); $title = array(); foreach ($entityTags as $tagId) { $title[] = $allTags[$tagId]; } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $entityTags); } elseif ($name == 'activity_status_id') { $activityStatus = CRM_Core_PseudoConstant::activityStatus(); $values[$index] = $activityStatus[$details->{$name}]; $params[$index] = $details->{$name}; } elseif ($name == 'activity_date_time') { $values[$index] = CRM_Utils_Date::customFormat($details->{$name}); $params[$index] = $details->{$name}; } elseif ($name == 'contact_sub_type') { $contactSubTypeNames = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}); if (!empty($contactSubTypeNames)) { $contactSubTypeLabels = array(); // get all contact subtypes $allContactSubTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); // build contact subtype labels array foreach ($contactSubTypeNames as $cstName) { if ($cstName) { $contactSubTypeLabels[] = $allContactSubTypes[$cstName]['label']; } } $values[$index] = implode(',', $contactSubTypeLabels); } $params[$index] = $details->{$name}; } else { if (substr($name, 0, 7) === 'do_not_' || substr($name, 0, 3) === 'is_') { if ($details->{$name}) { $values[$index] = '[ x ]'; } } else { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $htmlType = $field['html_type']; // field_type is only set when we are retrieving profile values // when sending email, we call the same function to get custom field // values etc, i.e. emulating a profile $fieldType = CRM_Utils_Array::value('field_type', $field); if ($htmlType == 'File') { $entityId = $cid; if (!$cid && $fieldType == 'Activity' && !empty($componentWhere[0][2])) { $entityId = $componentWhere[0][2]; } $fileURL = CRM_Core_BAO_CustomField::getFileURL($entityId, $cfID, NULL, $absolute, $additionalWhereClause); $params[$index] = $values[$index] = $fileURL['file_url']; } else { $customVal = NULL; if (isset($dao) && property_exists($dao, 'data_type') && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) { $customVal = (int) $details->{$name}; } elseif (isset($dao) && property_exists($dao, 'data_type') && $dao->data_type == 'Float') { $customVal = (double) $details->{$name}; } elseif (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) { $customVal = $details->{$name}; } //CRM-4582 if (CRM_Utils_System::isNull($customVal)) { continue; } $params[$index] = $customVal; $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); if ($field['data_type'] == 'ContactReference') { $params[$index] = $values[$index]; } if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) { $customFieldName = "{$name}_from"; } } } elseif ($name == 'image_URL') { list($width, $height) = getimagesize(CRM_Utils_String::unstupifyUrl($details->{$name})); list($thumbWidth, $thumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($width, $height); $image_URL = '<img src="' . $details->{$name} . '" height= ' . $thumbHeight . ' width= ' . $thumbWidth . ' />'; $values[$index] = "<a href='#' onclick='contactImagePopUp(\"{$details->{$name}}\", {$width}, {$height});'>{$image_URL}</a>"; } elseif (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) { $values[$index] = CRM_Utils_Date::customFormat($details->{$name}); $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name}); } else { $dao = ''; if ($index == 'Campaign') { $dao = 'CRM_Campaign_DAO_Campaign'; } elseif ($index == 'Contribution Page') { $dao = 'CRM_Contribute_DAO_ContributionPage'; } if ($dao) { $value = CRM_Core_DAO::getFieldValue($dao, $details->{$name}, 'title'); } else { $value = $details->{$name}; } $values[$index] = $value; } } } } elseif (strpos($name, '-') !== FALSE) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3); if (!in_array($fieldName, $multipleFields)) { if ($id == 'Primary') { // fix for CRM-1543 // not sure why we'd every use Primary location type id // we need to fix the source if we are using it // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid ); $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); } if (!$locationTypeName) { continue; } $detailName = "{$locationTypeName}-{$fieldName}"; $detailName = str_replace(' ', '_', $detailName); if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) { if ($type) { $detailName .= "-{$type}"; } } if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$detailName}; $idx = $detailName . '_id'; $params[$index] = $details->{$idx}; } elseif ($fieldName == 'im') { $providerId = $detailName . '-provider_id'; if (isset($imProviders[$details->{$providerId}])) { $values[$index] = $details->{$detailName} . " (" . $imProviders[$details->{$providerId}] . ")"; } else { $values[$index] = $details->{$detailName}; } $params[$index] = $details->{$detailName}; } elseif ($fieldName == 'phone') { $phoneExtField = str_replace('phone', 'phone_ext', $detailName); if (isset($details->{$phoneExtField})) { $values[$index] = $details->{$detailName} . " (" . $details->{$phoneExtField} . ")"; } else { $values[$index] = $details->{$detailName}; } $params[$index] = $details->{$detailName}; } else { $values[$index] = $params[$index] = $details->{$detailName}; } } else { $detailName = "website-{$id}-{$fieldName}"; $url = CRM_Utils_System::fixURL($details->{$detailName}); if ($details->{$detailName}) { $websiteTypeId = "website-{$id}-website_type_id"; $websiteType = $websiteTypes[$details->{$websiteTypeId}]; $values[$index] = "<a href=\"{$url}\">{$details->{$detailName}} ( {$websiteType} )</a>"; } else { $values[$index] = ''; } } } if (CRM_Utils_Array::value('visibility', $field) == 'Public Pages and Listings' && CRM_Core_Permission::check('profile listings and forms')) { if (CRM_Utils_System::isNull($params[$index])) { $params[$index] = $values[$index]; } if (!isset($params[$index])) { continue; } if (!$customFieldName) { $fieldName = $field['name']; } else { $fieldName = $customFieldName; } $url = NULL; if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) { $htmlType = $field['html_type']; if ($htmlType == 'Link') { $url = $params[$index]; } elseif (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) { $valSeperator = CRM_Core_DAO::VALUE_SEPARATOR; $selectedOptions = explode($valSeperator, $params[$index]); foreach ($selectedOptions as $key => $multiOption) { if ($multiOption) { $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($multiOption)); } } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } if ($url && !empty($values[$index]) && $searchable) { if (is_array($url) && !empty($url)) { $links = array(); $eachMultiValue = explode(', ', $values[$index]); foreach ($eachMultiValue as $key => $valueLabel) { $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>'; } $values[$index] = implode(', ', $links); } else { $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>'; } } } } }
/** * Process the mapped fields and map it into the uploaded file * preview the file and extract some summary statistics * * @return void * @access public */ function postProcess() { $fileName = $this->controller->exportValue('UploadFile', 'uploadFile'); $skipColumnHeader = $this->controller->exportValue('UploadFile', 'skipColumnHeader'); $invalidRowCount = $this->get('invalidRowCount'); $conflictRowCount = $this->get('conflictRowCount'); $onDuplicate = $this->get('onDuplicate'); $newGroup = $this->controller->exportValue($this->_name, 'newGroup'); $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName'); $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc'); $groups = $this->controller->exportValue($this->_name, 'groups'); $allGroups = $this->get('groups'); $tagForContact = $this->controller->exportValue($this->_name, 'tag'); $allTags = $this->get('tag'); $seperator = ','; $mapper = $this->controller->exportValue('MapField', 'mapper'); $mapperKeys = array(); $mapperLocTypes = array(); $mapperPhoneTypes = array(); $mapperRelated = array(); $mapperRelatedContactType = array(); $mapperRelatedContactDetails = array(); $mapperRelatedContactLocType = array(); $mapperRelatedContactPhoneType = array(); foreach ($mapper as $key => $value) { $mapperKeys[$key] = $mapper[$key][0]; if (is_numeric($mapper[$key][1])) { $mapperLocTypes[$key] = $mapper[$key][1]; } else { $mapperLocTypes[$key] = null; } if (!is_numeric($mapper[$key][2])) { $mapperPhoneTypes[$key] = $mapper[$key][2]; } else { $mapperPhoneTypes[$key] = null; } list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType =& new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(true); eval('$mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';'); $mapperRelated[$key] = $mapper[$key][0]; $mapperRelatedContactDetails[$key] = $mapper[$key][1]; $mapperRelatedContactLocType[$key] = $mapper[$key][2]; $mapperRelatedContactPhoneType[$key] = $mapper[$key][3]; } else { $mapperRelated[$key] = null; $mapperRelatedContactType[$key] = null; $mapperRelatedContactDetails[$key] = null; $mapperRelatedContactLocType[$key] = null; $mapperRelatedContactPhoneType[$key] = null; } } $parser =& new CRM_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType); $mapFields = $this->get('fields'); $locationTypes = CRM_Core_PseudoConstant::locationType(); $phoneTypes = CRM_Core_SelectValues::phoneType(); foreach ($mapper as $key => $value) { $header = array(); list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType =& new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(true); $header[] = $relationType->name_a_b; $header[] = ucwords(str_replace("_", " ", $mapper[$key][1])); if (isset($mapper[$key][2])) { $header[] = $locationTypes[$mapper[$key][2]]; } if (isset($mapper[$key][3])) { $header[] = $phoneTypes[$mapper[$key][3]]; } } else { if (isset($mapFields[$mapper[$key][0]])) { $header[] = $mapFields[$mapper[$key][0]]; if (isset($mapper[$key][1])) { $header[] = $locationTypes[$mapper[$key][1]]; } if (isset($mapper[$key][2])) { $header[] = $phoneTypes[$mapper[$key][2]]; } } } $mapperFields[] = implode(' - ', $header); } $parser->run($fileName, $seperator, $mapperFields, $skipColumnHeader, CRM_IMPORT_PARSER_MODE_IMPORT, $this->get('contactType'), $onDuplicate); // add the new contacts to selected groups $contactIds =& $parser->getImportedContacts(); // add the new related contacts to selected groups $relatedContactIds =& $parser->getRelatedImportedContacts(); $this->set('relatedCount', count($relatedContactIds)); $newGroupId = null; //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {" if ($newGroupName) { /* Create a new group */ $gParams = array('domain_id' => CRM_Core_Config::domainID(), 'name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => true); $group =& CRM_Contact_BAO_Group::create($gParams); $groups[] = $newGroupId = $group->id; } if (is_array($groups)) { $groupAdditions = array(); foreach ($groups as $groupId) { $addCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); if (!empty($relatedContactIds)) { $addRelCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId); } $totalCount = $addCount[1] + $addRelCount[1]; if ($groupId == $newGroupId) { $name = $newGroupName; $new = true; } else { $name = $allGroups[$groupId]; $new = false; } $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2], 'new' => $new); } $this->set('groupAdditions', $groupAdditions); } if (is_array($tagForContact)) { $tagAddition = array(); require_once "CRM/Core/BAO/EntityTag.php"; foreach ($tagForContact as $tagId => $selected) { $taggedContacts = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId); $tagName = $allTags[$tagId]; $tagAdditions[] = array('name' => $tagName, 'added' => $taggedContacts[1], 'notAdded' => $taggedContacts[2]); } $this->set('tagAdditions', $tagAdditions); } // add all the necessary variables to the form $parser->set($this, CRM_IMPORT_PARSER_MODE_IMPORT); // check if there is any error occured $errorStack =& CRM_Core_Error::singleton(); $errors = $errorStack->getErrors(); $errorMessage = array(); $config =& CRM_Core_Config::singleton(); if (is_array($errors)) { foreach ($errors as $key => $value) { $errorMessage[] = $value['message']; } $errorFile = $fileName . '.error.log'; if ($fd = fopen($errorFile, 'w')) { fwrite($fd, implode('\\n', $errorMessage)); } fclose($fd); $this->set('errorFile', $errorFile); $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=1')); $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=2')); $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=4')); } }
/** * set defaults for relevant form elements * * @param int $id the contact id * @param array $defaults the defaults array to store the values in * @param int $type what components are we interested in * @param string $fieldName this is used in batch profile(i.e to build multiple blocks) * * @return void * @access public * @static */ static function setDefaults($id, &$defaults, $type = CRM_Contact_Form_Edit_TagsandGroups::ALL, $fieldName = null) { $type = (int) $type; if ($type & self::GROUP) { $fName = 'group'; if ($fieldName) { $fName = $fieldName; } require_once 'CRM/Contact/BAO/GroupContact.php'; $contactGroup =& CRM_Contact_BAO_GroupContact::getContactGroup($id, 'Added', null, false, true); if ($contactGroup) { foreach ($contactGroup as $group) { $defaults[$fName . "[" . $group['group_id'] . "]"] = 1; } } } if ($type & self::TAG) { $fName = 'tag'; if ($fieldName) { $fName = $fieldName; } require_once 'CRM/Core/BAO/EntityTag.php'; $contactTag =& CRM_Core_BAO_EntityTag::getTag($id); if ($contactTag) { foreach ($contactTag as $tag) { $defaults[$fName . "[" . $tag . "]"] = 1; } } } }
/** * Takes an associative array and creates tag entity record for all tag entities. * * @param array $params * (reference) an assoc array of name/value pairs. * @param $entityTable * @param int $entityID * * @return void */ public static function create(&$params, $entityTable, $entityID) { // get categories for the entity id $entityTag = CRM_Core_BAO_EntityTag::getTag($entityID, $entityTable); // get the list of all the categories $allTag = CRM_Core_BAO_Tag::getTags($entityTable); // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input if (!is_array($params)) { $params = array(); } // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input if (!is_array($entityTag)) { $entityTag = array(); } // check which values has to be inserted/deleted for contact foreach ($allTag as $key => $varValue) { $tagParams['entity_table'] = $entityTable; $tagParams['entity_id'] = $entityID; $tagParams['tag_id'] = $key; if (array_key_exists($key, $params) && !array_key_exists($key, $entityTag)) { // insert a new record CRM_Core_BAO_EntityTag::add($tagParams); } elseif (!array_key_exists($key, $params) && array_key_exists($key, $entityTag)) { // delete a record for existing contact CRM_Core_BAO_EntityTag::del($tagParams); } } }
static function mergeTags() { $tagAId = CRM_Utils_Type::escape($_POST['fromId'], 'Integer'); $tagBId = CRM_Utils_Type::escape($_POST['toId'], 'Integer'); $result = CRM_Core_BAO_EntityTag::mergeTags($tagAId, $tagBId); if (!empty($result['tagB_used_for'])) { $usedFor = CRM_Core_OptionGroup::values('tag_used_for'); foreach ($result['tagB_used_for'] as &$val) { $val = $usedFor[$val]; } $result['tagB_used_for'] = implode(', ', $result['tagB_used_for']); } $result['message'] = ts('"%1" has been merged with "%2". All records previously tagged "%1" are now tagged "%2".', array(1 => $result['tagA'], 2 => $result['tagB'])); CRM_Utils_JSON::output($result); }
/** * View summary details of a contact. */ public function view() { // Add js for tabs, in-place editing, and jstree for tags CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Page/View/Summary.js', 2, 'html-header')->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header')->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE)->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header')->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')->addSetting(array('summaryPrint' => array('mode' => $this->_print), 'tabSettings' => array('active' => CRM_Utils_Request::retrieve('selectedChild', 'String', $this, FALSE, 'summary')))); $this->assign('summaryPrint', $this->_print); $session = CRM_Core_Session::singleton(); $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $this->_contactId); $session->pushUserContext($url); $params = array(); $defaults = array(); $ids = array(); $params['id'] = $params['contact_id'] = $this->_contactId; $params['noRelationships'] = $params['noNotes'] = $params['noGroups'] = TRUE; $contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults, TRUE); // Let summary page know if outbound mail is disabled so email links can be built conditionally $mailingBackend = Civi::settings()->get('mailing_backend'); $this->assign('mailingOutboundOption', $mailingBackend['outBound_option']); $communicationType = array('phone' => array('type' => 'phoneType', 'id' => 'phone_type', 'daoName' => 'CRM_Core_DAO_Phone', 'fieldName' => 'phone_type_id'), 'im' => array('type' => 'IMProvider', 'id' => 'provider', 'daoName' => 'CRM_Core_DAO_IM', 'fieldName' => 'provider_id'), 'website' => array('type' => 'websiteType', 'id' => 'website_type', 'daoName' => 'CRM_Core_DAO_Website', 'fieldName' => 'website_type_id'), 'address' => array('skip' => TRUE, 'customData' => 1), 'email' => array('skip' => TRUE), 'openid' => array('skip' => TRUE)); foreach ($communicationType as $key => $value) { if (!empty($defaults[$key])) { foreach ($defaults[$key] as &$val) { CRM_Utils_Array::lookupValue($val, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'display_name')), FALSE); if (empty($value['skip'])) { $daoName = $value['daoName']; $pseudoConst = $daoName::buildOptions($value['fieldName'], 'get'); CRM_Utils_Array::lookupValue($val, $value['id'], $pseudoConst, FALSE); } } if (isset($value['customData'])) { foreach ($defaults[$key] as $blockId => $blockVal) { $idValue = $blockVal['id']; if ($key == 'address') { if (!empty($blockVal['master_id'])) { $idValue = $blockVal['master_id']; } } $groupTree = CRM_Core_BAO_CustomGroup::getTree(ucfirst($key), $this, $idValue); // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var. $defaults[$key][$blockId]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_"); } // reset template variable since that won't be of any use, and could be misleading $this->assign("dnc_viewCustomData", NULL); } } } if (!empty($defaults['gender_id'])) { $defaults['gender_display'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'gender_id', $defaults['gender_id']); } $communicationStyle = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'); if (!empty($communicationStyle)) { if (!empty($defaults['communication_style_id'])) { $defaults['communication_style_display'] = $communicationStyle[CRM_Utils_Array::value('communication_style_id', $defaults)]; } else { // Make sure the field is displayed as long as it is active, even if it is unset for this contact. $defaults['communication_style_display'] = ''; } } // to make contact type label available in the template - $contactType = array_key_exists('contact_sub_type', $defaults) ? $defaults['contact_sub_type'] : $defaults['contact_type']; $defaults['contact_type_label'] = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $contactType, ', '); // get contact tags $contactTags = CRM_Core_BAO_EntityTag::getContactTags($this->_contactId); if (!empty($contactTags)) { $defaults['contactTag'] = implode(', ', $contactTags); } $defaults['privacy_values'] = CRM_Core_SelectValues::privacy(); //Show blocks only if they are visible in edit form $this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_edit_options'); foreach ($this->_editOptions as $blockName => $value) { $varName = '_show' . $blockName; $this->{$varName} = $value; $this->assign(substr($varName, 1), $this->{$varName}); } // get contact name of shared contact names $sharedAddresses = array(); $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']); foreach ($defaults['address'] as $key => $addressValue) { if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']); } } $this->assign('sharedAddresses', $sharedAddresses); //get the current employer name if (CRM_Utils_Array::value('contact_type', $defaults) == 'Individual') { if ($contact->employer_id && $contact->organization_name) { $defaults['current_employer'] = $contact->organization_name; $defaults['current_employer_id'] = $contact->employer_id; } //for birthdate format with respect to birth format set $this->assign('birthDateViewFormat', CRM_Utils_Array::value('qfMapping', CRM_Utils_Date::checkBirthDateFormat())); } $defaults['external_identifier'] = $contact->external_identifier; $this->assign($defaults); // FIXME: when we sort out TZ isssues with DATETIME/TIMESTAMP, we can skip next query // also assign the last modifed details $lastModified = CRM_Core_BAO_Log::lastModified($this->_contactId, 'civicrm_contact'); $this->assign_by_ref('lastModified', $lastModified); $allTabs = array(); $weight = 10; $this->_viewOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_view_options', TRUE); // show the tabs only if user has generic access to CiviCRM $accessCiviCRM = CRM_Core_Permission::check('access CiviCRM'); $changeLog = $this->_viewOptions['log']; $this->assign_by_ref('changeLog', $changeLog); $components = CRM_Core_Component::getEnabledComponents(); foreach ($components as $name => $component) { if (!empty($this->_viewOptions[$name]) && CRM_Core_Permission::access($component->name)) { $elem = $component->registerTab(); // FIXME: not very elegant, probably needs better approach // allow explicit id, if not defined, use keyword instead if (array_key_exists('id', $elem)) { $i = $elem['id']; } else { $i = $component->getKeyword(); } $u = $elem['url']; //appending isTest to url for test soft credit CRM-3891. //FIXME: hack ajax url. $q = "reset=1&force=1&cid={$this->_contactId}"; if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) { $q .= "&isTest=1"; } $allTabs[] = array('id' => $i, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$u}", $q), 'title' => $elem['title'], 'weight' => $elem['weight'], 'count' => CRM_Contact_BAO_Contact::getCountComponent($u, $this->_contactId), 'class' => 'livePage'); // make sure to get maximum weight, rest of tabs go after // FIXME: not very elegant again if ($weight < $elem['weight']) { $weight = $elem['weight']; } } } $rest = array('activity' => array('title' => ts('Activities'), 'class' => 'livePage'), 'rel' => array('title' => ts('Relationships'), 'class' => 'livePage'), 'group' => array('title' => ts('Groups'), 'class' => 'ajaxForm'), 'note' => array('title' => ts('Notes'), 'class' => 'livePage'), 'tag' => array('title' => ts('Tags')), 'log' => array('title' => ts('Change Log'))); foreach ($rest as $k => $v) { if ($accessCiviCRM && !empty($this->_viewOptions[$k])) { $allTabs[] = $v + array('id' => $k, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$k}", "reset=1&cid={$this->_contactId}"), 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($k, $this->_contactId)); $weight += 10; } } // now add all the custom tabs $entityType = $this->get('contactType'); $activeGroups = CRM_Core_BAO_CustomGroup::getActiveGroups($entityType, 'civicrm/contact/view/cd', $this->_contactId); foreach ($activeGroups as $group) { $id = "custom_{$group['id']}"; $allTabs[] = array('id' => $id, 'url' => CRM_Utils_System::url($group['path'], $group['query'] . "&selectedChild={$id}"), 'title' => $group['title'], 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($id, $this->_contactId, $group['table_name']), 'hideCount' => !$group['is_multiple'], 'class' => 'livePage'); $weight += 10; } $context = array('contact_id' => $this->_contactId); // see if any other modules want to add any tabs CRM_Utils_Hook::tabs($allTabs, $this->_contactId); CRM_Utils_Hook::tabset('civicrm/contact/view', $allTabs, $context); $allTabs[] = array('id' => 'summary', 'url' => '#contact-summary', 'title' => ts('Summary'), 'weight' => 0); // now sort the tabs based on weight usort($allTabs, array('CRM_Utils_Sort', 'cmpFunc')); $this->assign('allTabs', $allTabs); // hook for contact summary // ignored but needed to prevent warnings $contentPlacement = CRM_Utils_Hook::SUMMARY_BELOW; CRM_Utils_Hook::summary($this->_contactId, $content, $contentPlacement); if ($content) { $this->assign_by_ref('hookContent', $content); $this->assign('hookContentPlacement', $contentPlacement); } }
/** * Set defaults for relevant form elements. * * @param int $id * The contact id. * @param array $defaults * The defaults array to store the values in. * @param int $type * What components are we interested in. * @param string $fieldName * This is used in batch profile(i.e to build multiple blocks). * * @param string $groupElementType * * @return void */ public static function setDefaults($id, &$defaults, $type = self::ALL, $fieldName = NULL, $groupElementType = 'checkbox') { $type = (int) $type; if ($type & self::GROUP) { $fName = 'group'; if ($fieldName) { $fName = $fieldName; } $contactGroup = CRM_Contact_BAO_GroupContact::getContactGroup($id, 'Added', NULL, FALSE, TRUE); if ($contactGroup) { foreach ($contactGroup as $group) { if ($groupElementType == 'select') { $defaults[$fName][] = $group['group_id']; } else { $defaults[$fName . '[' . $group['group_id'] . ']'] = 1; } } } } if ($type & self::TAG) { $fName = 'tag'; if ($fieldName) { $fName = $fieldName; } $contactTag = CRM_Core_BAO_EntityTag::getTag($id); if ($contactTag) { foreach ($contactTag as $tag) { $defaults[$fName . '[' . $tag . ']'] = 1; } } } }
/** * Process the form submission. * * * @param array $params * * @return void */ public function postProcess($params = NULL) { $transaction = new CRM_Core_Transaction(); if ($this->_action & CRM_Core_Action::DELETE) { $statusMsg = NULL; //block deleting activities which affects //case attributes.CRM-4543 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')"; $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition); if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) { $params = array('id' => $this->_activityId); $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE); if ($activityDelete) { $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />'); } } else { $statusMsg = ts("Selected Activity cannot be deleted."); } $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId); CRM_Core_BAO_EntityTag::del($tagParams); CRM_Core_Session::setStatus('', $statusMsg, 'info'); return; } if ($this->_action & CRM_Core_Action::RENEW) { $statusMsg = NULL; $params = array('id' => $this->_activityId); $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params); if ($activityRestore) { $statusMsg = ts('The selected activity has been restored.<br />'); } CRM_Core_Session::setStatus('', $statusMsg, 'info'); return; } // store the submitted values in an array $params = $this->controller->exportValues($this->_name); //set parent id if its edit mode if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) { $params['parent_id'] = $parentId; } // store the dates with proper format $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']); $params['activity_type_id'] = $this->_activityTypeId; // format with contact (target contact) values if (isset($params['target_contact_id'])) { $params['target_contact_id'] = explode(',', $params['target_contact_id']); } else { $params['target_contact_id'] = array(); } // format activity custom data if (!empty($params['hidden_custom'])) { if ($this->_activityId) { // unset custom fields-id from params since we want custom // fields to be saved for new activity. foreach ($params as $key => $value) { $match = array(); if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) { $params[$match[1] . '-1'] = $params[$key]; // for autocomplete transfer hidden value instead of label if ($params[$key] && isset($params[$key . '_id'])) { $params[$match[1] . '-1_id'] = $params[$key . '_id']; unset($params[$key . '_id']); } unset($params[$key]); } } } // build custom data getFields array $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId); $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE)); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_activityId, 'Activity'); } // assigning formatted value if (!empty($params['assignee_contact_id'])) { $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']); } else { $params['assignee_contact_id'] = array(); } if (isset($this->_activityId)) { // activity which hasn't been modified by a user yet if ($this->_defaults['is_auto'] == 1) { $params['is_auto'] = 0; } // always create a revision of an case activity. CRM-4533 $newActParams = $params; // add target contact values in update mode if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) { $newActParams['target_contact_id'] = $this->_defaults['target_contact']; } } if (!isset($newActParams)) { // add more attachments if needed for old activity CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity'); // call begin post process, before the activity is created/updated. $this->beginPostProcess($params); foreach ($this->_caseId as $key => $val) { $params['case_id'] = $val; // activity create/update $activity = CRM_Activity_BAO_Activity::create($params); $vvalue[] = array('case_id' => $val, 'actId' => $activity->id); // call end post process, after the activity has been created/updated. $this->endPostProcess($params, $activity); } } else { // since the params we need to set are very few, and we don't want rest of the // work done by bao create method , lets use dao object to make the changes $params = array('id' => $this->_activityId); $params['is_current_revision'] = 0; $activity = new CRM_Activity_DAO_Activity(); $activity->copyValues($params); $activity->save(); } // create a new version of activity if activity was found to // have been modified/created by user if (isset($newActParams)) { // set proper original_id if (!empty($this->_defaults['original_id'])) { $newActParams['original_id'] = $this->_defaults['original_id']; } else { $newActParams['original_id'] = $activity->id; } //is_current_revision will be set to 1 by default. // add attachments if any CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity'); // call begin post process, before the activity is created/updated. $this->beginPostProcess($newActParams); foreach ($this->_caseId as $key => $val) { $newActParams['case_id'] = $val; $activity = CRM_Activity_BAO_Activity::create($newActParams); $vvalue[] = array('case_id' => $val, 'actId' => $activity->id); // call end post process, after the activity has been created/updated. $this->endPostProcess($newActParams, $activity); } // copy files attached to old activity if any, to new one, // as long as users have not selected the 'delete attachment' option. if (empty($newActParams['is_delete_attachment'])) { CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id); } // copy back params to original var $params = $newActParams; } foreach ($vvalue as $vkey => $vval) { if ($vval['actId']) { // add tags if exists $tagParams = array(); if (!empty($params['tag'])) { foreach ($params['tag'] as $tag) { $tagParams[$tag] = 1; } } //save static tags CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']); //save free tags if (isset($params['taglist']) && !empty($params['taglist'])) { CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this); } } // update existing case record if needed $caseParams = $params; $caseParams['id'] = $vval['case_id']; if (!empty($caseParams['case_status_id'])) { $caseParams['status_id'] = $caseParams['case_status_id']; } // unset params intended for activities only unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']); $case = CRM_Case_BAO_Case::create($caseParams); // create case activity record $caseParams = array('activity_id' => $vval['actId'], 'case_id' => $vval['case_id']); CRM_Case_BAO_Case::processCaseActivity($caseParams); } // Insert civicrm_log record for the activity (e.g. store the // created / edited by contact id and date for the activity) // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create() // send copy to selected contacts. $mailStatus = ''; $mailToContacts = array(); //CRM-5695 //check for notification settings for assignee contacts $selectedContacts = array('contact_check'); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) { $selectedContacts[] = 'assignee_contact_id'; } foreach ($vvalue as $vkey => $vval) { foreach ($selectedContacts as $dnt => $val) { if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) { if ($val == 'contact_check') { $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s)."); } else { $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE); $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s)."); } //build an associative array with unique email addresses. foreach ($params[$val] as $key => $value) { if ($val == 'contact_check') { $id = $key; } else { $id = $value; } if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) { //if email already exists in array then append with ', ' another role only otherwise add it to array. if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) { $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]); $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole; } else { $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id]; } } } } } $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId); $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams); if (empty($result)) { $mailStatus = ''; } // create follow up activity if needed $followupStatus = ''; if (!empty($params['followup_activity_type_id'])) { $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params); if ($followupActivity) { $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $vval['case_id']); CRM_Case_BAO_Case::processCaseActivity($caseParams); $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />'; } } $title = ts("%1 Saved", array(1 => $this->_activityTypeName)); CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success'); } }
/** * View summary details of a contact * * @return void * @access public */ function view() { $session = CRM_Core_Session::singleton(); $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $this->_contactId); $session->pushUserContext($url); $params = array(); $defaults = array(); $ids = array(); $params['id'] = $params['contact_id'] = $this->_contactId; $params['noRelationships'] = $params['noNotes'] = $params['noGroups'] = true; $contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults, true); $communicationType = array('phone' => array('type' => 'phoneType', 'id' => 'phone_type'), 'im' => array('type' => 'IMProvider', 'id' => 'provider'), 'website' => array('type' => 'websiteType', 'id' => 'website_type'), 'address' => array('skip' => true, 'customData' => 1), 'email' => array('skip' => true), 'openid' => array('skip' => true)); foreach ($communicationType as $key => $value) { if (CRM_Utils_Array::value($key, $defaults)) { foreach ($defaults[$key] as &$val) { CRM_Utils_Array::lookupValue($val, 'location_type', CRM_Core_PseudoConstant::locationType(), false); if (!CRM_Utils_Array::value('skip', $value)) { eval('$pseudoConst = CRM_Core_PseudoConstant::' . $value['type'] . '( );'); CRM_Utils_Array::lookupValue($val, $value['id'], $pseudoConst, false); } } if (isset($value['customData'])) { foreach ($defaults[$key] as $blockId => $blockVal) { $groupTree = CRM_Core_BAO_CustomGroup::getTree(ucfirst($key), $this, $blockVal['id']); // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var. $defaults[$key][$blockId]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, false, null, "dnc_"); } // reset template variable since that won't be of any use, and could be misleading $this->assign("dnc_viewCustomData", null); } } } if (CRM_Utils_Array::value('gender_id', $defaults)) { $gender = CRM_Core_PseudoConstant::gender(); $defaults['gender_display'] = $gender[CRM_Utils_Array::value('gender_id', $defaults)]; } // to make contact type label available in the template - $contactType = array_key_exists('contact_sub_type', $defaults) ? $defaults['contact_sub_type'] : $defaults['contact_type']; $defaults['contact_type_label'] = CRM_Contact_BAO_ContactType::contactTypePairs(true, $contactType); // get contact tags require_once 'CRM/Core/BAO/EntityTag.php'; $contactTags = CRM_Core_BAO_EntityTag::getContactTags($this->_contactId); if (!empty($contactTags)) { $defaults['contactTag'] = implode(', ', $contactTags); } $defaults['privacy_values'] = CRM_Core_SelectValues::privacy(); //Show blocks only if they are visible in edit form require_once 'CRM/Core/BAO/Preferences.php'; $this->_editOptions = CRM_Core_BAO_Preferences::valueOptions('contact_edit_options'); $configItems = array('CommBlock' => 'Communication Preferences', 'Demographics' => 'Demographics', 'TagsAndGroups' => 'Tags and Groups', 'Notes' => 'Notes'); foreach ($configItems as $c => $t) { $varName = '_show' . $c; $this->{$varName} = CRM_Utils_Array::value($c, $this->_editOptions); $this->assign(substr($varName, 1), $this->{$varName}); } // get contact name of shared contact names $sharedAddresses = array(); $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']); foreach ($defaults['address'] as $key => $addressValue) { if (CRM_Utils_Array::value('master_id', $addressValue) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']); } } $this->assign('sharedAddresses', $sharedAddresses); //get the current employer name if (CRM_Utils_Array::value('contact_type', $defaults) == 'Individual') { if ($contact->employer_id && $contact->organization_name) { $defaults['current_employer'] = $contact->organization_name; $defaults['current_employer_id'] = $contact->employer_id; } //for birthdate format with respect to birth format set $this->assign('birthDateViewFormat', CRM_Utils_Array::value('qfMapping', CRM_Utils_Date::checkBirthDateFormat())); } $this->assign($defaults); // also assign the last modifed details require_once 'CRM/Core/BAO/Log.php'; $lastModified =& CRM_Core_BAO_Log::lastModified($this->_contactId, 'civicrm_contact'); $this->assign_by_ref('lastModified', $lastModified); $allTabs = array(); $weight = 10; $this->_viewOptions = CRM_Core_BAO_Preferences::valueOptions('contact_view_options', true); $changeLog = $this->_viewOptions['log']; $this->assign_by_ref('changeLog', $changeLog); require_once 'CRM/Core/Component.php'; $components = CRM_Core_Component::getEnabledComponents(); foreach ($components as $name => $component) { if (CRM_Utils_Array::value($name, $this->_viewOptions) && CRM_Core_Permission::access($component->name)) { $elem = $component->registerTab(); // FIXME: not very elegant, probably needs better approach // allow explicit id, if not defined, use keyword instead if (array_key_exists('id', $elem)) { $i = $elem['id']; } else { $i = $component->getKeyword(); } $u = $elem['url']; //appending isTest to url for test soft credit CRM-3891. //FIXME: hack ajax url. $q = "reset=1&snippet=1&force=1&cid={$this->_contactId}"; if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) { $q = $q . "&isTest=1"; } $allTabs[] = array('id' => $i, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$u}", $q), 'title' => $elem['title'], 'weight' => $elem['weight'], 'count' => CRM_Contact_BAO_Contact::getCountComponent($u, $this->_contactId)); // make sure to get maximum weight, rest of tabs go after // FIXME: not very elegant again if ($weight < $elem['weight']) { $weight = $elem['weight']; } } } $rest = array('activity' => ts('Activities'), 'case' => ts('Cases'), 'rel' => ts('Relationships'), 'group' => ts('Groups'), 'note' => ts('Notes'), 'tag' => ts('Tags'), 'log' => ts('Change Log')); $config = CRM_Core_Config::singleton(); if (isset($config->sunlight) && $config->sunlight) { $title = ts('Elected Officials'); $rest['sunlight'] = $title; $this->_viewOptions[$title] = true; } foreach ($rest as $k => $v) { if (CRM_Utils_Array::value($k, $this->_viewOptions)) { $allTabs[] = array('id' => $k, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$k}", "reset=1&snippet=1&cid={$this->_contactId}"), 'title' => $v, 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($k, $this->_contactId)); $weight += 10; } } // now add all the custom tabs $entityType = $this->get('contactType'); $activeGroups = CRM_Core_BAO_CustomGroup::getActiveGroups($entityType, 'civicrm/contact/view/cd', $this->_contactId); foreach ($activeGroups as $group) { $id = "custom_{$group['id']}"; $allTabs[] = array('id' => $id, 'url' => CRM_Utils_System::url($group['path'], $group['query'] . "&snippet=1&selectedChild={$id}"), 'title' => $group['title'], 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($id, $this->_contactId, $group['table_name'])); $weight += 10; } // see if any other modules want to add any tabs require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::tabs($allTabs, $this->_contactId); // now sort the tabs based on weight require_once 'CRM/Utils/Sort.php'; usort($allTabs, array('CRM_Utils_Sort', 'cmpFunc')); $this->assign('allTabs', $allTabs); $selectedChild = CRM_Utils_Request::retrieve('selectedChild', 'String', $this, false, 'summary'); $this->assign('selectedChild', $selectedChild); // hook for contact summary require_once 'CRM/Utils/Hook.php'; $contentPlacement = CRM_Utils_Hook::SUMMARY_BELOW; // ignored but needed to prevent warnings CRM_Utils_Hook::summary($this->_contactId, $content, $contentPlacement); if ($content) { $this->assign_by_ref('hookContent', $content); $this->assign('hookContentPlacement', $contentPlacement); } }
/** * Get options for a given contact field. * * @see CRM_Core_DAO::buildOptions * * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow? * TODO: In context of chainselect, what to return if e.g. a country has no states? * * @param string $fieldName * @param string $context * @see CRM_Core_DAO::buildOptionsContext * @param array $props * whatever is known about this dao object. * * @return array|bool */ public static function buildOptions($fieldName, $context = NULL, $props = array()) { $params = array(); // Special logic for fields whose options depend on context or properties switch ($fieldName) { case 'contact_sub_type': if (!empty($props['contact_type'])) { $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')"; } break; case 'contact_type': if ($context == 'search') { // CRM-15495 - EntityRef filters and basic search forms expect this format // FIXME: Search builder does not return CRM_Contact_BAO_ContactType::getSelectElements(); } break; // The contact api supports some related entities so we'll honor that by fetching their options // The contact api supports some related entities so we'll honor that by fetching their options case 'group_id': case 'group': return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props); case 'tag_id': case 'tag': $props['entity_table'] = 'civicrm_contact'; return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props); } return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context); }
/** * Function to build the form * * @return void * @access public */ public function buildQuickForm() { //this call is for show related cases. if ($this->_showRelatedCases) { return; } CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js')->addScriptFile('civicrm', 'templates/CRM/Case/Form/CaseView.js'); $xmlProcessor = new CRM_Case_XMLProcessor_Process(); $caseRoles = $xmlProcessor->get($this->_caseType, 'CaseRoles'); $reports = $xmlProcessor->get($this->_caseType, 'ActivitySets'); //adding case manager.CRM-4510. $managerRoleId = $xmlProcessor->getCaseManagerRoleId($this->_caseType); if (!empty($managerRoleId)) { $caseRoles[$managerRoleId] = $caseRoles[$managerRoleId] . '<br />' . '(' . ts('Case Manager') . ')'; } $aTypes = $xmlProcessor->get($this->_caseType, 'ActivityTypes', TRUE); $allActTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name'); $emailActivityType = array_search('Email', $allActTypes); $pdfActivityType = array_search('Print PDF Letter', $allActTypes); // remove Open Case activity type since we're inside an existing case if ($openActTypeId = array_search('Open Case', $allActTypes)) { unset($aTypes[$openActTypeId]); } //check for link cases. $unclosedCases = CRM_Case_BAO_Case::getUnclosedCases(NULL, array($this->_caseID)); if (empty($unclosedCases) && ($linkActTypeId = array_search('Link Cases', $allActTypes))) { unset($aTypes[$linkActTypeId]); } if (!$xmlProcessor->getNaturalActivityTypeSort()) { asort($aTypes); } $activityLinks = array('' => ts('Add Activity')); foreach ($aTypes as $type => $label) { if ($type == $emailActivityType) { $url = CRM_Utils_System::url('civicrm/activity/email/add', "action=add&context=standalone&reset=1&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } else { if ($type == $pdfActivityType) { $url = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=add&context=standalone&reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } else { $url = CRM_Utils_System::url('civicrm/case/activity', "action=add&reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } } $activityLinks[$url] = $label; } $this->add('select', 'add_activity_type_id', '', $activityLinks, FALSE, array('class' => 'crm-select2 crm-action-menu action-icon-plus twenty')); if ($this->_hasAccessToAllCases) { $this->add('select', 'report_id', '', array('' => ts('Activity Audit')) + $reports, FALSE, array('class' => 'crm-select2 crm-action-menu action-icon-clipboard')); $this->add('select', 'timeline_id', '', array('' => ts('Add Timeline')) + $reports, FALSE, array('class' => 'crm-select2 crm-action-menu action-icon-play')); } $this->addElement('submit', $this->getButtonName('next'), ' ', array('class' => 'hiddenElement')); if ($this->_mergeCases) { $allCases = CRM_Case_BAO_Case::getContactCases($this->_contactID); $otherCases = array(); foreach ($allCases as $caseId => $details) { //filter current and own cases. if ($caseId == $this->_caseID || !$this->_hasAccessToAllCases && !array_key_exists($caseId, $this->_userCases)) { continue; } $otherCases[$caseId] = 'Case ID: ' . $caseId . ' Type: ' . $details['case_type'] . ' Start: ' . $details['case_start_date']; } if (empty($otherCases)) { $this->_mergeCases = FALSE; $this->assign('mergeCases', $this->_mergeCases); } else { $this->add('select', 'merge_case_id', ts('Select Case for Merge'), array('' => ts('- select case -')) + $otherCases, FALSE, array('class' => 'crm-select2 huge')); $this->addElement('submit', $this->getButtonName('next', 'merge_case'), ts('Merge'), array('class' => 'crm-form-submit-inline hiddenElement')); } } //call activity form self::activityForm($this); //get case related relationships (Case Role) $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($this->_contactID, $this->_caseID); //save special label because we unset it in the loop $managerLabel = empty($managerRoleId) ? '' : $caseRoles[$managerRoleId]; foreach ($caseRelationships as $key => &$value) { if (!empty($managerRoleId)) { if ($managerRoleId == $value['relation_type']) { $value['relation'] = $managerLabel; } } //calculate roles that don't have relationships if (!empty($caseRoles[$value['relation_type']])) { unset($caseRoles[$value['relation_type']]); } } $this->assign('caseRelationships', $caseRelationships); //also add client as role. CRM-4438 $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($this->_caseID); $this->assign('caseRoles', $caseRoles); // Retrieve ALL client relationships $relClient = CRM_Contact_BAO_Relationship::getRelationship($this->_contactID, CRM_Contact_BAO_Relationship::CURRENT, 0, 0, 0, NULL, NULL, FALSE); // Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles // so they don't show up twice. $clientRelationships = array(); foreach ($relClient as $r) { if (!array_key_exists($r['id'], $caseRelationships)) { $clientRelationships[] = $r; } } $this->assign('clientRelationships', $clientRelationships); // Now global contact list that appears on all cases. $globalGroupInfo = array(); CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo); $this->assign('globalGroupInfo', $globalGroupInfo); // List of relationship types $baoRel = new CRM_Contact_BAO_Relationship(); $relType = $baoRel->getRelationType('Individual'); $roleTypes = array(); foreach ($relType as $k => $v) { $roleTypes[substr($k, 0, strpos($k, '_'))] = $v; } $this->add('select', 'role_type', ts('Relationship Type'), array('' => ts('- select type -')) + $roleTypes, FALSE, array('class' => 'crm-select2 twenty')); $hookCaseSummary = CRM_Utils_Hook::caseSummary($this->_caseID); if (is_array($hookCaseSummary)) { $this->assign('hookCaseSummary', $hookCaseSummary); } $allTags = CRM_Core_BAO_Tag::getTags('civicrm_case'); if (!empty($allTags)) { $this->add('select', 'case_tag', ts('Tags'), $allTags, FALSE, array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2')); $tags = CRM_Core_BAO_EntityTag::getTag($this->_caseID, 'civicrm_case'); $this->setDefaults(array('case_tag' => $tags)); foreach ($tags as $tid) { if (isset($allTags[$tid])) { $tags[$tid] = $allTags[$tid]; } else { unset($tags[$tid]); } } $this->assign('tags', implode(', ', array_filter($tags))); $this->assign('showTags', TRUE); } else { $this->assign('showTags', FALSE); } // build tagset widget // see if we have any tagsets which can be assigned to cases $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_case'); if ($parentNames) { $this->assign('showTagsets', TRUE); } else { $this->assign('showTagsets', FALSE); } CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_case', $this->_caseID, FALSE, TRUE); $this->addButtons(array(array('type' => 'cancel', 'name' => ts('Done'), 'spacing' => ' ', 'isDefault' => TRUE))); }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $tx = new CRM_Core_Transaction(); // check if dedupe button, if so return. $buttonName = $this->controller->getButtonName(); if (isset($this->_dedupeButtonName) && $buttonName == $this->_dedupeButtonName) { return; } if ($this->_action & CRM_Core_Action::DELETE) { $statusMsg = NULL; $caseDelete = CRM_Case_BAO_Case::deleteCase($this->_caseId, TRUE); if ($caseDelete) { $statusMsg = ts('The selected case has been moved to the Trash. You can view and / or restore deleted cases by checking the "Deleted Cases" option under Find Cases.<br />'); } CRM_Core_Session::setStatus($statusMsg); return; } if ($this->_action & CRM_Core_Action::RENEW) { $statusMsg = NULL; $caseRestore = CRM_Case_BAO_Case::restoreCase($this->_caseId); if ($caseRestore) { $statusMsg = ts('The selected case has been restored.<br />'); } CRM_Core_Session::setStatus($statusMsg); return; } // store the submitted values in an array $params = $this->controller->exportValues($this->_name); $params['now'] = date("Ymd"); // 1. call begin post process if ($this->_activityTypeFile) { eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}" . "::beginPostProcess( \$this, \$params );"); } if (CRM_Utils_Array::value('hidden_custom', $params) && !isset($params['custom'])) { $customFields = array(); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, NULL, 'Case'); } // 2. create/edit case if (CRM_Utils_Array::value('case_type_id', $params)) { $caseType = CRM_Case_PseudoConstant::caseType('name'); $params['case_type'] = $caseType[$params['case_type_id']]; $params['subject'] = $params['activity_subject']; $params['case_type_id'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['case_type_id'] . CRM_Core_DAO::VALUE_SEPARATOR; } $caseObj = CRM_Case_BAO_Case::create($params); $params['case_id'] = $caseObj->id; // unset any ids, custom data unset($params['id'], $params['custom']); // add tags if exists $tagParams = array(); if (!empty($params['tag'])) { $tagParams = array(); foreach ($params['tag'] as $tag) { $tagParams[$tag] = 1; } } CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_case', $caseObj->id); //save free tags if (isset($params['case_taglist']) && !empty($params['case_taglist'])) { CRM_Core_Form_Tag::postProcess($params['case_taglist'], $caseObj->id, 'civicrm_case', $this); } // user context $url = CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseObj->id}"); $session = CRM_Core_Session::singleton(); $session->pushUserContext($url); // 3. format activity custom data if (CRM_Utils_Array::value('hidden_custom', $params)) { $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId); $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE)); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity'); } // 4. call end post process if ($this->_activityTypeFile) { eval("CRM_Case_Form_Activity_{$this->_activityTypeFile}" . "::endPostProcess( \$this, \$params );"); } // 5. auto populate activites // 6. set status CRM_Core_Session::setStatus("{$params['statusMsg']}"); }
/** * Given a contact id and a field set, return the values from the db * for this contact * * @param int $id the contact id * @param array $fields the profile fields of interest * @param array $values the values for the above fields * @return void * @access public * @static */ function getValues($cid, &$fields, &$values) { $options = array(); // get the contact details (hier) $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); $params = array('id' => $cid); $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $details = $query->searchQuery(); if (!$details->fetch()) { return; } require_once 'CRM/Core/PseudoConstant.php'; $locationTypes = CRM_Core_PseudoConstant::locationType(); //start of code to set the default values foreach ($fields as $name => $field) { $index = $field['title']; $params[$index] = $values[$index] = ''; if ($details->{$name} || $name == 'group' || $name == 'tag') { //hack for CRM-665 //to handle custom data (checkbox) to be written // to handle gender / suffix / prefix if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) { $values[$index] = $details->{$name}; $name = $name . '_id'; $params[$index] = $details->{$name}; } else { if (in_array($name, array('state_province', 'country'))) { $values[$index] = $details->{$name}; $idx = $name . '_id'; $params[$index] = $details->{$idx}; } else { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($details->{$name}) { $values[$index] = '[ x ]'; } } else { if ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true); $title = array(); $ids = array(); foreach ($groups as $g) { if ($g['visibility'] != 'User and User Admin Only') { $title[] = $g['title']; if ($g['visibility'] == 'Public User Pages and Listings') { $ids[] = $g['group_id']; } } } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $ids); } else { if ($name == 'tag') { require_once 'CRM/Core/BAO/EntityTag.php'; $entityTags =& CRM_Core_BAO_EntityTag::getTag('civicrm_contact', $cid); $allTags =& CRM_Core_PseudoConstant::tag(); $title = array(); foreach ($entityTags as $tagId) { $title[] = $allTags[$tagId]; } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $entityTags); } else { require_once 'CRM/Core/BAO/CustomField.php'; if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $params[$index] = $details->{$name}; $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($details->{$name}, $cfID, $options); } else { $values[$index] = $details->{$name}; } } } } } } } else { if (strpos($name, '-') !== false) { list($fieldName, $id, $type) = explode('-', $name); $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); if (!$locationTypeName) { continue; } $detailName = "{$locationTypeName}-{$fieldName}"; if (in_array($fieldName, array('phone', 'im', 'email'))) { if ($type) { $detailName .= "-{$type}"; } else { $detailName .= '-1'; } } if (in_array($fieldName, array('state_province', 'country'))) { $values[$index] = $details->{$detailName}; $idx = $detailName . '_id'; $params[$index] = $details->{$idx}; } else { $values[$index] = $params[$index] = $details->{$detailName}; } } } if ($field['visibility'] == "Public User Pages and Listings" && CRM_Utils_System::checkPermission('profile listings and forms')) { if (CRM_Utils_System::isNull($params[$index])) { $params[$index] = $values[$index]; } if (empty($params[$index])) { continue; } $fieldName = $field['name']; $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); if (!empty($values[$index])) { $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>'; } } } }
/** * Process activity creation. * * @param array $params * Associated array of submitted values. * * @return self|null|object */ protected function processActivity(&$params) { $activityAssigned = array(); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); // format assignee params if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) { //skip those assignee contacts which are already assigned //while sending a copy.CRM-4509. $activityAssigned = array_flip($params['assignee_contact_id']); if ($this->_activityId) { $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID); $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts); } } // call begin post process. Idea is to let injecting file do // any processing before the activity is added/updated. $this->beginPostProcess($params); $activity = CRM_Activity_BAO_Activity::create($params); // add tags if exists $tagParams = array(); if (!empty($params['tag'])) { foreach ($params['tag'] as $tag) { $tagParams[$tag] = 1; } } // Save static tags. CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id); // Save free tags. if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) { CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this); } // call end post process. Idea is to let injecting file do any // processing needed, after the activity has been added/updated. $this->endPostProcess($params, $activity); // CRM-9590 if (!empty($params['is_multi_activity'])) { $this->_activityIds[] = $activity->id; } else { $this->_activityId = $activity->id; } // create follow up activity if needed $followupStatus = ''; $followupActivity = NULL; if (!empty($params['followup_activity_type_id'])) { $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params); $followupStatus = ts('A followup activity has been scheduled.'); } // send copy to assignee contacts.CRM-4509 $mailStatus = ''; if (Civi::settings()->get('activity_assignee_notification')) { $activityIDs = array($activity->id); if ($followupActivity) { $activityIDs = array_merge($activityIDs, array($followupActivity->id)); } $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE); if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) { $mailToContacts = array(); // Build an associative array with unique email addresses. foreach ($activityAssigned as $id => $dnc) { if (isset($id) && array_key_exists($id, $assigneeContacts)) { $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id]; } } $sent = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts); if ($sent) { $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s)."); } } // Also send email to follow-up activity assignees if set if ($followupActivity) { $mailToFollowupContacts = array(); foreach ($assigneeContacts as $values) { if ($values['activity_id'] == $followupActivity->id) { $mailToFollowupContacts[$values['email']] = $values; } } $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts); if ($sentFollowup) { $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s)."); } } } // set status message $subject = ''; if (!empty($params['subject'])) { $subject = "'" . $params['subject'] . "'"; } CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3', array(1 => $subject, 2 => $followupStatus, 3 => $mailStatus)), ts('Saved'), 'success'); return $activity; }
/** * Save entity tags when it is not save used AJAX. * * @param array $params * @param int $entityId * Entity id, eg: contact id, activity id, case id, file id. * @param string $entityTable * Entity table. * @param CRM_Core_Form $form * Form object. */ public static function postProcess(&$params, $entityId, $entityTable = 'civicrm_contact', &$form) { if ($form && !empty($form->_entityTagValues)) { $existingTags = $form->_entityTagValues; } else { $existingTags = CRM_Core_BAO_EntityTag::getTag($entityId, $entityTable); } if ($form) { // if the key is missing from the form response then all the tags were deleted / cleared // in that case we create empty tagset params so that below logic works and tagset are // deleted correctly foreach ($form->_tagsetInfo as $tagsetName => $tagsetInfo) { $tagsetId = explode('parentId_', $tagsetName); $tagsetId = $tagsetId[1]; if (empty($params[$tagsetId])) { $params[$tagsetId] = ''; } } } // when form is submitted with tagset values below logic will work and in the case when all tags in a tagset // are deleted we will have to set $params[tagset id] = '' which is done by above logic foreach ($params as $parentId => $value) { $newTagIds = array(); $tagIds = array(); if ($value) { $tagIds = explode(',', $value); foreach ($tagIds as $tagId) { if ($form && $form->_action != CRM_Core_Action::UPDATE || !array_key_exists($tagId, $existingTags)) { $newTagIds[] = $tagId; } } } // Any existing entity tags from this tagset missing from the $params should be deleted $deleteSQL = "DELETE FROM civicrm_entity_tag\n USING civicrm_entity_tag, civicrm_tag\n WHERE civicrm_tag.id=civicrm_entity_tag.tag_id\n AND civicrm_entity_tag.entity_table='{$entityTable}'\n AND entity_id={$entityId} AND parent_id={$parentId}"; if (!empty($tagIds)) { $deleteSQL .= " AND tag_id NOT IN (" . implode(', ', $tagIds) . ");"; } CRM_Core_DAO::executeQuery($deleteSQL); if (!empty($newTagIds)) { // New tag ids can be inserted directly into the db table. $insertValues = array(); foreach ($newTagIds as $tagId) { $insertValues[] = "( {$tagId}, {$entityId}, '{$entityTable}' ) "; } $insertSQL = 'INSERT INTO civicrm_entity_tag ( tag_id, entity_id, entity_table ) VALUES ' . implode(', ', $insertValues) . ';'; CRM_Core_DAO::executeQuery($insertSQL); } } }
/** * get all the files and associated object associated with this * combination */ static function getEntityFile($entityTable, $entityID, $addDeleteArgs = false) { if (empty($entityTable) || !$entityID) { $results = NULL; return $results; } $config = CRM_Core_Config::singleton(); list($sql, $params) = self::sql($entityTable, $entityID, NULL); $dao = CRM_Core_DAO::executeQuery($sql, $params); $results = array(); while ($dao->fetch()) { $result['fileID'] = $dao->cfID; $result['entityID'] = $dao->cefID; $result['mime_type'] = $dao->mime_type; $result['fileName'] = $dao->uri; $result['description'] = $dao->description; $result['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri); $result['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri; $result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$entityID}"); $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>"; $result['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->cfID, 'civicrm_file'); if ($addDeleteArgs) { $result['deleteURLArgs'] = self::deleteURLArgs($entityTable, $entityID, $dao->cfID); } $results[$dao->cfID] = $result; } //fix tag names $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); foreach ($results as &$values) { if (!empty($values['tag'])) { $tagNames = array(); foreach ($values['tag'] as $tid) { $tagNames[] = $tags[$tid]; } $values['tag'] = implode(', ', $tagNames); } else { $values['tag'] = ''; } } $dao->free(); return $results; }
/** * Given a contact id and a field set, return the values from the db * for this contact * * @param int $id the contact id * @param array $fields the profile fields of interest * @param array $values the values for the above fields * @param boolean $searchable searchable or not * @param array $componentWhere component condition * * @return void * @access public * @static */ public static function getValues($cid, &$fields, &$values, $searchable = true, $componentWhere = null) { if (empty($cid)) { return null; } $options = array(); $studentFields = array(); if (CRM_Core_Permission::access('Quest', false)) { //student fields ( check box ) require_once 'CRM/Quest/BAO/Student.php'; $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields; } // get the contact details (hier) $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); $params = array(array('contact_id', '=', $cid, 0, 0)); // add conditions specified by components. eg partcipant_id etc if (!empty($componentWhere)) { $params = array_merge($params, $componentWhere); } $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $details = $query->searchQuery(); if (!$details->fetch()) { return; } $config =& CRM_Core_Config::singleton(); require_once 'CRM/Core/PseudoConstant.php'; $locationTypes = $imProviders = array(); $locationTypes = CRM_Core_PseudoConstant::locationType(); $imProviders = CRM_Core_PseudoConstant::IMProvider(); //start of code to set the default values foreach ($fields as $name => $field) { // fix for CRM-3962 if ($name == 'id') { $name = 'contact_id'; } $index = $field['title']; $params[$index] = $values[$index] = ''; $customFieldName = null; $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee'); if (isset($details->{$name}) || $name == 'group' || $name == 'tag') { //hack for CRM-665 // to handle gender / suffix / prefix if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) { $values[$index] = $details->{$name}; $name = $name . '_id'; $params[$index] = $details->{$name}; } else { if (in_array($name, array('email_greeting', 'postal_greeting', 'addressee'))) { $dname = $name . '_display'; $values[$index] = $details->{$dname}; $name = $name . '_id'; $params[$index] = $details->{$name}; } else { if (in_array($name, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$name}; $idx = $name . '_id'; $params[$index] = $details->{$idx}; } else { if ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::pcm(); $pref = array(); $compref = array(); $pref = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details->{$name}); foreach ($pref as $k) { if ($k) { $compref[] = $communicationFields[$k]; } } $params[$index] = $details->{$name}; $values[$index] = implode(",", $compref); } else { if ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true); $title = array(); $ids = array(); foreach ($groups as $g) { if ($g['visibility'] != 'User and User Admin Only') { $title[] = $g['title']; if ($g['visibility'] == 'Public Pages') { $ids[] = $g['group_id']; } } } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $ids); } else { if ($name == 'tag') { require_once 'CRM/Core/BAO/EntityTag.php'; $entityTags =& CRM_Core_BAO_EntityTag::getTag($cid); $allTags =& CRM_Core_PseudoConstant::tag(); $title = array(); foreach ($entityTags as $tagId) { $title[] = $allTags[$tagId]; } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $entityTags); } else { if (array_key_exists($name, $studentFields)) { require_once 'CRM/Core/OptionGroup.php'; $paramsNew = array($name => $details->{$name}); if ($name == 'test_tutoring') { $names = array($name => array('newName' => $index, 'groupName' => 'test')); } else { if (substr($name, 0, 4) == 'cmr_') { //for readers group $names = array($name => array('newName' => $index, 'groupName' => substr($name, 0, -3))); } else { $names = array($name => array('newName' => $index, 'groupName' => $name)); } } CRM_Core_OptionGroup::lookupValues($paramsNew, $names, false); $values[$index] = $paramsNew[$index]; $params[$index] = $paramsNew[$name]; } else { $processed = false; if (CRM_Core_Permission::access('Quest', false)) { require_once 'CRM/Quest/BAO/Student.php'; $processed = CRM_Quest_BAO_Student::buildStudentForm($this, $field); } if (!$processed) { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($details->{$name}) { $values[$index] = '[ x ]'; } } else { require_once 'CRM/Core/BAO/CustomField.php'; if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $htmlType = $field['html_type']; $dataType = $field['data_type']; if ($htmlType == 'File') { $fileURL = CRM_Core_BAO_CustomField::getFileURL($cid, $cfID); $params[$index] = $values[$index] = $fileURL['file_url']; } else { $customVal = null; if (isset($dao) && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) { $customVal = (int) $details->{$name}; } else { if (isset($dao) && $dao->data_type == 'Float') { $customVal = (double) $details->{$name}; } else { if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) { $customVal = $details->{$name}; } } } //CRM-4582 if (CRM_Utils_System::isNull($customVal)) { continue; } $params[$index] = $customVal; $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); if ($htmlType == 'Autocomplete-Select') { $params[$index] = $values[$index]; } if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) { $customFieldName = "{$name}_from"; } } } else { if ($name == 'home_URL' && !empty($details->{$name})) { $url = CRM_Utils_System::fixURL($details->{$name}); $values[$index] = "<a href=\"{$url}\">{$details->{$name}}</a>"; } else { if (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) { require_once 'CRM/Utils/Date.php'; $values[$index] = CRM_Utils_Date::customFormat($details->{$name}); $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name}); } else { $values[$index] = $details->{$name}; } } } } } } } } } } } } } else { if (strpos($name, '-') !== false) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3); if ($id == 'Primary') { // fix for CRM-1543 // not sure why we'd every use Primary location type id // we need to fix the source if we are using it // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid ); $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); } if (!$locationTypeName) { continue; } $detailName = "{$locationTypeName}-{$fieldName}"; $detailName = str_replace(' ', '_', $detailName); if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) { if ($type) { $detailName .= "-{$type}"; } } if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$detailName}; $idx = $detailName . '_id'; $params[$index] = $details->{$idx}; } else { if ($fieldName == 'im') { $providerId = $detailName . '-provider_id'; $providerName = $imProviders[$details->{$providerId}]; if ($providerName) { $values[$index] = $details->{$detailName} . " (" . $providerName . ")"; } else { $values[$index] = $details->{$detailName}; } $params[$index] = $details->{$detailName}; } else { $values[$index] = $params[$index] = $details->{$detailName}; } } } } if ($field['visibility'] == "Public Pages and Listings" && CRM_Core_Permission::check('profile listings and forms')) { if (CRM_Utils_System::isNull($params[$index])) { $params[$index] = $values[$index]; } if (!isset($params[$index])) { continue; } $customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name']); if (!$customFieldName) { $fieldName = $field['name']; } else { $fieldName = $customFieldName; } $url = null; if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) { $htmlType = $field['html_type']; if ($htmlType == 'Link') { $url = $params[$index]; } else { if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) { $valSeperator = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR; $selectedOptions = explode($valSeperator, $params[$index]); foreach ($selectedOptions as $key => $multiOption) { if ($multiOption) { $eachOption = $valSeperator . $multiOption . $valSeperator; $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($eachOption)); } } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } if ($url && !empty($values[$index]) && $searchable) { if (is_array($url) && !empty($url)) { $links = array(); $eachMultiValue = explode(', ', $values[$index]); foreach ($eachMultiValue as $key => $valueLabel) { $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>'; } $values[$index] = implode(', ', $links); } else { $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>'; } } } } }
/** * Form submission of new/edit contact is processed. * * @access public * @return None */ public function postProcess() { // check if dedupe button, if so return. $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->_dedupeButtonName) { return; } //get the submitted values in an array $params = $this->controller->exportValues($this->_name); //get the related id for shared / current employer if (CRM_Utils_Array::value('shared_household_id', $params)) { $params['shared_household'] = $params['shared_household_id']; } if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && CRM_Utils_Array::value('current_employer', $params)) { $params['current_employer'] = $params['current_employer_id']; } // don't carry current_employer_id field, // since we don't want to directly update DAO object without // handling related business logic ( eg related membership ) if (isset($params['current_employer_id'])) { unset($params['current_employer_id']); } $params['contact_type'] = $this->_contactType; if ($this->_contactId) { $params['contact_id'] = $this->_contactId; } //make deceased date null when is_deceased = false if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('Demographics', $this->_editOptions) && !CRM_Utils_Array::value('is_deceased', $params)) { $params['is_deceased'] = false; $params['deceased_date'] = null; } if ($this->_contactSubType && $this->_action & CRM_Core_Action::ADD) { $params['contact_sub_type'] = $this->_contactSubType; } // action is taken depending upon the mode require_once 'CRM/Utils/Hook.php'; if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params); } else { CRM_Utils_Hook::pre('create', $params['contact_type'], null, $params); } require_once 'CRM/Core/BAO/CustomField.php'; $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], false, true); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_contactId, $params['contact_type'], true); if (array_key_exists('CommunicationPreferences', $this->_editOptions)) { // this is a chekbox, so mark false if we dont get a POST value $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, false); } // copy household address, if use_household_address option (for individual form) is checked if ($this->_contactType == 'Individual') { if (CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('shared_household', $params)) { if (is_numeric($params['shared_household'])) { CRM_Contact_Form_Edit_Individual::copyHouseholdAddress($params); } CRM_Contact_Form_Edit_Individual::createSharedHousehold($params); } else { $params['mail_to_household_id'] = 'null'; } } else { $params['mail_to_household_id'] = 'null'; } if (!array_key_exists('TagsAndGroups', $this->_editOptions)) { unset($params['group']); } if (CRM_Utils_Array::value('contact_id', $params) && $this->_action & CRM_Core_Action::UPDATE) { // cleanup unwanted location blocks require_once 'CRM/Core/BAO/Location.php'; CRM_Core_BAO_Location::cleanupContactLocations($params); // figure out which all groups are intended to be removed if (!empty($params['group'])) { $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added'); if (is_array($contactGroupList)) { foreach ($contactGroupList as $key) { if ($params['group'][$key['group_id']] != 1) { $params['group'][$key['group_id']] = -1; } } } } } require_once 'CRM/Contact/BAO/Contact.php'; $contact =& CRM_Contact_BAO_Contact::create($params, true, false); if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('mail_to_household_id', $params)) { // add/edit/delete the relation of individual with household, if use-household-address option is checked/unchecked. CRM_Contact_Form_Edit_Individual::handleSharedRelation($contact->id, $params); } if ($this->_contactType == 'Household' && $this->_action & CRM_Core_Action::UPDATE) { //TO DO: commented because of schema changes require_once 'CRM/Contact/Form/Edit/Household.php'; CRM_Contact_Form_Edit_Household::synchronizeIndividualAddresses($contact->id); } if (array_key_exists('TagsAndGroups', $this->_editOptions)) { //add contact to tags require_once 'CRM/Core/BAO/EntityTag.php'; CRM_Core_BAO_EntityTag::create($params['tag'], $params['contact_id']); } // here we replace the user context with the url to view this contact $session =& CRM_Core_Session::singleton(); CRM_Core_Session::setStatus(ts('Your %1 contact record has been saved.', array(1 => $contact->contact_type_display))); $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->getButtonName('next', 'new') || $buttonName == $this->getButtonName('upload', 'new')) { require_once 'CRM/Utils/Recent.php'; // add the recently viewed contact $displayName = CRM_Contact_BAO_Contact::displayName($contact->id); CRM_Utils_Recent::add($displayName, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $displayName); $resetStr = "reset=1&ct={$contact->contact_type}"; $resetStr .= $this->_contactSubType ? "&cst={$this->_contactSubType}" : ''; $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr)); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id)); } // now invoke the post hook if ($this->_action & CRM_Core_Action::UPDATE) { CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact); } else { CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact); } }
static function mergeTags() { $tagAId = CRM_Utils_Type::escape($_POST['fromId'], 'Integer'); $tagBId = CRM_Utils_Type::escape($_POST['toId'], 'Integer'); $result = CRM_Core_BAO_EntityTag::mergeTags($tagAId, $tagBId); if (!empty($result['tagB_used_for'])) { $usedFor = CRM_Core_OptionGroup::values('tag_used_for'); foreach ($result['tagB_used_for'] as &$val) { $val = $usedFor[$val]; } $result['tagB_used_for'] = implode(', ', $result['tagB_used_for']); } CRM_Utils_JSON::output($result); }
/** * Process the view. * * * @return void */ public function preProcess() { $contactID = CRM_Utils_Request::retrieve('cid', 'Integer', $this, TRUE); $activityID = CRM_Utils_Request::retrieve('aid', 'Integer', $this, TRUE); $revs = CRM_Utils_Request::retrieve('revs', 'Boolean', CRM_Core_DAO::$_nullObject); $caseID = CRM_Utils_Request::retrieve('caseID', 'Boolean', CRM_Core_DAO::$_nullObject); $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'subject'); //check for required permissions, CRM-6264 if ($activityID && !CRM_Activity_BAO_Activity::checkPermission($activityID, CRM_Core_Action::VIEW)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } $this->assign('contactID', $contactID); $this->assign('caseID', $caseID); // CRM-9145 $this->assign('activityID', $activityID); $xmlProcessor = new CRM_Case_XMLProcessor_Report(); $report = $xmlProcessor->getActivityInfo($contactID, $activityID, TRUE); $attachmentUrl = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityID); if ($attachmentUrl) { $report['fields'][] = array('label' => 'Attachment(s)', 'value' => $attachmentUrl, 'type' => 'Link'); } $tags = CRM_Core_BAO_EntityTag::getTag($activityID, 'civicrm_activity'); if (!empty($tags)) { $allTag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); foreach ($tags as $tid) { $tags[$tid] = $allTag[$tid]; } $report['fields'][] = array('label' => 'Tags', 'value' => implode('<br />', $tags), 'type' => 'String'); } $this->assign('report', $report); $latestRevisionID = CRM_Activity_BAO_Activity::getLatestActivityId($activityID); $viewPriorActivities = array(); $priorActivities = CRM_Activity_BAO_Activity::getPriorAcitivities($activityID); foreach ($priorActivities as $activityId => $activityValues) { if (CRM_Case_BAO_Case::checkPermission($activityId, 'view', NULL, $contactID)) { $viewPriorActivities[$activityId] = $activityValues; } } if ($revs) { CRM_Utils_System::setTitle(ts('Activity Revision History')); $this->assign('revs', $revs); $this->assign('result', $viewPriorActivities); $this->assign('subject', $activitySubject); $this->assign('latestRevisionID', $latestRevisionID); } else { if (count($viewPriorActivities) > 1) { $this->assign('activityID', $activityID); } if ($latestRevisionID != $activityID) { $this->assign('latestRevisionID', $latestRevisionID); } } $parentID = CRM_Activity_BAO_Activity::getParentActivity($activityID); if ($parentID) { $this->assign('parentID', $parentID); } //viewing activity should get diplayed in recent list.CRM-4670 $activityTypeID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityID, 'activity_type_id'); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $activityTargetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activityID, $targetID); if (!empty($activityTargetContacts)) { $recentContactId = $activityTargetContacts[0]; } else { $recentContactId = $contactID; } if (!isset($caseID)) { $caseID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $activityID, 'case_id', 'activity_id'); } $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activityID}&cid={$recentContactId}&caseID={$caseID}&context=home"); $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId); // add the recently created Activity $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE); $title = ""; if (isset($activitySubject)) { $title = $activitySubject . ' - '; } $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activityTypeID] . ')'; $recentOther = array(); if (CRM_Case_BAO_Case::checkPermission($activityID, 'edit')) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=update&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home"); } if (CRM_Case_BAO_Case::checkPermission($activityID, 'delete')) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/case/activity', "reset=1&action=delete&id={$activityID}&cid={$recentContactId}&caseid={$caseID}&context=home"); } CRM_Utils_Recent::add($title, $url, $activityID, 'Activity', $recentContactId, $recentContactDisplay, $recentOther); }
private function _tagImportedContactsWithNewTag($contactIds, $newTagName, $newTagDesc) { $newTagId = NULL; if ($newTagName) { /* Create a new Tag */ $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_selectable' => TRUE, 'used_for' => 'civicrm_contact'); $id = array(); $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id); $this->_tag[$addedTag->id] = 1; } //add Tag to Import if (is_array($this->_tag)) { $tagAdditions = array(); foreach ($this->_tag as $tagId => $val) { $addTagCount = CRM_Core_BAO_EntityTag::addEntitiesToTag($contactIds, $tagId); $totalTagCount = $addTagCount[1]; if (isset($addedTag) && $tagId == $addedTag->id) { $tagName = $newTagName; $new = TRUE; } else { $tagName = $this->_allTags[$tagId]; $new = FALSE; } $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2], 'new' => $new); } return $tagAdditions; } return FALSE; }