Merge pull request #18536 from eileenmcnaughton/main
[civicrm-core.git] / CRM / Contact / Form / Task.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
5a409b50 19 * This class generates form components for search-result tasks.
6a488035 20 */
31aaf096 21class CRM_Contact_Form_Task extends CRM_Core_Form_Task {
6a488035
TO
22
23 /**
100fef9d 24 * The task being performed
6a488035
TO
25 *
26 * @var int
27 */
28 protected $_task;
29
30 /**
31 * The array that holds all the contact ids
32 *
33 * @var array
34 */
35 public $_contactIds;
36
37 /**
38 * The array that holds all the contact types
39 *
40 * @var array
41 */
42 public $_contactTypes;
43
44 /**
45 * The additional clause that we restrict the search with
46 *
47 * @var string
48 */
49 protected $_componentClause = NULL;
50
51 /**
52 * The name of the temp table where we store the contact IDs
53 *
54 * @var string
55 */
56 protected $_componentTable = NULL;
57
58 /**
59 * The array that holds all the component ids
60 *
61 * @var array
62 */
63 protected $_componentIds;
64
65 /**
66 * This includes the submitted values of the search form
69078420 67 * @var array
6a488035
TO
68 */
69 static protected $_searchFormValues;
70
71 /**
d8689418 72 * Build all the data structures needed to build the form.
8ef12e64 73 */
00be9182 74 public function preProcess() {
6a488035
TO
75 self::preProcessCommon($this);
76 }
77
86538308 78 /**
d8689418
EM
79 * Common pre-processing function.
80 *
986ac53f 81 * @param \CRM_Core_Form_Task $form
a0174743
MW
82 *
83 * @throws \CRM_Core_Exception
86538308 84 */
2b089ce1 85 public static function preProcessCommon(&$form) {
be2fb01f
CW
86 $form->_contactIds = [];
87 $form->_contactTypes = [];
6a488035 88
78b22ce9 89 $isStandAlone = in_array('task', $form->urlPath) || in_array('standalone', $form->urlPath);
061ff68c 90 if ($isStandAlone) {
986ac53f 91 [$form->_task, $title] = CRM_Contact_Task::getTaskAndTitleByClass(get_class($form));
061ff68c 92 if (!array_key_exists($form->_task, CRM_Contact_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()))) {
f2774867 93 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
061ff68c 94 }
78b22ce9 95 $form->_contactIds = explode(',', CRM_Utils_Request::retrieve('cids', 'CommaSeparatedIntegers', $form, TRUE));
061ff68c 96 if (empty($form->_contactIds)) {
6bc234fa 97 CRM_Core_Error::statusBounce(ts('No Contacts Selected'));
061ff68c 98 }
99 $form->setTitle($title);
100 }
101
6a488035
TO
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) {
6a488035
TO
106 $fragment .= '/advanced';
107 }
108 elseif ($form->_action == CRM_Core_Action::PROFILE) {
6a488035
TO
109 $fragment .= '/builder';
110 }
111 elseif ($form->_action == CRM_Core_Action::COPY) {
6a488035
TO
112 $fragment .= '/custom';
113 }
986ac53f 114 if (!$isStandAlone) {
2d09a0c3 115 self::$_searchFormValues = $form->getSearchFormValues();
6a488035
TO
116 }
117
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";
123 }
124
6a488035
TO
125 $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
126 $session = CRM_Core_Session::singleton();
127 $session->replaceUserContext($url);
128
986ac53f 129 $cacheKey = "civicrm search {$qfKey}";
130
9c1bc317 131 $form->_task = self::$_searchFormValues['task'] ?? NULL;
6a488035
TO
132 $crmContactTaskTasks = CRM_Contact_Task::taskTitles();
133 $form->assign('taskName', CRM_Utils_Array::value($form->_task, $crmContactTaskTasks));
134
6a488035
TO
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)
138 ) {
66ceb5d9 139 // since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
8e1a7c71 140 // rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
141 // final result set
239d4cf8 142 $allCids[$cacheKey] = self::getContactIds($form);
6a488035 143
be2fb01f 144 $form->_contactIds = [];
239d4cf8 145 if (empty($form->_contactIds)) {
6a488035
TO
146 // filter duplicates here
147 // CRM-7058
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.
151
152 foreach ($allCids[$cacheKey] as $cid => $ignore) {
153 $form->_contactIds[] = $cid;
154 }
155 }
156 }
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
be2fb01f 160 $insertString = [];
6a488035 161
b44e3f84 162 // refire sql in case of custom search
6a488035
TO
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) {
239d4cf8 168 $form->_contactIds[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
6a488035
TO
169 }
170 }
171 }
172 else {
5d272ea2 173 // fetching selected contact ids of passed cache key
b7994703 174 $selectedCids = Civi::service('prevnext')->getSelection($cacheKey);
5d272ea2 175 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
239d4cf8 176 $form->_contactIds[] = $selectedCid;
6a488035
TO
177 }
178 }
8ef12e64 179
6a488035
TO
180 if (!empty($insertString)) {
181 $string = implode(',', $insertString);
182 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
183 CRM_Core_DAO::executeQuery($sql);
184 }
185 }
186
187 //contact type for pick up profiles as per selected contact types with subtypes
188 //CRM-5521
189 if ($selectedTypes = CRM_Utils_Array::value('contact_type', self::$_searchFormValues)) {
190 if (!is_array($selectedTypes)) {
191 $selectedTypes = explode(' ', $selectedTypes);
192 }
193 foreach ($selectedTypes as $ct => $dontcare) {
194 if (strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR) === FALSE) {
195 $form->_contactTypes[] = $ct;
196 }
197 else {
198 $separator = strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR);
199 $form->_contactTypes[] = substr($ct, $separator + 1);
200 }
201 }
202 }
203
6a488035 204 if (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel'
5d272ea2 205 && ($form->_action != CRM_Core_Action::COPY)
206 ) {
9c1bc317 207 $sel = self::$_searchFormValues['radio_ts'] ?? NULL;
5d272ea2 208 $form->assign('searchtype', $sel);
0dbe04b1 209 $result = self::getSelectedContactNames();
6a488035
TO
210 $form->assign("value", $result);
211 }
8ef12e64 212
6a488035
TO
213 if (!empty($form->_contactIds)) {
214 $form->_componentClause = ' contact_a.id IN ( ' . implode(',', $form->_contactIds) . ' ) ';
215 $form->assign('totalSelectedContacts', count($form->_contactIds));
216
217 $form->_componentIds = $form->_contactIds;
218 }
219 }
220
221 /**
fe9b66c1
MW
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
d8689418 226 *
fe9b66c1
MW
227 * @param $form CRM_Core_Form
228 *
229 * @return array $contactIds
6a488035 230 */
fe9b66c1 231 public static function getContactIds($form) {
6a488035
TO
232 // need to perform action on all contacts
233 // fire the query again and get the contact id's + display name
234 $sortID = NULL;
fe9b66c1
MW
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)
6a488035
TO
238 );
239 }
240
fe9b66c1 241 $selectorName = $form->controller->selectorName();
6a488035 242
fe9b66c1
MW
243 $fv = $form->get('formValues');
244 $customClass = $form->get('customSearchClass');
6a488035
TO
245 $returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
246
5d272ea2 247 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
6a488035 248
fe9b66c1 249 $params = $form->get('queryParams');
6a488035
TO
250
251 // fix for CRM-5165
fe9b66c1 252 $sortByCharacter = $form->get('sortByCharacter');
a7cddb8c 253 if ($sortByCharacter && $sortByCharacter != 1) {
be2fb01f 254 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
6a488035 255 }
fe9b66c1 256 $queryOperator = $form->get('queryOperator');
6a488035
TO
257 if (!$queryOperator) {
258 $queryOperator = 'AND';
259 }
ae066a2b 260 $dao = $selector->contactIDQuery($params, $sortID,
5d272ea2 261 CRM_Utils_Array::value('display_relationship_type', $fv),
6a488035
TO
262 $queryOperator
263 );
264
be2fb01f 265 $contactIds = [];
5d272ea2 266 while ($dao->fetch()) {
6a488035
TO
267 $contactIds[$dao->contact_id] = $dao->contact_id;
268 }
269
270 return $contactIds;
271 }
272
6a488035 273 /**
ee0ce2ef 274 * Set default values for the form. Relationship that in edit/view action.
6a488035 275 *
ee0ce2ef 276 * The default values are retrieved from the database.
6a488035 277 *
e2046b33 278 * @return array
6a488035 279 */
00be9182 280 public function setDefaultValues() {
be2fb01f 281 $defaults = [];
6a488035
TO
282 return $defaults;
283 }
284
285 /**
57507ae6 286 * Add the rules for form.
6a488035 287 */
00be9182 288 public function addRules() {
5d272ea2 289 }
6a488035
TO
290
291 /**
5c9ff055 292 * Build the form object.
6a488035
TO
293 */
294 public function buildQuickForm() {
295 $this->addDefaultButtons(ts('Confirm Action'));
296 }
297
298 /**
ee0ce2ef 299 * Process the form after the input has been submitted and validated.
6a488035 300 */
5d272ea2 301 public function postProcess() {
302 }
303
6a488035 304 /**
57507ae6
EM
305 * Simple shell that derived classes can call to add form buttons.
306 *
307 * Allows customized title for the main Submit
6a488035 308 *
77c5b619
TO
309 * @param string $title
310 * Title of the main button.
311 * @param string $nextType
312 * Button type for the form after processing.
77b97be7
EM
313 * @param string $backType
314 * @param bool $submitOnce
6a488035 315 */
00be9182 316 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
be2fb01f 317 $this->addButtons([
69078420
SL
318 [
319 'type' => $nextType,
320 'name' => $title,
321 'isDefault' => TRUE,
322 ],
323 [
324 'type' => $backType,
325 'name' => ts('Cancel'),
326 'icon' => 'fa-times',
327 ],
328 ]);
6a488035 329 }
57884c26
DJ
330
331 /**
100fef9d 332 * Replace ids of household members in $this->_contactIds with the id of their household.
57884c26 333 *
0e480632 334 * @see https://issues.civicrm.org/jira/browse/CRM-8338
57884c26
DJ
335 */
336 public function mergeContactIdsByHousehold() {
337 if (empty($this->_contactIds)) {
338 return;
339 }
340
341 $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
342 NULL,
343 NULL,
344 NULL,
345 NULL,
346 TRUE,
347 'name',
348 FALSE
349 );
350
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);
be2fb01f 354 $householdRelationshipTypes = [
57884c26
DJ
355 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
356 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
be2fb01f 357 ];
57884c26
DJ
358
359 $relID = implode(',', $this->_contactIds);
360
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';
369 }
370
371 // Find related households.
353ffa53 372 $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact ";
57884c26
DJ
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} ";
375
376 // Check for active relationship status only.
353ffa53
TO
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}";
0ee5581e 380 $relationGroupBy = " GROUP BY crel.{$contactA}, contact_household.id";
57884c26
DJ
381 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationGroupBy";
382
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]);
388 }
389 if (!in_array($householdsDAO->household_id, $this->_contactIds)) {
390 $this->_contactIds[] = $householdsDAO->household_id;
391 }
392 }
57884c26 393 }
31fd348d
AS
394
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) {
be2fb01f
CW
398 $result = civicrm_api3('Contact', 'get', [
399 'return' => ['id'],
400 'id' => ['IN' => $this->_contactIds],
401 'options' => [
31fd348d 402 'limit' => 0,
351b2dd9 403 'sort' => "sort_name",
be2fb01f
CW
404 ],
405 ]);
31fd348d
AS
406 $this->_contactIds = array_keys($result['values']);
407 }
57884c26 408 }
96025800 409
0dbe04b1
TO
410 /**
411 * @return array
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.
415 */
416 private static function getSelectedContactNames() {
417 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
418 $cacheKey = "civicrm search {$qfKey}";
419
be2fb01f 420 $cids = [];
0dbe04b1
TO
421 // Gymanstic time!
422 foreach (Civi::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
423 $cids = array_unique(array_merge($cids, array_keys($values)));
424 }
425
426 $result = CRM_Utils_SQL_Select::from('civicrm_contact')
427 ->where('id IN (#cids)', ['cids' => $cids])
428 ->execute()
429 ->fetchMap('id', 'sort_name');
430 return $result;
431 }
432
36c74cd6
TO
433 /**
434 * Given this task's list of targets, produce a hidden group.
435 *
436 * @return array
437 * Array(0 => int $groupID, 1 => int|NULL $ssID).
438 * @throws Exception
439 */
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.
69078420
SL
445 // groups require a unique name
446 $randID = md5(time() . rand(1, 1000));
36c74cd6
TO
447 $grpTitle = "Hidden Group {$randID}";
448 $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
449
450 if (!$grpID) {
be2fb01f 451 $groupParams = [
36c74cd6
TO
452 'title' => $grpTitle,
453 'is_active' => 1,
454 'is_hidden' => 1,
be2fb01f
CW
455 'group_type' => ['2' => 1],
456 ];
36c74cd6
TO
457
458 $group = CRM_Contact_BAO_Group::create($groupParams);
459 $grpID = $group->id;
460
461 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
462
463 $newGroupTitle = "Hidden Group {$grpID}";
be2fb01f 464 $groupParams = [
36c74cd6
TO
465 'id' => $grpID,
466 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
467 'title' => $newGroupTitle,
be2fb01f
CW
468 'group_type' => ['2' => 1],
469 ];
5ab8fe4a 470 CRM_Contact_BAO_Group::create($groupParams);
36c74cd6
TO
471 }
472
473 // note at this point its a static group
be2fb01f 474 return [$grpID, NULL];
36c74cd6
TO
475 }
476 else {
477 // Create a smart group.
36c74cd6 478 $ssId = $this->get('ssID');
be2fb01f
CW
479 $hiddenSmartParams = [
480 'group_type' => ['2' => 1],
d1249113 481 // queryParams have been preprocessed esp WRT any entity reference fields - see +
482 // https://github.com/civicrm/civicrm-core/pull/13250
93287bd4 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
af7e94a6 486 'form_values' => $this->get('isSearchBuilder') ? $this->get('formValues') : $this->get('queryParams'),
36c74cd6
TO
487 'saved_search_id' => $ssId,
488 'search_custom_id' => $this->get('customSearchID'),
489 'search_context' => $this->get('context'),
be2fb01f 490 ];
36c74cd6
TO
491
492 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
be2fb01f 493 return [$smartGroupId, $savedSearchId];
36c74cd6
TO
494 }
495
496 }
497
6a488035 498}