static function preProcessCommon(&$form, $useTable = true) { $form->_contactIds = array(); $form->_contactTypes = array(); $form->_searchFrom = $searchformName = 'contact'; $searchFrom = $form->get('searchFormName'); $pages = $form->controller->_pages; $prefix = 'contact'; if ($pages[$searchFrom]) { $prefix = $pages[$searchFrom]->getVar('_prefix'); if ($prefix == 'member_') { $searchformName = 'member'; } } if ($searchformName == 'member') { $form->_searchFrom = $searchformName; $values = $form->controller->exportValues($form->get('searchFormName')); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $sortOrder = null; if ($form->get(CRM_Utils_Sort::SORT_ORDER)) { $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER); } $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_MEMBER); $query->_distinctComponentClause = ' civicrm_membership.id'; $query->_groupByComponentClause = ' GROUP BY civicrm_membership.id '; $result = $query->searchQuery(0, 0, $sortOrder); while ($result->fetch()) { $ids[] = $result->membership_id; } } if (!empty($ids)) { $form->_componentClause = ' civicrm_membership.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedMembers', count($ids)); } $form->_memberIds = $form->_componentIds = $ids; $form->_contactIds =& CRM_Core_DAO::getContactIDsFromComponent($ids, 'civicrm_membership'); $form->assign('totalSelectedContacts', count($form->_contactIds)); } else { parent::preProcessCommon($form); } }
/** * Test CRM_Contact_BAO_Query::searchQuery() * @dataProvider dataProvider */ function testSearch($fv, $count, $ids, $full) { $op = new PHPUnit_Extensions_Database_Operation_Insert(); $op->execute($this->_dbconn, new PHPUnit_Extensions_Database_DataSet_FlatXMLDataSet(dirname(__FILE__) . '/queryDataset.xml')); $params = CRM_Contact_BAO_Query::convertFormValues($fv); $obj = new CRM_Contact_BAO_Query($params); $obj->_useGroupBy = TRUE; $dao = $obj->searchQuery(); $contacts = array(); while ($dao->fetch()) { $contacts[] = $dao->contact_id; } sort($contacts, SORT_NUMERIC); $this->assertEquals($ids, $contacts, 'In line ' . __LINE__); }
/** * @param CRM_Core_Form $form * @param bool $useTable */ public static function preProcessCommon(&$form, $useTable = FALSE) { $form->_contributionIds = array(); $values = $form->controller->exportValues($form->get('searchFormName')); $form->_task = $values['task']; $contributeTasks = CRM_Contribute_Task::tasks(); $form->assign('taskName', $contributeTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $sortOrder = NULL; if ($form->get(CRM_Utils_Sort::SORT_ORDER)) { $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER); } $form->_includesSoftCredits = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($queryParams); $query = new CRM_Contact_BAO_Query($queryParams, array('contribution_id'), NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE); // @todo the function CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled should handle this // can we remove? if not why not? if ($form->_includesSoftCredits) { $contactIds = $contributionContactIds = array(); $query->_rowCountClause = " count(civicrm_contribution.id)"; $query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id "; } else { $query->_distinctComponentClause = ' civicrm_contribution.id'; $query->_groupByComponentClause = ' GROUP BY civicrm_contribution.id '; } $result = $query->searchQuery(0, 0, $sortOrder); while ($result->fetch()) { $ids[] = $result->contribution_id; if ($form->_includesSoftCredits) { $contactIds[$result->contact_id] = $result->contact_id; $contributionContactIds["{$result->contact_id}-{$result->contribution_id}"] = $result->contribution_id; } } $result->free(); $form->assign('totalSelectedContributions', $form->get('rowCount')); } if (!empty($ids)) { $form->_componentClause = ' civicrm_contribution.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedContributions', count($ids)); } if (!empty($form->_includesSoftCredits) && !empty($contactIds)) { $form->_contactIds = $contactIds; $form->_contributionContactIds = $contributionContactIds; } $form->_contributionIds = $form->_componentIds = $ids; //set the context for redirection for any task actions $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $searchFormName = strtolower($form->get('searchFormName')); if ($searchFormName == 'search') { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/search', $urlParams)); } else { $session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/{$searchFormName}", $urlParams)); } }
static function relationshipContacts() { $data = $searchValues = $searchRows = array(); $addCount = 0; $relType = CRM_Utils_Type::escape($_REQUEST['relType'], 'String'); $typeName = isset($_REQUEST['typeName']) ? CRM_Utils_Type::escape($_REQUEST['typeName'], 'String') : ''; $relContact = CRM_Utils_Type::escape($_REQUEST['relContact'], 'String'); $currentContactId = CRM_Utils_Type::escape($_REQUEST['cid'], 'Integer'); if (in_array($typeName, array('Employee of', 'Employer of'))) { $addCount = 1; } $sortMapper = array(1 => 'sort_name', 2 + $addCount => 'city', 3 + $addCount => 'state_province', 4 + $addCount => 'email', 5 + $addCount => 'phone'); $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer'); $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0; $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25; $sort = isset($_REQUEST['iSortCol_0']) ? $sortMapper[CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer')] : 'sort_name'; $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc'; $searchValues[] = array('sort_name', 'LIKE', $relContact, 0, 1); list($rid, $direction) = explode('_', $relType, 2); $relationshipType = new CRM_Contact_DAO_RelationshipType(); $relationshipType->id = $rid; if ($relationshipType->find(TRUE)) { if ($direction == 'a_b') { $type = $relationshipType->contact_type_b; $subType = $relationshipType->contact_sub_type_b; } else { $type = $relationshipType->contact_type_a; $subType = $relationshipType->contact_sub_type_a; } if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') { $searchValues[] = array('contact_type', '=', $type, 0, 0); $contactTypeAdded = TRUE; } if ($subType) { $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0); } } // exclude current contact $searchValues[] = array('contact_id', '!=', $currentContactId, 0, 0); $contactBAO = new CRM_Contact_BAO_Contact(); $query = new CRM_Contact_BAO_Query($searchValues); $searchCount = $query->searchQuery(0, 0, NULL, TRUE); $iTotal = $searchCount; if ($searchCount > 0) { // get the result of the search $result = $query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, NULL, $sortOrder); $config = CRM_Core_Config::singleton(); //variable is set if only one record is foun and that record already has relationship with the contact $duplicateRelationship = 0; while ($result->fetch()) { $contactID = $result->contact_id; $duplicateRelationship = 0; $contact_type = '<img src="' . $config->resourceBase . 'i/contact_'; $typeImage = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $contactID); $searchRows[$contactID]['id'] = $contactID; $searchRows[$contactID]['name'] = $typeImage . ' ' . $result->sort_name; $searchRows[$contactID]['city'] = $result->city; $searchRows[$contactID]['state'] = $result->state_province; $searchRows[$contactID]['email'] = $result->email; $searchRows[$contactID]['phone'] = $result->phone; } } foreach ($searchRows as $cid => $row) { $searchRows[$cid]['check'] = '<input type="checkbox" id="contact_check[' . $cid . ']" name="contact_check[' . $cid . ']" value=' . $cid . ' />'; if ($typeName == 'Employee of') { $searchRows[$cid]['employee_of'] = '<input type="radio" name="employee_of" value=' . $cid . ' >'; } elseif ($typeName == 'Employer of') { $searchRows[$cid]['employer_of'] = '<input type="checkbox" name="employer_of[' . $cid . ']" value=' . $cid . ' />'; } } $selectorElements = array('check', 'name'); if ($typeName == 'Employee of') { $selectorElements[] = 'employee_of'; } elseif ($typeName == 'Employer of') { $selectorElements[] = 'employer_of'; } $selectorElements = array_merge($selectorElements, array('city', 'state', 'email', 'phone')); $iFilteredTotal = $iTotal; echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); CRM_Utils_System::civiExit(); }
/** * 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 = $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(); $websiteTypes = CRM_Core_PseudoConstant::websiteType(); $multipleFields = array('url'); $nullIndex = $nullValueIndex = ' '; //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']; //handle for the label not set for the field if (empty($field['title'])) { $index = $nullIndex; $nullIndex .= $nullIndex; } //handle the case to avoid re-write where the profile field labels are the same if (CRM_Utils_Array::value($index, $values)) { $index .= $nullValueIndex; $nullValueIndex .= $nullValueIndex; } $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 = $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 === 'preferred_language') { $languages = CRM_Core_PseudoConstant::languages(); $params[$index] = $details->{$name}; $values[$index] = $languages[$details->{$name}]; } else { if ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true); $title = $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 == 'image_URL') { list($width, $height) = getimagesize($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>"; } 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 (!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}; } 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}; } } } else { $detailName = "website-{$id}-{$fieldName}"; $url = CRM_Utils_System::fixURL($details->{$detailName}); $websiteTypeId = "website-{$id}-website_type_id"; $websiteType = $websiteTypes[$details->{$websiteTypeId}]; if ($details->{$detailName}) { $values[$index] = "<a href=\"{$url}\">{$details->{$detailName}} ( {$websiteType} )</a>"; } else { $values[$index] = ''; } } } } 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) { $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>'; } } } } }
/** * @param $params * @param $action * @param $sortID * @param null $displayRelationshipType * @param string $queryOperator * * @return CRM_Contact_DAO_Contact */ function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') { $sortOrder =& $this->getSortOrder($this->_action); $sort = new CRM_Utils_Sort($sortOrder, $sortID); // rectify params to what proximity search expects if there is a value for prox_distance // CRM-7021 CRM-7905 if (!empty($params)) { CRM_Contact_BAO_ProximityQuery::fixInputParams($params); } if (!$displayRelationshipType) { $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties, NULL, FALSE, FALSE, 1, FALSE, TRUE, TRUE, NULL, $queryOperator); } else { $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties, NULL, FALSE, FALSE, 1, FALSE, TRUE, TRUE, $displayRelationshipType, $queryOperator); } $value = $query->searchQuery(0, 0, $sort, FALSE, FALSE, FALSE, FALSE, FALSE); return $value; }
/** * Common pre-process function. * * @param CRM_Core_Form $form * @param bool $useTable */ public static function preProcessCommon(&$form, $useTable = FALSE) { $form->_activityHolderIds = array(); $values = $form->controller->exportValues($form->get('searchFormName')); $form->_task = $values['task']; $activityTasks = CRM_Activity_Task::tasks(); $form->assign('taskName', $activityTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_ACTIVITY); $query->_distinctComponentClause = '( civicrm_activity.id )'; $query->_groupByComponentClause = " GROUP BY civicrm_activity.id "; // CRM-12675 $activityClause = NULL; $components = CRM_Core_Component::getNames(); $componentClause = array(); foreach ($components as $componentID => $componentName) { if (!CRM_Core_Permission::check("access {$componentName}")) { $componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) "; } } if (!empty($componentClause)) { $activityClause = implode(' AND ', $componentClause); } $result = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $activityClause); while ($result->fetch()) { if (!empty($result->activity_id)) { $ids[] = $result->activity_id; } } } if (!empty($ids)) { $form->_componentClause = ' civicrm_activity.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedActivities', count($ids)); } $form->_activityHolderIds = $form->_componentIds = $ids; // Set the context for redirection for any task actions. $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $session = CRM_Core_Session::singleton(); $searchFormName = strtolower($form->get('searchFormName')); if ($searchFormName == 'search') { $session->replaceUserContext(CRM_Utils_System::url('civicrm/activity/search', $urlParams)); } else { $session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/{$searchFormName}", $urlParams)); } }
/** * This function is to get the result of the search for contact in relationship form * * @param array $params This contains elements for search criteria * * @access public * @return None * */ function search(&$params) { //max records that will be listed $searchValues = array(); if (CRM_Utils_Array::value('rel_contact', $params)) { if (is_numeric($params['rel_contact_id'])) { $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1); } else { $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1); } } $contactTypeAdded = false; $excludedContactIds = array($this->_contactId); if ($params['relationship_type_id']) { $relationshipType = new CRM_Contact_DAO_RelationshipType(); list($rid, $direction) = explode('_', $params['relationship_type_id'], 2); $relationshipType->id = $rid; if ($relationshipType->find(true)) { if ($direction == 'a_b') { $type = $relationshipType->contact_type_b; $subType = $relationshipType->contact_sub_type_b; } else { $type = $relationshipType->contact_type_a; $subType = $relationshipType->contact_sub_type_a; } $this->set('contact_type', $type); $this->set('contact_sub_type', $subType); if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') { $searchValues[] = array('contact_type', '=', $type, 0, 0); $contactTypeAdded = true; } if ($subType) { $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0); } } } if (!$contactTypeAdded && CRM_Utils_Array::value('contact_type', $params)) { $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0); } // get the count of contact $contactBAO = new CRM_Contact_BAO_Contact(); $query = new CRM_Contact_BAO_Query($searchValues); $searchCount = $query->searchQuery(0, 0, null, true); $this->set('searchCount', $searchCount); if ($searchCount <= self::MAX_RELATIONSHIPS) { // get the result of the search $result = $query->searchQuery(0, 50, null); $config = CRM_Core_Config::singleton(); $searchRows = array(); //variable is set if only one record is foun and that record already has relationship with the contact $duplicateRelationship = 0; while ($result->fetch()) { $contactID = $result->contact_id; if (in_array($contactID, $excludedContactIds)) { $duplicateRelationship++; continue; } $duplicateRelationship = 0; $searchRows[$contactID]['id'] = $contactID; $searchRows[$contactID]['name'] = $result->sort_name; $searchRows[$contactID]['city'] = $result->city; $searchRows[$contactID]['state'] = $result->state_province; $searchRows[$contactID]['email'] = $result->email; $searchRows[$contactID]['phone'] = $result->phone; $contact_type = '<img src="' . $config->resourceBase . 'i/contact_'; require_once 'CRM/Contact/BAO/Contact/Utils.php'; $searchRows[$contactID]['type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type); } $this->set('searchRows', $searchRows); $this->set('duplicateRelationship', $duplicateRelationship); } else { // resetting the session variables if many records are found $this->set('searchRows', null); $this->set('duplicateRelationship', null); } }
/** * Get the result of the search for Add to * forms. * * @param CRM_Core_Form $form * @param array $params * This contains elements for search criteria. */ public function search(&$form, &$params) { //max records that will be listed $searchValues = array(); if (!empty($params['rel_contact'])) { if (isset($params['rel_contact_id']) && is_numeric($params['rel_contact_id'])) { $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1); } else { $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1); } } $contactTypeAdded = FALSE; $excludedContactIds = array(); if (isset($form->_contactId)) { $excludedContactIds[] = $form->_contactId; } if (!empty($params['relationship_type_id'])) { $relationshipType = new CRM_Contact_DAO_RelationshipType(); list($rid, $direction) = explode('_', $params['relationship_type_id'], 2); $relationshipType->id = $rid; if ($relationshipType->find(TRUE)) { if ($direction == 'a_b') { $type = $relationshipType->contact_type_b; $subType = $relationshipType->contact_sub_type_b; } else { $type = $relationshipType->contact_type_a; $subType = $relationshipType->contact_sub_type_a; } $form->set('contact_type', $type); $form->set('contact_sub_type', $subType); if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') { $searchValues[] = array('contact_type', '=', $type, 0, 0); $contactTypeAdded = TRUE; } if ($subType) { $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0); } } } if (!$contactTypeAdded && !empty($params['contact_type'])) { $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0); } // get the count of contact $contactBAO = new CRM_Contact_BAO_Contact(); $query = new CRM_Contact_BAO_Query($searchValues); $searchCount = $query->searchQuery(0, 0, NULL, TRUE); $form->set('searchCount', $searchCount); if ($searchCount <= 50) { // get the result of the search $result = $query->searchQuery(0, 50, NULL); $config = CRM_Core_Config::singleton(); $searchRows = array(); //variable is set if only one record is foun and that record already has relationship with the contact $duplicateRelationship = 0; while ($result->fetch()) { $query->convertToPseudoNames($result); $contactID = $result->contact_id; if (in_array($contactID, $excludedContactIds)) { $duplicateRelationship++; continue; } $duplicateRelationship = 0; $searchRows[$contactID]['id'] = $contactID; $searchRows[$contactID]['name'] = $result->sort_name; $searchRows[$contactID]['city'] = $result->city; $searchRows[$contactID]['state'] = $result->state_province; $searchRows[$contactID]['email'] = $result->email; $searchRows[$contactID]['phone'] = $result->phone; $contact_type = '<img src="' . $config->resourceBase . 'i/contact_'; $searchRows[$contactID]['type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type); } $form->set('searchRows', $searchRows); $form->set('duplicateRelationship', $duplicateRelationship); } else { // resetting the session variables if many records are found $form->set('searchRows', NULL); $form->set('duplicateRelationship', NULL); } }
/** * CRM-14263 search builder failure with search profile & address in criteria * We are retrieving primary here - checking the actual sql seems super prescriptive - but since the massive query object has * so few tests detecting any change seems good here :-) */ public function testSearchProfilePrimaryCityCRM14263() { $contactID = $this->individualCreate(); CRM_Core_Config::singleton()->defaultSearchProfileID = 1; $this->callAPISuccess('address', 'create', array('contact_id' => $contactID, 'city' => 'Cool City', 'location_type_id' => 1)); $params = array(0 => array(0 => 'city', 1 => '=', 2 => 'Cool City', 3 => 1, 4 => 0)); $returnProperties = array('contact_type' => 1, 'contact_sub_type' => 1, 'sort_name' => 1); $expectedSQL = "SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`, civicrm_address.id as address_id, civicrm_address.city as `city` FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 ) WHERE ( ( LOWER(civicrm_address.city) = 'cool city' ) ) AND (contact_a.is_deleted = 0) ORDER BY contact_a.sort_name asc, contact_a.id "; $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties); try { $this->assertEquals($expectedSQL, $queryObj->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, TRUE)); } catch (PEAR_Exception $e) { $err = $e->getCause(); $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo); } }
static function preProcessCommon(&$form, $useTable = false) { $form->_participantIds = array(); $values = $form->controller->exportValues($form->get('searchFormName')); $form->_task = $values['task']; $eventTasks = CRM_Event_Task::tasks(); $form->assign('taskName', $eventTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $sortOrder = null; if ($form->get(CRM_Utils_Sort::SORT_ORDER)) { $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER); } $query = new CRM_Contact_BAO_Query($queryParams, null, null, false, false, CRM_Contact_BAO_Query::MODE_EVENT); $result = $query->searchQuery(0, 0, $sortOrder); while ($result->fetch()) { $ids[] = $result->participant_id; } } if (!empty($ids)) { $form->_componentClause = ' civicrm_participant.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedParticipants', count($ids)); } $form->_participantIds = $form->_componentIds = $ids; //set the context for redirection for any task actions $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this); require_once 'CRM/Utils/Rule.php'; $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $searchFormName = strtolower($form->get('searchFormName')); if ($searchFormName == 'search') { $session->replaceUserContext(CRM_Utils_System::url('civicrm/event/search', $urlParams)); } else { $session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/{$searchFormName}", $urlParams)); } }
/** * load the smart group cache for a saved search */ static function load(&$group, $fresh = FALSE) { $groupID = $group->id; $savedSearchID = $group->saved_search_id; if (array_key_exists($groupID, self::$_alreadyLoaded) && !$fresh) { return; } self::$_alreadyLoaded[$groupID] = 1; $sql = NULL; $idName = 'id'; $customClass = NULL; if ($savedSearchID) { $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID); // rectify params to what proximity search expects if there is a value for prox_distance // CRM-7021 if (!empty($ssParams)) { CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams); } $returnProperties = array(); if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) { $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv); } if (isset($ssParams['customSearchID'])) { // if custom search // we split it up and store custom class // so temp tables are not destroyed if they are used // hence customClass is defined above at top of function $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID); $searchSQL = $customClass->contactIDs(); $idName = 'contact_id'; } else { $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); $query = new CRM_Contact_BAO_Query($ssParams, $returnProperties, NULL, FALSE, FALSE, 1, TRUE, TRUE, FALSE, CRM_Utils_Array::value('display_relationship_type', $formValues), CRM_Utils_Array::value('operator', $formValues, 'AND')); $query->_useDistinct = FALSE; $query->_useGroupBy = FALSE; $searchSQL = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, TRUE, TRUE, NULL, NULL, NULL, TRUE); } $groupID = CRM_Utils_Type::escape($groupID, 'Integer'); $sql = $searchSQL . " AND contact_a.id NOT IN (\n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.status = 'Removed'\n AND civicrm_group_contact.group_id = {$groupID} ) "; } if ($sql) { $sql = preg_replace("/^\\s*SELECT/", "SELECT {$groupID} as group_id, ", $sql); } // lets also store the records that are explicitly added to the group // this allows us to skip the group contact LEFT JOIN $sqlB = "\nSELECT {$groupID} as group_id, contact_id as {$idName}\nFROM civicrm_group_contact\nWHERE civicrm_group_contact.status = 'Added'\n AND civicrm_group_contact.group_id = {$groupID} "; $groupIDs = array($groupID); self::remove($groupIDs); foreach (array($sql, $sqlB) as $selectSql) { if (!$selectSql) { continue; } $insertSql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) ({$selectSql});"; $processed = TRUE; // FIXME $result = CRM_Core_DAO::executeQuery($insertSql); } self::updateCacheTime($groupIDs, $processed); if ($group->children) { //Store a list of contacts who are removed from the parent group $sql = "\nSELECT contact_id\nFROM civicrm_group_contact\nWHERE civicrm_group_contact.status = 'Removed'\nAND civicrm_group_contact.group_id = {$groupID} "; $dao = CRM_Core_DAO::executeQuery($sql); $removed_contacts = array(); while ($dao->fetch()) { $removed_contacts[] = $dao->contact_id; } $childrenIDs = explode(',', $group->children); foreach ($childrenIDs as $childID) { $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE); //Unset each contact that is removed from the parent group foreach ($removed_contacts as $removed_contact) { unset($contactIDs[$removed_contact]); } $values = array(); foreach ($contactIDs as $contactID => $dontCare) { $values[] = "({$groupID},{$contactID})"; } self::store($groupIDs, $values); } } }
function contactIDQuery($params, $action, $sortID) { $sortOrder =& $this->getSortOrder($this->_action); $sort = new CRM_Utils_Sort($sortOrder, $sortID); $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties); $value = $query->searchQuery(0, 0, $sort, false, false, false, false, false); return $value; }
function voterList() { $searchParams = array('city', 'sort_name', 'street_unit', 'street_name', 'postal_code', 'street_number', 'street_address', 'survey_interviewer_id', 'campaign_survey_id', 'campaign_search_voter_for'); $params = $searchRows = array(); foreach ($searchParams as $param) { if (CRM_Utils_Array::value($param, $_POST)) { $params[$param] = $_POST[$param]; } } $voterClauseParams = array(); foreach (array('campaign_survey_id', 'survey_interviewer_id', 'campaign_search_voter_for') as $fld) { $voterClauseParams[$fld] = CRM_Utils_Array::value($fld, $params); } $interviewerId = $surveyTypeId = $surveyId = null; $searchVoterFor = $params['campaign_search_voter_for']; if ($searchVoterFor == 'reserve') { if (CRM_Utils_Array::value('campaign_survey_id', $params)) { require_once 'CRM/Campaign/DAO/Survey.php'; $survey = new CRM_Campaign_DAO_Survey(); $survey->id = $surveyId = $params['campaign_survey_id']; $survey->selectAdd('campaign_id, activity_type_id'); $survey->find(true); $campaignId = $survey->campaign_id; $surveyTypeId = $survey->activity_type_id; if ($campaignId) { require_once 'CRM/Campaign/BAO/Campaign.php'; $campaignGroups = CRM_Campaign_BAO_Campaign::getCampaignGroups($campaignId); foreach ($campaignGroups as $id => $group) { if ($group['entity_table'] == 'civicrm_group') { $params['group'][$group['entity_id']] = 1; } } } unset($params['campaign_survey_id']); } unset($params['survey_interviewer_id']); } else { //get the survey status in where clause. require_once 'CRM/Core/PseudoConstant.php'; $scheduledStatusId = array_search('Scheduled', CRM_Core_PseudoConstant::activityStatus('name')); if ($scheduledStatusId) { $params['survey_status_id'] = $scheduledStatusId; } //BAO/Query knows reserve/release/interview processes. if ($params['campaign_search_voter_for'] == 'gotv') { $params['campaign_search_voter_for'] = 'release'; } } $selectorCols = array('sort_name', 'street_address', 'street_name', 'street_number', 'street_unit'); // get the data table params. $dataTableParams = array('sEcho' => array('name' => 'sEcho', 'type' => 'Integer', 'default' => 0), 'offset' => array('name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0), 'rowCount' => array('name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25), 'sort' => array('name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'sort_name'), 'sortOrder' => array('name' => 'sSortDir_0', 'type' => 'String', 'default' => 'asc')); foreach ($dataTableParams as $pName => $pValues) { ${$pName} = $pValues['default']; if (CRM_Utils_Array::value($pValues['name'], $_POST)) { ${$pName} = CRM_Utils_Type::escape($_POST[$pValues['name']], $pValues['type']); if ($pName == 'sort') { ${$pName} = $selectorCols[${$pName}]; } } } require_once 'CRM/Contact/BAO/Query.php'; $queryParams = CRM_Contact_BAO_Query::convertFormValues($params); $query = new CRM_Contact_BAO_Query($queryParams, null, null, false, false, CRM_Contact_BAO_Query::MODE_CAMPAIGN); //get the voter clause to restrict and validate search. require_once 'CRM/Campaign/BAO/Query.php'; $voterClause = CRM_Campaign_BAO_Query::voterClause($voterClauseParams); $searchCount = $query->searchQuery(0, 0, null, true, false, false, false, false, $voterClause); $iTotal = $searchCount; $selectorCols = array('contact_type', 'sort_name', 'street_address', 'street_name', 'street_number', 'street_unit'); $extraVoterColName = 'is_interview_conducted'; if ($params['campaign_search_voter_for'] = 'reserve') { $extraVoterColName = 'reserve_voter'; } if ($searchCount > 0) { if ($searchCount < $offset) { $offset = 0; } require_once 'CRM/Contact/BAO/Contact/Utils.php'; $config = CRM_Core_Config::singleton(); // get the result of the search $result = $query->searchQuery($offset, $rowCount, $sort, false, false, false, false, false, $voterClause, $sortOrder); while ($result->fetch()) { $contactID = $result->contact_id; $typeImage = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, false, $result->contact_id); $searchRows[$contactID] = array('id' => $contactID); foreach ($selectorCols as $col) { $val = $result->{$col}; if ($col == 'contact_type') { $val = $typeImage; } $searchRows[$contactID][$col] = $val; } if ($searchVoterFor == 'reserve') { $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $contactID . ']" name="survey_activity[' . $contactID . ']" value=' . $contactID . ' onClick="processVoterData( this, \'reserve\' );" />'; $msg = ts('Respondent Reserved.'); $voterExtraColHtml .= " <span id='success_msg_{$contactID}' class='ok' style='display:none;'>{$msg}</span>"; } else { if ($searchVoterFor == 'gotv') { $surveyActId = $result->survey_activity_id; $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $surveyActId . ']" name="survey_activity[' . $surveyActId . ']" value=' . $surveyActId . ' onClick="processVoterData( this, \'gotv\' );" />'; $msg = ts('Vote Recorded'); $voterExtraColHtml .= " <span id='success_msg_{$surveyActId}' class='ok' style='display:none;'>{$msg}</span>"; } else { $surveyActId = $result->survey_activity_id; $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $surveyActId . ']" name="survey_activity[' . $surveyActId . ']" value=' . $surveyActId . ' onClick="processVoterData( this, \'release\' );" />'; $msg = ts('Vote Recorded'); $voterExtraColHtml .= " <span id='success_msg_{$surveyActId}' class='ok' style='display:none;'>{$msg}</span>"; } } $searchRows[$contactID][$extraVoterColName] = $voterExtraColHtml; } } require_once "CRM/Utils/JSON.php"; $selectorElements = array_merge($selectorCols, array($extraVoterColName)); $iFilteredTotal = $iTotal; echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); CRM_Utils_System::civiExit(); }
public function voterList() { //get the search criteria params. $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $searchParams = explode(',', $searchCriteria); $params = $searchRows = array(); foreach ($searchParams as $param) { if (!empty($_POST[$param])) { $params[$param] = $_POST[$param]; } } //format multi-select group and contact types. foreach (array('group', 'contact_type') as $param) { $paramValue = CRM_Utils_Array::value($param, $params); if ($paramValue) { unset($params[$param]); $paramValue = explode(',', $paramValue); foreach ($paramValue as $key => $value) { $params[$param][$value] = 1; } } } $voterClauseParams = array(); foreach (array('campaign_survey_id', 'survey_interviewer_id', 'campaign_search_voter_for') as $fld) { $voterClauseParams[$fld] = CRM_Utils_Array::value($fld, $params); } $interviewerId = $surveyTypeId = $surveyId = NULL; $searchVoterFor = $params['campaign_search_voter_for']; if ($searchVoterFor == 'reserve') { if (!empty($params['campaign_survey_id'])) { $survey = new CRM_Campaign_DAO_Survey(); $survey->id = $surveyId = $params['campaign_survey_id']; $survey->selectAdd('campaign_id, activity_type_id'); $survey->find(TRUE); $campaignId = $survey->campaign_id; $surveyTypeId = $survey->activity_type_id; //allow voter search in sub-part of given constituents, //but make sure in case user does not select any group. //get all associated campaign groups in where filter, CRM-7406 $groups = CRM_Utils_Array::value('group', $params); if ($campaignId && CRM_Utils_System::isNull($groups)) { $campaignGroups = CRM_Campaign_BAO_Campaign::getCampaignGroups($campaignId); foreach ($campaignGroups as $id => $group) { $params['group'][$id] = 1; } } //apply filter of survey contact type for search. $contactType = CRM_Campaign_BAO_Survey::getSurveyContactType($surveyId); if ($contactType) { $params['contact_type'][$contactType] = 1; } unset($params['campaign_survey_id']); } unset($params['survey_interviewer_id']); } else { //get the survey status in where clause. $scheduledStatusId = array_search('Scheduled', CRM_Core_PseudoConstant::activityStatus('name')); if ($scheduledStatusId) { $params['survey_status_id'] = $scheduledStatusId; } //BAO/Query knows reserve/release/interview processes. if ($params['campaign_search_voter_for'] == 'gotv') { $params['campaign_search_voter_for'] = 'release'; } } $selectorCols = array('sort_name', 'street_address', 'street_name', 'street_number', 'street_unit'); // get the data table params. $dataTableParams = array('sEcho' => array('name' => 'sEcho', 'type' => 'Integer', 'default' => 0), 'offset' => array('name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0), 'rowCount' => array('name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25), 'sort' => array('name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'sort_name'), 'sortOrder' => array('name' => 'sSortDir_0', 'type' => 'String', 'default' => 'asc')); foreach ($dataTableParams as $pName => $pValues) { ${$pName} = $pValues['default']; if (!empty($_POST[$pValues['name']])) { ${$pName} = CRM_Utils_Type::escape($_POST[$pValues['name']], $pValues['type']); if ($pName == 'sort') { ${$pName} = $selectorCols[${$pName}]; } } } $queryParams = CRM_Contact_BAO_Query::convertFormValues($params); $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CAMPAIGN, TRUE); //get the voter clause to restrict and validate search. $voterClause = CRM_Campaign_BAO_Query::voterClause($voterClauseParams); $searchCount = $query->searchQuery(0, 0, NULL, TRUE, FALSE, FALSE, FALSE, FALSE, CRM_Utils_Array::value('whereClause', $voterClause), NULL, CRM_Utils_Array::value('fromClause', $voterClause)); $iTotal = $searchCount; $selectorCols = array('contact_type', 'sort_name', 'street_address', 'street_name', 'street_number', 'street_unit'); $extraVoterColName = 'is_interview_conducted'; if ($params['campaign_search_voter_for'] == 'reserve') { $extraVoterColName = 'reserve_voter'; } if ($searchCount > 0) { if ($searchCount < $offset) { $offset = 0; } $config = CRM_Core_Config::singleton(); // get the result of the search $result = $query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, CRM_Utils_Array::value('whereClause', $voterClause), $sortOrder, CRM_Utils_Array::value('fromClause', $voterClause)); while ($result->fetch()) { $contactID = $result->contact_id; $typeImage = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $searchRows[$contactID] = array('id' => $contactID); foreach ($selectorCols as $col) { $val = $result->{$col}; if ($col == 'contact_type') { $val = $typeImage; } $searchRows[$contactID][$col] = $val; } if ($searchVoterFor == 'reserve') { $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $contactID . ']" name="survey_activity[' . $contactID . ']" value=' . $contactID . ' onClick="processVoterData( this, \'reserve\' );" />'; $msg = ts('Respondent Reserved.'); $voterExtraColHtml .= " <span id='success_msg_{$contactID}' class='ok' style='display:none;'>{$msg}</span>"; } elseif ($searchVoterFor == 'gotv') { $surveyActId = $result->survey_activity_id; $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $surveyActId . ']" name="survey_activity[' . $surveyActId . ']" value=' . $surveyActId . ' onClick="processVoterData( this, \'gotv\' );" />'; $msg = ts('Vote Recorded.'); $voterExtraColHtml .= " <span id='success_msg_{$surveyActId}' class='ok' style='display:none;'>{$msg}</span>"; } else { $surveyActId = $result->survey_activity_id; $voterExtraColHtml = '<input type="checkbox" id="survey_activity[' . $surveyActId . ']" name="survey_activity[' . $surveyActId . ']" value=' . $surveyActId . ' onClick="processVoterData( this, \'release\' );" />'; $msg = ts('Vote Recorded.'); $voterExtraColHtml .= " <span id='success_msg_{$surveyActId}' class='ok' style='display:none;'>{$msg}</span>"; } $searchRows[$contactID][$extraVoterColName] = $voterExtraColHtml; } } $selectorElements = array_merge($selectorCols, array($extraVoterColName)); $iFilteredTotal = $iTotal; CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); CRM_Utils_System::civiExit(); }
/** * build all the data structures needed to build the form * * @param * * @return void * @access public */ function preProcess() { $values = $this->controller->exportValues('Search'); $this->_task = $values['task']; $campaignTasks = CRM_Campaign_Task::tasks(); $taskName = CRM_Utils_Array::value($this->_task, $campaignTasks); $this->assign('taskName', $taskName); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $this->get('queryParams'); $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CAMPAIGN, TRUE); $result = $query->searchQuery(0, 0, NULL); while ($result->fetch()) { $ids[] = $result->contact_id; } $this->assign('totalSelectedVoters', $this->get('rowCount')); } if (!empty($ids)) { $this->_componentClause = 'contact_a.id IN ( ' . implode(',', $ids) . ' ) '; $this->assign('totalSelectedVoters', count($ids)); } $this->_voterIds = $this->_contactIds = $this->_componentIds = $ids; $this->assign('totalSelectedContacts', count($this->_contactIds)); //set the context for redirection for any task actions $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= '&qfKey=' . $qfKey; } $session->replaceUserContext(CRM_Utils_System::url('civicrm/survey/search', $urlParams)); }
/** * 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>'; } } } } }
/** * @param CRM_Core_Form $form * @param bool $useTable */ public static function preProcessCommon(&$form, $useTable = FALSE) { $form->_grantIds = array(); $values = $form->controller->exportValues('Search'); $form->_task = $values['task']; $grantTasks = CRM_Grant_Task::tasks(); $form->assign('taskName', $grantTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $sortOrder = NULL; if ($form->get(CRM_Utils_Sort::SORT_ORDER)) { $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER); } $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_GRANT); $query->_distinctComponentClause = ' civicrm_grant.id'; $query->_groupByComponentClause = ' GROUP BY civicrm_grant.id '; $result = $query->searchQuery(0, 0, $sortOrder); while ($result->fetch()) { $ids[] = $result->grant_id; } } if (!empty($ids)) { $form->_componentClause = ' civicrm_grant.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedGrants', count($ids)); } $form->_grantIds = $form->_componentIds = $ids; //set the context for redirection for any task actions $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $session = CRM_Core_Session::singleton(); $session->replaceUserContext(CRM_Utils_System::url('civicrm/grant/search', $urlParams)); }
static function preProcessCommon(&$form, $useTable = FALSE) { $values = $form->controller->exportValues($form->get('searchFormName')); $form->_task = CRM_Utils_Array::value('task', $values); $mailingTasks = CRM_Mailing_Task::tasks(); $form->assign('taskName', CRM_Utils_Array::value('task', $values)); // ids are mailing event queue ids $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $sortOrder = null; if ($form->get(CRM_Utils_Sort::SORT_ORDER)) { $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER); } $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_MAILING); $result = $query->searchQuery(0, 0, $sortOrder); while ($result->fetch()) { $ids[] = $result->mailing_recipients_id; } $form->assign('totalSelectedMailingRecipients', $form->get('rowCount')); } if (!empty($ids)) { $form->_componentClause = ' civicrm_mailing_recipients.id IN ( ' . implode(',', $ids) . ' ) '; } //set the context for redirection for any task actions $session = CRM_Core_Session::singleton(); $fragment = 'search'; if ($form->_action == CRM_Core_Action::ADVANCED) { $fragment .= '/advanced'; } $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams); $session = CRM_Core_Session::singleton(); $session->replaceUserContext($url); }
/** * load the smart group cache for a saved search */ static function load(&$group) { $groupID = $group->id; $savedSearchID = $group->saved_search_id; $sql = null; $idName = 'id'; $customClass = null; if ($savedSearchID) { require_once 'CRM/Contact/BAO/SavedSearch.php'; $ssParams =& CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID); $returnProperties = array(); if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) { require_once "CRM/Core/BAO/Mapping.php"; $fv =& CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv); } if (isset($ssParams['customSearchID'])) { // if custom search require_once 'CRM/Contact/BAO/SearchCustom.php'; // we split it up and store custom class // so temp tables are not destroyed if they are used // hence customClass is defined above at top of function $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID); $searchSQL = $customClass->contactIDs(); $idName = 'contact_id'; } else { require_once 'CRM/Contact/BAO/Query.php'; $query = new CRM_Contact_BAO_Query($ssParams, $returnProperties, null, false, false, 1, true, true, false); $query->_useGroupBy = false; $searchSQL =& $query->searchQuery(0, 0, null, false, false, false, true, true, null); } $groupID = CRM_Utils_Type::escape($groupID, 'Integer'); $sql = $searchSQL . " AND contact_a.id NOT IN ( \n SELECT contact_id FROM civicrm_group_contact \n WHERE civicrm_group_contact.status = 'Removed' \n AND civicrm_group_contact.group_id = {$groupID} ) "; } if ($sql) { $sql .= " UNION "; } // lets also store the records that are explicitly added to the group // this allows us to skip the group contact LEFT JOIN $sql .= "\nSELECT contact_id as {$idName}\nFROM civicrm_group_contact\nWHERE civicrm_group_contact.status = 'Added'\n AND civicrm_group_contact.group_id = {$groupID} "; $dao = CRM_Core_DAO::executeQuery($sql); $values = array(); while ($dao->fetch()) { $values[] = "({$groupID},{$dao->{$idName}})"; } $groupIDs = array($groupID); self::remove($groupIDs); self::store($groupIDs, $values); if ($group->children) { require_once 'CRM/Contact/BAO/Group.php'; $childrenIDs = explode(',', $group->children); foreach ($childrenIDs as $childID) { $contactIDs =& CRM_Contact_BAO_Group::getMember($childID, false); $values = array(); foreach ($contactIDs as $contactID => $dontCare) { $values[] = "({$groupID},{$contactID})"; } self::store($groupIDs, $values); } } }
/** * This function is to get the result of the search for membership organisation. * * @param array $params This contains elements for search criteria * * @access public * * @return None * */ function search(&$params) { //max records that will be listed $searchValues = array(); if (!empty($params['member_org'])) { $searchValues[] = array('sort_name', 'LIKE', $params['member_org'], 0, 1); } $searchValues[] = array('contact_type', '=', 'organization', 0, 0); // get the count of contact $contactBAO = new CRM_Contact_BAO_Contact(); $query = new CRM_Contact_BAO_Query($searchValues); $searchCount = $query->searchQuery(0, 0, NULL, TRUE); $this->set('searchCount', $searchCount); if ($searchCount <= self::MAX_CONTACTS) { // get the result of the search $result = $query->searchQuery(0, self::MAX_CONTACTS, NULL); $config = CRM_Core_Config::singleton(); $searchRows = array(); while ($result->fetch()) { $contactID = $result->contact_id; $searchRows[$contactID]['id'] = $contactID; $searchRows[$contactID]['name'] = $result->sort_name; $searchRows[$contactID]['city'] = $result->city; $searchRows[$contactID]['state'] = $result->state_province; $searchRows[$contactID]['email'] = $result->email; $searchRows[$contactID]['phone'] = $result->phone; $contact_type = '<img src="' . $config->resourceBase . 'i/contact_'; $contact_type .= 'org.gif" alt="' . ts('Organization') . '" height="16" width="18" />'; $searchRows[$contactID]['type'] = $contact_type; } $this->set('searchRows', $searchRows); } else { // resetting the session variables if many records are found $this->set('searchRows', NULL); } }
/** * Function to get the list of contacts for a profile * * @param $form object * * @access public */ function getProfileContact($gid) { $session = CRM_Core_Session::singleton(); $params = $session->get('profileParams'); $details = array(); $ufGroupParam = array('id' => $gid); require_once "CRM/Core/BAO/UFGroup.php"; CRM_Core_BAO_UFGroup::retrieve($ufGroupParam, $details); // make sure this group can be mapped if (!$details['is_map']) { CRM_Core_Error::statusBounce(ts('This profile does not have the map feature turned on.')); } $groupId = CRM_Utils_Array::value('limit_listings_group_id', $details); // add group id to params if a uf group belong to a any group if ($groupId) { if (CRM_Utils_Array::value('group', $params)) { $params['group'][$groupId] = 1; } else { $params['group'] = array($groupId => 1); } } $fields = CRM_Core_BAO_UFGroup::getListingFields(CRM_Core_Action::VIEW, CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY, false, $gid); $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); $returnProperties['contact_type'] = 1; $returnProperties['sort_name'] = 1; $queryParams =& CRM_Contact_BAO_Query::convertFormValues($params, 1); $query = new CRM_Contact_BAO_Query($queryParams, $returnProperties, $fields); $ids = $query->searchQuery(0, 0, null, false, false, false, true, false); $contactIds = explode(',', $ids); return $contactIds; }
/** * Load the smart group cache for a saved search. * * @param object $group * The smart group that needs to be loaded. * @param bool $force * Should we force a search through. */ public static function load(&$group, $force = FALSE) { $groupID = $group->id; $savedSearchID = $group->saved_search_id; if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) { return; } // grab a lock so other processes don't compete and do the same query $lock = Civi::lockManager()->acquire("data.core.group.{$groupID}"); if (!$lock->isAcquired()) { // this can cause inconsistent results since we don't know if the other process // will fill up the cache before our calling routine needs it. // however this routine does not return the status either, so basically // its a "lets return and hope for the best" return; } self::$_alreadyLoaded[$groupID] = 1; // we now have the lock, but some other process could have actually done the work // before we got here, so before we do any work, lets ensure that work needs to be // done // we allow hidden groups here since we dont know if the caller wants to evaluate an // hidden group if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) { $lock->release(); return; } $sql = NULL; $idName = 'id'; $customClass = NULL; if ($savedSearchID) { $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID); // rectify params to what proximity search expects if there is a value for prox_distance // CRM-7021 if (!empty($ssParams)) { CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams); } $returnProperties = array(); if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) { $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv); } if (isset($ssParams['customSearchID'])) { // if custom search // we split it up and store custom class // so temp tables are not destroyed if they are used // hence customClass is defined above at top of function $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID); $searchSQL = $customClass->contactIDs(); $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL); if (!strstr($searchSQL, 'WHERE')) { $searchSQL .= " WHERE ( 1 ) "; } $idName = 'contact_id'; } else { $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); // CRM-17075 using the formValues in this way imposes extra logic and complexity. // we have the where_clause and where tables stored in the saved_search table // and should use these rather than re-processing the form criteria (which over-works // the link between the form layer & the query layer too). // It's hard to think of when you would want to use anything other than return // properties = array('contact_id' => 1) here as the point would appear to be to // generate the list of contact ids in the group. // @todo review this to use values in saved_search table (preferably for 4.8). $query = new CRM_Contact_BAO_Query($ssParams, $returnProperties, NULL, FALSE, FALSE, 1, TRUE, TRUE, FALSE, CRM_Utils_Array::value('display_relationship_type', $formValues), CRM_Utils_Array::value('operator', $formValues, 'AND')); $query->_useDistinct = FALSE; $query->_useGroupBy = FALSE; $searchSQL = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, TRUE, TRUE, NULL, NULL, NULL, TRUE); } $groupID = CRM_Utils_Type::escape($groupID, 'Integer'); $sql = $searchSQL . " AND contact_a.id NOT IN (\n SELECT contact_id FROM civicrm_group_contact\n WHERE civicrm_group_contact.status = 'Removed'\n AND civicrm_group_contact.group_id = {$groupID} ) "; } if ($sql) { $sql = preg_replace("/^\\s*SELECT/", "SELECT {$groupID} as group_id, ", $sql); } // lets also store the records that are explicitly added to the group // this allows us to skip the group contact LEFT JOIN $sqlB = "\nSELECT {$groupID} as group_id, contact_id as {$idName}\nFROM civicrm_group_contact\nWHERE civicrm_group_contact.status = 'Added'\n AND civicrm_group_contact.group_id = {$groupID} "; $groupIDs = array($groupID); self::remove($groupIDs); $processed = FALSE; $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000); foreach (array($sql, $sqlB) as $selectSql) { if (!$selectSql) { continue; } $insertSql = "CREATE TEMPORARY TABLE {$tempTable} ({$selectSql});"; $processed = TRUE; CRM_Core_DAO::executeQuery($insertSql); CRM_Core_DAO::executeQuery("INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)\n SELECT DISTINCT {$idName}, group_id FROM {$tempTable}\n "); CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE {$tempTable}"); } self::updateCacheTime($groupIDs, $processed); if ($group->children) { //Store a list of contacts who are removed from the parent group $sql = "\nSELECT contact_id\nFROM civicrm_group_contact\nWHERE civicrm_group_contact.status = 'Removed'\nAND civicrm_group_contact.group_id = {$groupID} "; $dao = CRM_Core_DAO::executeQuery($sql); $removed_contacts = array(); while ($dao->fetch()) { $removed_contacts[] = $dao->contact_id; } $childrenIDs = explode(',', $group->children); foreach ($childrenIDs as $childID) { $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE); //Unset each contact that is removed from the parent group foreach ($removed_contacts as $removed_contact) { unset($contactIDs[$removed_contact]); } $values = array(); foreach ($contactIDs as $contactID => $dontCare) { $values[] = "({$groupID},{$contactID})"; } self::store($groupIDs, $values); } } $lock->release(); }
/** * Returns the number of Contact objects which match the search criteria specified in $params. * * @deprecated deprecated since version 2.2.3; civicrm_contact_get now returns a record_count value * * @param array $params * * @return int * @access public */ function civicrm_contact_search_count(&$params) { // convert the params to new format require_once 'CRM/Contact/Form/Search.php'; $newP = CRM_Contact_BAO_Query::convertFormValues($params); $query = new CRM_Contact_BAO_Query($newP); return $query->searchQuery(0, 0, NULL, TRUE); }
static function preProcessCommon(&$form, $useTable = FALSE) { $form->_caseIds = array(); $values = $form->controller->exportValues($form->get('searchFormName')); $form->_task = $values['task']; $caseTasks = CRM_Case_Task::tasks(); $form->assign('taskName', $caseTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CASE); $query->_distinctComponentClause = " ( civicrm_case.id )"; $query->_groupByComponentClause = " GROUP BY civicrm_case.id "; $result = $query->searchQuery(0, 0, NULL); while ($result->fetch()) { $ids[] = $result->case_id; } } if (!empty($ids)) { $form->_componentClause = ' civicrm_case.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedCases', count($ids)); } $form->_caseIds = $form->_componentIds = $ids; //set the context for redirection for any task actions $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form); $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $session = CRM_Core_Session::singleton(); $searchFormName = strtolower($form->get('searchFormName')); if ($searchFormName == 'search') { $session->replaceUserContext(CRM_Utils_System::url('civicrm/case/search', $urlParams)); } else { $session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/{$searchFormName}", $urlParams)); } }
static function preProcessCommon(&$form, $useTable = false) { $form->_memberIds = array(); $values = $form->controller->exportValues('Search'); $form->_task = $values['task']; $memberTasks = CRM_Member_Task::tasks(); $form->assign('taskName', $memberTasks[$form->_task]); $ids = array(); if ($values['radio_ts'] == 'ts_sel') { foreach ($values as $name => $value) { if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { $ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN); } } } else { $queryParams = $form->get('queryParams'); $query = new CRM_Contact_BAO_Query($queryParams, null, null, false, false, CRM_Contact_BAO_Query::MODE_MEMBER); $result = $query->searchQuery(0, 0, null); while ($result->fetch()) { $ids[] = $result->membership_id; } } if (!empty($ids)) { $form->_componentClause = ' civicrm_membership.id IN ( ' . implode(',', $ids) . ' ) '; $form->assign('totalSelectedMembers', count($ids)); } $form->_memberIds = $form->_componentIds = $ids; //set the context for redirection for any task actions $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form); require_once 'CRM/Utils/Rule.php'; $urlParams = 'force=1'; if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/search', $urlParams)); }