Merge pull request #18571 from eileenmcnaughton/aipn
[civicrm-core.git] / CRM / Contact / Form / Task.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for search-result tasks.
20 */
21 class CRM_Contact_Form_Task extends CRM_Core_Form_Task {
22
23 /**
24 * The task being performed
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
67 * @var array
68 */
69 static protected $_searchFormValues;
70
71 /**
72 * Build all the data structures needed to build the form.
73 */
74 public function preProcess() {
75 self::preProcessCommon($this);
76 }
77
78 /**
79 * Common pre-processing function.
80 *
81 * @param \CRM_Core_Form_Task $form
82 *
83 * @throws \CRM_Core_Exception
84 */
85 public static function preProcessCommon(&$form) {
86 $form->_contactIds = [];
87 $form->_contactTypes = [];
88
89 $isStandAlone = in_array('task', $form->urlPath) || in_array('standalone', $form->urlPath);
90 if ($isStandAlone) {
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.'));
94 }
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'));
98 }
99 $form->setTitle($title);
100 }
101
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';
107 }
108 elseif ($form->_action == CRM_Core_Action::PROFILE) {
109 $fragment .= '/builder';
110 }
111 elseif ($form->_action == CRM_Core_Action::COPY) {
112 $fragment .= '/custom';
113 }
114 if (!$isStandAlone) {
115 self::$_searchFormValues = $form->getFormValues();
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
125 $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
126 $session = CRM_Core_Session::singleton();
127 $session->replaceUserContext($url);
128
129 $cacheKey = "civicrm search {$qfKey}";
130
131 $form->_task = self::$_searchFormValues['task'] ?? NULL;
132 $crmContactTaskTasks = CRM_Contact_Task::taskTitles();
133 $form->assign('taskName', CRM_Utils_Array::value($form->_task, $crmContactTaskTasks));
134
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 ) {
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
141 // final result set
142 $allCids[$cacheKey] = self::getContactIds($form);
143
144 $form->_contactIds = [];
145 if (empty($form->_contactIds)) {
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
160 $insertString = [];
161
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);
169 }
170 }
171 }
172 else {
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;
177 }
178 }
179
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
204 if (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel'
205 && ($form->_action != CRM_Core_Action::COPY)
206 ) {
207 $sel = self::$_searchFormValues['radio_ts'] ?? NULL;
208 $form->assign('searchtype', $sel);
209 $result = self::getSelectedContactNames();
210 $form->assign("value", $result);
211 }
212
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 /**
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
226 *
227 * @param $form CRM_Core_Form
228 *
229 * @return array $contactIds
230 */
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
234 $sortID = NULL;
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)
238 );
239 }
240
241 $selectorName = $form->controller->selectorName();
242
243 $fv = $form->get('formValues');
244 $customClass = $form->get('customSearchClass');
245 $returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
246
247 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
248
249 $params = $form->get('queryParams');
250
251 // fix for CRM-5165
252 $sortByCharacter = $form->get('sortByCharacter');
253 if ($sortByCharacter && $sortByCharacter != 1) {
254 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
255 }
256 $queryOperator = $form->get('queryOperator');
257 if (!$queryOperator) {
258 $queryOperator = 'AND';
259 }
260 $dao = $selector->contactIDQuery($params, $sortID,
261 CRM_Utils_Array::value('display_relationship_type', $fv),
262 $queryOperator
263 );
264
265 $contactIds = [];
266 while ($dao->fetch()) {
267 $contactIds[$dao->contact_id] = $dao->contact_id;
268 }
269
270 return $contactIds;
271 }
272
273 /**
274 * Set default values for the form. Relationship that in edit/view action.
275 *
276 * The default values are retrieved from the database.
277 *
278 * @return array
279 */
280 public function setDefaultValues() {
281 $defaults = [];
282 return $defaults;
283 }
284
285 /**
286 * Add the rules for form.
287 */
288 public function addRules() {
289 }
290
291 /**
292 * Build the form object.
293 */
294 public function buildQuickForm() {
295 $this->addDefaultButtons(ts('Confirm Action'));
296 }
297
298 /**
299 * Process the form after the input has been submitted and validated.
300 */
301 public function postProcess() {
302 }
303
304 /**
305 * Simple shell that derived classes can call to add form buttons.
306 *
307 * Allows customized title for the main Submit
308 *
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
315 */
316 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
317 $this->addButtons([
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 ]);
329 }
330
331 /**
332 * Replace ids of household members in $this->_contactIds with the id of their household.
333 *
334 * @see https://issues.civicrm.org/jira/browse/CRM-8338
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);
354 $householdRelationshipTypes = [
355 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
356 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
357 ];
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.
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} ";
375
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";
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 }
393 }
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) {
398 $result = civicrm_api3('Contact', 'get', [
399 'return' => ['id'],
400 'id' => ['IN' => $this->_contactIds],
401 'options' => [
402 'limit' => 0,
403 'sort' => "sort_name",
404 ],
405 ]);
406 $this->_contactIds = array_keys($result['values']);
407 }
408 }
409
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
420 $cids = [];
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
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.
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');
449
450 if (!$grpID) {
451 $groupParams = [
452 'title' => $grpTitle,
453 'is_active' => 1,
454 'is_hidden' => 1,
455 'group_type' => ['2' => 1],
456 ];
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}";
464 $groupParams = [
465 'id' => $grpID,
466 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
467 'title' => $newGroupTitle,
468 'group_type' => ['2' => 1],
469 ];
470 CRM_Contact_BAO_Group::create($groupParams);
471 }
472
473 // note at this point its a static group
474 return [$grpID, NULL];
475 }
476 else {
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'),
490 ];
491
492 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
493 return [$smartGroupId, $savedSearchId];
494 }
495
496 }
497
498 }