3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for search-result tasks.
21 class CRM_Contact_Form_Task
extends CRM_Core_Form_Task
{
24 * The task being performed
31 * The array that holds all the contact ids
38 * The array that holds all the contact types
42 public $_contactTypes;
45 * The additional clause that we restrict the search with
49 protected $_componentClause = NULL;
52 * The name of the temp table where we store the contact IDs
56 protected $_componentTable = NULL;
59 * The array that holds all the component ids
63 protected $_componentIds;
66 * This includes the submitted values of the search form
69 static protected $_searchFormValues;
72 * Build all the data structures needed to build the form.
74 public function preProcess() {
75 self
::preProcessCommon($this);
79 * Common pre-processing function.
81 * @param \CRM_Core_Form_Task $form
83 * @throws \CRM_Core_Exception
85 public static function preProcessCommon(&$form) {
86 $form->_contactIds
= [];
87 $form->_contactTypes
= [];
89 $isStandAlone = in_array('task', $form->urlPath
) ||
in_array('standalone', $form->urlPath
);
91 [$form->_task
, $title] = CRM_Contact_Task
::getTaskAndTitleByClass(get_class($form));
92 if (!array_key_exists($form->_task
, CRM_Contact_Task
::permissionedTaskTitles(CRM_Core_Permission
::getPermission()))) {
93 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
95 $form->_contactIds
= explode(',', CRM_Utils_Request
::retrieve('cids', 'CommaSeparatedIntegers', $form, TRUE));
96 if (empty($form->_contactIds
)) {
97 CRM_Core_Error
::statusBounce(ts('No Contacts Selected'));
99 $form->setTitle($title);
102 // get the submitted values of the search form
103 // we'll need to get fv from either search or adv search in the future
104 $fragment = 'search';
105 if ($form->_action
== CRM_Core_Action
::ADVANCED
) {
106 $fragment .= '/advanced';
108 elseif ($form->_action
== CRM_Core_Action
::PROFILE
) {
109 $fragment .= '/builder';
111 elseif ($form->_action
== CRM_Core_Action
::COPY
) {
112 $fragment .= '/custom';
114 if (!$isStandAlone) {
115 self
::$_searchFormValues = $form->getSearchFormValues();
118 //set the user context for redirection of task actions
119 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String', $form);
120 $urlParams = 'force=1';
121 if (CRM_Utils_Rule
::qfKey($qfKey)) {
122 $urlParams .= "&qfKey=$qfKey";
125 $url = CRM_Utils_System
::url('civicrm/contact/' . $fragment, $urlParams);
126 $session = CRM_Core_Session
::singleton();
127 $session->replaceUserContext($url);
129 $cacheKey = "civicrm search {$qfKey}";
131 $form->_task
= self
::$_searchFormValues['task'] ??
NULL;
132 $crmContactTaskTasks = CRM_Contact_Task
::taskTitles();
133 $form->assign('taskName', CRM_Utils_Array
::value($form->_task
, $crmContactTaskTasks));
135 // all contacts or action = save a search
136 if ((CRM_Utils_Array
::value('radio_ts', self
::$_searchFormValues) == 'ts_all') ||
137 ($form->_task
== CRM_Contact_Task
::SAVE_SEARCH
)
139 // since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
140 // rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
142 $allCids[$cacheKey] = self
::getContactIds($form);
144 $form->_contactIds
= [];
145 if (empty($form->_contactIds
)) {
146 // filter duplicates here
148 // might be better to do this in the query, but that logic is a bit complex
149 // and it decides when to use distinct based on input criteria, which needs
150 // to be fixed and optimized.
152 foreach ($allCids[$cacheKey] as $cid => $ignore) {
153 $form->_contactIds
[] = $cid;
157 elseif (CRM_Utils_Array
::value('radio_ts', self
::$_searchFormValues) == 'ts_sel') {
158 // selected contacts only
159 // need to perform action on only selected contacts
162 // refire sql in case of custom search
163 if ($form->_action
== CRM_Core_Action
::COPY
) {
164 // selected contacts only
165 // need to perform action on only selected contacts
166 foreach (self
::$_searchFormValues as $name => $value) {
167 if (substr($name, 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
168 $form->_contactIds
[] = substr($name, CRM_Core_Form
::CB_PREFIX_LEN
);
173 // fetching selected contact ids of passed cache key
174 $selectedCids = Civi
::service('prevnext')->getSelection($cacheKey);
175 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
176 $form->_contactIds
[] = $selectedCid;
180 if (!empty($insertString)) {
181 $string = implode(',', $insertString);
182 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
183 CRM_Core_DAO
::executeQuery($sql);
187 //contact type for pick up profiles as per selected contact types with subtypes
189 if ($selectedTypes = CRM_Utils_Array
::value('contact_type', self
::$_searchFormValues)) {
190 if (!is_array($selectedTypes)) {
191 $selectedTypes = explode(' ', $selectedTypes);
193 foreach ($selectedTypes as $ct => $dontcare) {
194 if (strpos($ct, CRM_Core_DAO
::VALUE_SEPARATOR
) === FALSE) {
195 $form->_contactTypes
[] = $ct;
198 $separator = strpos($ct, CRM_Core_DAO
::VALUE_SEPARATOR
);
199 $form->_contactTypes
[] = substr($ct, $separator +
1);
204 if (CRM_Utils_Array
::value('radio_ts', self
::$_searchFormValues) == 'ts_sel'
205 && ($form->_action
!= CRM_Core_Action
::COPY
)
207 $sel = self
::$_searchFormValues['radio_ts'] ??
NULL;
208 $form->assign('searchtype', $sel);
209 $result = self
::getSelectedContactNames();
210 $form->assign("value", $result);
213 if (!empty($form->_contactIds
)) {
214 $form->_componentClause
= ' contact_a.id IN ( ' . implode(',', $form->_contactIds
) . ' ) ';
215 $form->assign('totalSelectedContacts', count($form->_contactIds
));
217 $form->_componentIds
= $form->_contactIds
;
222 * Get the contact ids for:
223 * - "Select Records: All xx records"
224 * - custom search (FIXME: does this still apply to custom search?).
225 * When we call this function we are not using the prev/next cache
227 * @param $form CRM_Core_Form
229 * @return array $contactIds
231 public static function getContactIds($form) {
232 // need to perform action on all contacts
233 // fire the query again and get the contact id's + display name
235 if ($form->get(CRM_Utils_Sort
::SORT_ID
)) {
236 $sortID = CRM_Utils_Sort
::sortIDValue($form->get(CRM_Utils_Sort
::SORT_ID
),
237 $form->get(CRM_Utils_Sort
::SORT_DIRECTION
)
241 $selectorName = $form->controller
->selectorName();
243 $fv = $form->get('formValues');
244 $customClass = $form->get('customSearchClass');
245 $returnProperties = CRM_Core_BAO_Mapping
::returnProperties(self
::$_searchFormValues);
247 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
249 $params = $form->get('queryParams');
252 $sortByCharacter = $form->get('sortByCharacter');
253 if ($sortByCharacter && $sortByCharacter != 1) {
254 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
256 $queryOperator = $form->get('queryOperator');
257 if (!$queryOperator) {
258 $queryOperator = 'AND';
260 $dao = $selector->contactIDQuery($params, $sortID,
261 CRM_Utils_Array
::value('display_relationship_type', $fv),
266 while ($dao->fetch()) {
267 $contactIds[$dao->contact_id
] = $dao->contact_id
;
274 * Set default values for the form. Relationship that in edit/view action.
276 * The default values are retrieved from the database.
280 public function setDefaultValues() {
286 * Add the rules for form.
288 public function addRules() {
292 * Build the form object.
294 public function buildQuickForm() {
295 $this->addDefaultButtons(ts('Confirm Action'));
299 * Process the form after the input has been submitted and validated.
301 public function postProcess() {
305 * Simple shell that derived classes can call to add form buttons.
307 * Allows customized title for the main Submit
309 * @param string $title
310 * Title of the main button.
311 * @param string $nextType
312 * Button type for the form after processing.
313 * @param string $backType
314 * @param bool $submitOnce
316 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
325 'name' => ts('Cancel'),
326 'icon' => 'fa-times',
332 * Replace ids of household members in $this->_contactIds with the id of their household.
334 * @see https://issues.civicrm.org/jira/browse/CRM-8338
336 public function mergeContactIdsByHousehold() {
337 if (empty($this->_contactIds
)) {
341 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
351 // Get Head of Household & Household Member relationships
352 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
353 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
354 $householdRelationshipTypes = [
355 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
356 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
359 $relID = implode(',', $this->_contactIds
);
361 foreach ($householdRelationshipTypes as $rel => $dnt) {
362 list($id, $direction) = explode('_', $rel, 2);
363 // identify the relationship direction
364 $contactA = 'contact_id_a';
365 $contactB = 'contact_id_b';
366 if ($direction == 'b_a') {
367 $contactA = 'contact_id_b';
368 $contactB = 'contact_id_a';
371 // Find related households.
372 $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact ";
373 $relationFrom = " FROM civicrm_contact contact_household
374 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_household.id AND crel.relationship_type_id = {$id} ";
376 // Check for active relationship status only.
377 $today = date('Ymd');
378 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
379 $relationWhere = " WHERE contact_household.is_deleted = 0 AND crel.{$contactA} IN ( {$relID} ) {$relationActive}";
380 $relationGroupBy = " GROUP BY crel.{$contactA}, contact_household.id";
381 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationGroupBy";
383 $householdsDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
384 while ($householdsDAO->fetch()) {
385 // Remove contact's id from $this->_contactIds and replace with their household's id.
386 foreach (array_keys($this->_contactIds
, $householdsDAO->refContact
) as $idKey) {
387 unset($this->_contactIds
[$idKey]);
389 if (!in_array($householdsDAO->household_id
, $this->_contactIds
)) {
390 $this->_contactIds
[] = $householdsDAO->household_id
;
395 // If contact list has changed, households will probably be at the end of
396 // the list. Sort it again by sort_name.
397 if (implode(',', $this->_contactIds
) != $relID) {
398 $result = civicrm_api3('Contact', 'get', [
400 'id' => ['IN' => $this->_contactIds
],
403 'sort' => "sort_name",
406 $this->_contactIds
= array_keys($result['values']);
412 * List of contact names.
413 * NOTE: These are raw values from the DB. In current data-model, that means
414 * they are pre-encoded HTML.
416 private static function getSelectedContactNames() {
417 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String');
418 $cacheKey = "civicrm search {$qfKey}";
422 foreach (Civi
::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
423 $cids = array_unique(array_merge($cids, array_keys($values)));
426 $result = CRM_Utils_SQL_Select
::from('civicrm_contact')
427 ->where('id IN (#cids)', ['cids' => $cids])
429 ->fetchMap('id', 'sort_name');
434 * Given this task's list of targets, produce a hidden group.
437 * Array(0 => int $groupID, 1 => int|NULL $ssID).
440 public function createHiddenGroup() {
441 // Did the user select "All" matches or cherry-pick a few records?
442 $searchParams = $this->controller
->exportValues();
443 if ($searchParams['radio_ts'] == 'ts_sel') {
444 // Create a static group.
445 // groups require a unique name
446 $randID = md5(time() . rand(1, 1000));
447 $grpTitle = "Hidden Group {$randID}";
448 $grpID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
452 'title' => $grpTitle,
455 'group_type' => ['2' => 1],
458 $group = CRM_Contact_BAO_Group
::create($groupParams);
461 CRM_Contact_BAO_GroupContact
::addContactsToGroup($this->_contactIds
, $group->id
);
463 $newGroupTitle = "Hidden Group {$grpID}";
466 'name' => CRM_Utils_String
::titleToVar($newGroupTitle),
467 'title' => $newGroupTitle,
468 'group_type' => ['2' => 1],
470 CRM_Contact_BAO_Group
::create($groupParams);
473 // note at this point its a static group
474 return [$grpID, NULL];
477 // Create a smart group.
478 $ssId = $this->get('ssID');
479 $hiddenSmartParams = [
480 'group_type' => ['2' => 1],
481 // queryParams have been preprocessed esp WRT any entity reference fields - see +
482 // https://github.com/civicrm/civicrm-core/pull/13250
483 // Advanced search sets queryParams, for builder you need formValues.
484 // This is kinda fragile but .... see CRM_Mailing_Form_Task_AdhocMailingTest for test effort.
485 // Moral never touch anything ever again and the house of cards will stand tall, unless there is a breeze
486 'form_values' => $this->get('isSearchBuilder') ?
$this->get('formValues') : $this->get('queryParams'),
487 'saved_search_id' => $ssId,
488 'search_custom_id' => $this->get('customSearchID'),
489 'search_context' => $this->get('context'),
492 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group
::createHiddenSmartGroup($hiddenSmartParams);
493 return [$smartGroupId, $savedSearchId];