Merge pull request #18631 from eileenmcnaughton/ppp
[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->getSearchFormValues();
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
133 // all contacts or action = save a search
134 if ((CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_all') ||
135 ($form->_task == CRM_Contact_Task::SAVE_SEARCH)
136 ) {
137 // since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
138 // rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
139 // final result set
140 $allCids[$cacheKey] = self::getContactIds($form);
141
142 $form->_contactIds = [];
143 if (empty($form->_contactIds)) {
144 // filter duplicates here
145 // CRM-7058
146 // might be better to do this in the query, but that logic is a bit complex
147 // and it decides when to use distinct based on input criteria, which needs
148 // to be fixed and optimized.
149
150 foreach ($allCids[$cacheKey] as $cid => $ignore) {
151 $form->_contactIds[] = $cid;
152 }
153 }
154 }
155 elseif (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel') {
156 // selected contacts only
157 // need to perform action on only selected contacts
158 $insertString = [];
159
160 // refire sql in case of custom search
161 if ($form->_action == CRM_Core_Action::COPY) {
162 // selected contacts only
163 // need to perform action on only selected contacts
164 foreach (self::$_searchFormValues as $name => $value) {
165 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
166 $form->_contactIds[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
167 }
168 }
169 }
170 else {
171 // fetching selected contact ids of passed cache key
172 $selectedCids = Civi::service('prevnext')->getSelection($cacheKey);
173 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
174 $form->_contactIds[] = $selectedCid;
175 }
176 }
177
178 if (!empty($insertString)) {
179 $string = implode(',', $insertString);
180 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
181 CRM_Core_DAO::executeQuery($sql);
182 }
183 }
184
185 //contact type for pick up profiles as per selected contact types with subtypes
186 //CRM-5521
187 if ($selectedTypes = CRM_Utils_Array::value('contact_type', self::$_searchFormValues)) {
188 if (!is_array($selectedTypes)) {
189 $selectedTypes = explode(' ', $selectedTypes);
190 }
191 foreach ($selectedTypes as $ct => $dontcare) {
192 if (strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR) === FALSE) {
193 $form->_contactTypes[] = $ct;
194 }
195 else {
196 $separator = strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR);
197 $form->_contactTypes[] = substr($ct, $separator + 1);
198 }
199 }
200 }
201
202 if (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel'
203 && ($form->_action != CRM_Core_Action::COPY)
204 ) {
205 $sel = self::$_searchFormValues['radio_ts'] ?? NULL;
206 $form->assign('searchtype', $sel);
207 $result = self::getSelectedContactNames();
208 $form->assign("value", $result);
209 }
210
211 if (!empty($form->_contactIds)) {
212 $form->_componentClause = ' contact_a.id IN ( ' . implode(',', $form->_contactIds) . ' ) ';
213 $form->assign('totalSelectedContacts', count($form->_contactIds));
214
215 $form->_componentIds = $form->_contactIds;
216 }
217 }
218
219 /**
220 * Get the contact ids for:
221 * - "Select Records: All xx records"
222 * - custom search (FIXME: does this still apply to custom search?).
223 * When we call this function we are not using the prev/next cache
224 *
225 * @param $form CRM_Core_Form
226 *
227 * @return array $contactIds
228 */
229 public static function getContactIds($form) {
230 // need to perform action on all contacts
231 // fire the query again and get the contact id's + display name
232 $sortID = NULL;
233 if ($form->get(CRM_Utils_Sort::SORT_ID)) {
234 $sortID = CRM_Utils_Sort::sortIDValue($form->get(CRM_Utils_Sort::SORT_ID),
235 $form->get(CRM_Utils_Sort::SORT_DIRECTION)
236 );
237 }
238
239 $selectorName = $form->controller->selectorName();
240
241 $fv = $form->get('formValues');
242 $customClass = $form->get('customSearchClass');
243 $returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
244
245 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
246
247 $params = $form->get('queryParams');
248
249 // fix for CRM-5165
250 $sortByCharacter = $form->get('sortByCharacter');
251 if ($sortByCharacter && $sortByCharacter != 1) {
252 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
253 }
254 $queryOperator = $form->get('queryOperator');
255 if (!$queryOperator) {
256 $queryOperator = 'AND';
257 }
258 $dao = $selector->contactIDQuery($params, $sortID,
259 CRM_Utils_Array::value('display_relationship_type', $fv),
260 $queryOperator
261 );
262
263 $contactIds = [];
264 while ($dao->fetch()) {
265 $contactIds[$dao->contact_id] = $dao->contact_id;
266 }
267
268 return $contactIds;
269 }
270
271 /**
272 * Set default values for the form. Relationship that in edit/view action.
273 *
274 * The default values are retrieved from the database.
275 *
276 * @return array
277 */
278 public function setDefaultValues() {
279 $defaults = [];
280 return $defaults;
281 }
282
283 /**
284 * Add the rules for form.
285 */
286 public function addRules() {
287 }
288
289 /**
290 * Build the form object.
291 */
292 public function buildQuickForm() {
293 $this->addDefaultButtons(ts('Confirm Action'));
294 }
295
296 /**
297 * Process the form after the input has been submitted and validated.
298 */
299 public function postProcess() {
300 }
301
302 /**
303 * Simple shell that derived classes can call to add form buttons.
304 *
305 * Allows customized title for the main Submit
306 *
307 * @param string $title
308 * Title of the main button.
309 * @param string $nextType
310 * Button type for the form after processing.
311 * @param string $backType
312 * @param bool $submitOnce
313 */
314 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
315 $this->addButtons([
316 [
317 'type' => $nextType,
318 'name' => $title,
319 'isDefault' => TRUE,
320 ],
321 [
322 'type' => $backType,
323 'name' => ts('Cancel'),
324 'icon' => 'fa-times',
325 ],
326 ]);
327 }
328
329 /**
330 * Replace ids of household members in $this->_contactIds with the id of their household.
331 *
332 * @see https://issues.civicrm.org/jira/browse/CRM-8338
333 */
334 public function mergeContactIdsByHousehold() {
335 if (empty($this->_contactIds)) {
336 return;
337 }
338
339 $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
340 NULL,
341 NULL,
342 NULL,
343 NULL,
344 TRUE,
345 'name',
346 FALSE
347 );
348
349 // Get Head of Household & Household Member relationships
350 $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
351 $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
352 $householdRelationshipTypes = [
353 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
354 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
355 ];
356
357 $relID = implode(',', $this->_contactIds);
358
359 foreach ($householdRelationshipTypes as $rel => $dnt) {
360 list($id, $direction) = explode('_', $rel, 2);
361 // identify the relationship direction
362 $contactA = 'contact_id_a';
363 $contactB = 'contact_id_b';
364 if ($direction == 'b_a') {
365 $contactA = 'contact_id_b';
366 $contactB = 'contact_id_a';
367 }
368
369 // Find related households.
370 $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact ";
371 $relationFrom = " FROM civicrm_contact contact_household
372 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_household.id AND crel.relationship_type_id = {$id} ";
373
374 // Check for active relationship status only.
375 $today = date('Ymd');
376 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
377 $relationWhere = " WHERE contact_household.is_deleted = 0 AND crel.{$contactA} IN ( {$relID} ) {$relationActive}";
378 $relationGroupBy = " GROUP BY crel.{$contactA}, contact_household.id";
379 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationGroupBy";
380
381 $householdsDAO = CRM_Core_DAO::executeQuery($relationQueryString);
382 while ($householdsDAO->fetch()) {
383 // Remove contact's id from $this->_contactIds and replace with their household's id.
384 foreach (array_keys($this->_contactIds, $householdsDAO->refContact) as $idKey) {
385 unset($this->_contactIds[$idKey]);
386 }
387 if (!in_array($householdsDAO->household_id, $this->_contactIds)) {
388 $this->_contactIds[] = $householdsDAO->household_id;
389 }
390 }
391 }
392
393 // If contact list has changed, households will probably be at the end of
394 // the list. Sort it again by sort_name.
395 if (implode(',', $this->_contactIds) != $relID) {
396 $result = civicrm_api3('Contact', 'get', [
397 'return' => ['id'],
398 'id' => ['IN' => $this->_contactIds],
399 'options' => [
400 'limit' => 0,
401 'sort' => "sort_name",
402 ],
403 ]);
404 $this->_contactIds = array_keys($result['values']);
405 }
406 }
407
408 /**
409 * @return array
410 * List of contact names.
411 * NOTE: These are raw values from the DB. In current data-model, that means
412 * they are pre-encoded HTML.
413 */
414 private static function getSelectedContactNames() {
415 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
416 $cacheKey = "civicrm search {$qfKey}";
417
418 $cids = [];
419 // Gymanstic time!
420 foreach (Civi::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
421 $cids = array_unique(array_merge($cids, array_keys($values)));
422 }
423
424 $result = CRM_Utils_SQL_Select::from('civicrm_contact')
425 ->where('id IN (#cids)', ['cids' => $cids])
426 ->execute()
427 ->fetchMap('id', 'sort_name');
428 return $result;
429 }
430
431 /**
432 * Given this task's list of targets, produce a hidden group.
433 *
434 * @return array
435 * Array(0 => int $groupID, 1 => int|NULL $ssID).
436 * @throws Exception
437 */
438 public function createHiddenGroup() {
439 // Did the user select "All" matches or cherry-pick a few records?
440 $searchParams = $this->controller->exportValues();
441 if ($searchParams['radio_ts'] == 'ts_sel') {
442 // Create a static group.
443 // groups require a unique name
444 $randID = md5(time() . rand(1, 1000));
445 $grpTitle = "Hidden Group {$randID}";
446 $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
447
448 if (!$grpID) {
449 $groupParams = [
450 'title' => $grpTitle,
451 'is_active' => 1,
452 'is_hidden' => 1,
453 'group_type' => ['2' => 1],
454 ];
455
456 $group = CRM_Contact_BAO_Group::create($groupParams);
457 $grpID = $group->id;
458
459 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
460
461 $newGroupTitle = "Hidden Group {$grpID}";
462 $groupParams = [
463 'id' => $grpID,
464 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
465 'title' => $newGroupTitle,
466 'group_type' => ['2' => 1],
467 ];
468 CRM_Contact_BAO_Group::create($groupParams);
469 }
470
471 // note at this point its a static group
472 return [$grpID, NULL];
473 }
474 else {
475 // Create a smart group.
476 $ssId = $this->get('ssID');
477 $hiddenSmartParams = [
478 'group_type' => ['2' => 1],
479 // queryParams have been preprocessed esp WRT any entity reference fields - see +
480 // https://github.com/civicrm/civicrm-core/pull/13250
481 // Advanced search sets queryParams, for builder you need formValues.
482 // This is kinda fragile but .... see CRM_Mailing_Form_Task_AdhocMailingTest for test effort.
483 // Moral never touch anything ever again and the house of cards will stand tall, unless there is a breeze
484 'form_values' => $this->get('isSearchBuilder') ? $this->get('formValues') : $this->get('queryParams'),
485 'saved_search_id' => $ssId,
486 'search_custom_id' => $this->get('customSearchID'),
487 'search_context' => $this->get('context'),
488 ];
489
490 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
491 return [$smartGroupId, $savedSearchId];
492 }
493
494 }
495
496 }