Merge pull request #14010 from colemanw/assetCheck
[civicrm-core.git] / CRM / Contact / Form / Task.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class generates form components for search-result tasks.
36 */
37 class CRM_Contact_Form_Task extends CRM_Core_Form_Task {
38
39 /**
40 * The task being performed
41 *
42 * @var int
43 */
44 protected $_task;
45
46 /**
47 * The array that holds all the contact ids
48 *
49 * @var array
50 */
51 public $_contactIds;
52
53 /**
54 * The array that holds all the contact types
55 *
56 * @var array
57 */
58 public $_contactTypes;
59
60 /**
61 * The additional clause that we restrict the search with
62 *
63 * @var string
64 */
65 protected $_componentClause = NULL;
66
67 /**
68 * The name of the temp table where we store the contact IDs
69 *
70 * @var string
71 */
72 protected $_componentTable = NULL;
73
74 /**
75 * The array that holds all the component ids
76 *
77 * @var array
78 */
79 protected $_componentIds;
80
81 /**
82 * This includes the submitted values of the search form
83 * @var array
84 */
85 static protected $_searchFormValues;
86
87 /**
88 * Build all the data structures needed to build the form.
89 */
90 public function preProcess() {
91 self::preProcessCommon($this);
92 }
93
94 /**
95 * Common pre-processing function.
96 *
97 * @param CRM_Core_Form $form
98 *
99 * @throws \CRM_Core_Exception
100 */
101 public static function preProcessCommon(&$form) {
102 $form->_contactIds = [];
103 $form->_contactTypes = [];
104
105 $useTable = (CRM_Utils_System::getClassName($form->controller->getStateMachine()) == 'CRM_Export_StateMachine_Standalone');
106
107 $isStandAlone = in_array('task', $form->urlPath) || in_array('standalone', $form->urlPath);
108 if ($isStandAlone) {
109 list($form->_task, $title) = CRM_Contact_Task::getTaskAndTitleByClass(get_class($form));
110 if (!array_key_exists($form->_task, CRM_Contact_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()))) {
111 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
112 }
113 $form->_contactIds = explode(',', CRM_Utils_Request::retrieve('cids', 'CommaSeparatedIntegers', $form, TRUE));
114 if (empty($form->_contactIds)) {
115 CRM_Core_Error::statusBounce(ts('No Contacts Selected'));
116 }
117 $form->setTitle($title);
118 }
119
120 // get the submitted values of the search form
121 // we'll need to get fv from either search or adv search in the future
122 $fragment = 'search';
123 if ($form->_action == CRM_Core_Action::ADVANCED) {
124 self::$_searchFormValues = $form->controller->exportValues('Advanced');
125 $fragment .= '/advanced';
126 }
127 elseif ($form->_action == CRM_Core_Action::PROFILE) {
128 self::$_searchFormValues = $form->controller->exportValues('Builder');
129 $fragment .= '/builder';
130 }
131 elseif ($form->_action == CRM_Core_Action::COPY) {
132 self::$_searchFormValues = $form->controller->exportValues('Custom');
133 $fragment .= '/custom';
134 }
135 elseif (!$isStandAlone) {
136 self::$_searchFormValues = $form->controller->exportValues('Basic');
137 }
138
139 //set the user context for redirection of task actions
140 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
141 $urlParams = 'force=1';
142 if (CRM_Utils_Rule::qfKey($qfKey)) {
143 $urlParams .= "&qfKey=$qfKey";
144 }
145
146 $cacheKey = "civicrm search {$qfKey}";
147
148 $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
149 $session = CRM_Core_Session::singleton();
150 $session->replaceUserContext($url);
151
152 $form->_task = CRM_Utils_Array::value('task', self::$_searchFormValues);
153 $crmContactTaskTasks = CRM_Contact_Task::taskTitles();
154 $form->assign('taskName', CRM_Utils_Array::value($form->_task, $crmContactTaskTasks));
155
156 if ($useTable) {
157 $tempTable = CRM_Utils_SQL_TempTable::build()->setCategory('tskact')->setDurable()->setId($qfKey)->setUtf8();
158 $form->_componentTable = $tempTable->getName();
159 $tempTable->drop();
160 $tempTable->createWithColumns('contact_id int primary key');
161 }
162
163 // all contacts or action = save a search
164 if ((CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_all') ||
165 ($form->_task == CRM_Contact_Task::SAVE_SEARCH)
166 ) {
167 // since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
168 // rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
169 // final result set
170 if ($useTable) {
171 $allCids = Civi::service('prevnext')->getSelection($cacheKey, "getall");
172 }
173 else {
174 $allCids[$cacheKey] = self::getContactIds($form);
175 }
176
177 $form->_contactIds = [];
178 if ($useTable) {
179 $count = 0;
180 $insertString = [];
181 foreach ($allCids[$cacheKey] as $cid => $ignore) {
182 $count++;
183 $insertString[] = " ( {$cid} ) ";
184 if ($count % 200 == 0) {
185 $string = implode(',', $insertString);
186 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
187 CRM_Core_DAO::executeQuery($sql);
188 $insertString = [];
189 }
190 }
191 if (!empty($insertString)) {
192 $string = implode(',', $insertString);
193 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
194 CRM_Core_DAO::executeQuery($sql);
195 }
196 }
197 elseif (empty($form->_contactIds)) {
198 // filter duplicates here
199 // CRM-7058
200 // might be better to do this in the query, but that logic is a bit complex
201 // and it decides when to use distinct based on input criteria, which needs
202 // to be fixed and optimized.
203
204 foreach ($allCids[$cacheKey] as $cid => $ignore) {
205 $form->_contactIds[] = $cid;
206 }
207 }
208 }
209 elseif (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel') {
210 // selected contacts only
211 // need to perform action on only selected contacts
212 $insertString = [];
213
214 // refire sql in case of custom search
215 if ($form->_action == CRM_Core_Action::COPY) {
216 // selected contacts only
217 // need to perform action on only selected contacts
218 foreach (self::$_searchFormValues as $name => $value) {
219 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
220 $contactID = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
221 if ($useTable) {
222 $insertString[] = " ( {$contactID} ) ";
223 }
224 else {
225 $form->_contactIds[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
226 }
227 }
228 }
229 }
230 else {
231 // fetching selected contact ids of passed cache key
232 $selectedCids = Civi::service('prevnext')->getSelection($cacheKey);
233 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
234 if ($useTable) {
235 $insertString[] = " ( {$selectedCid} ) ";
236 }
237 else {
238 $form->_contactIds[] = $selectedCid;
239 }
240 }
241 }
242
243 if (!empty($insertString)) {
244 $string = implode(',', $insertString);
245 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
246 CRM_Core_DAO::executeQuery($sql);
247 }
248 }
249
250 //contact type for pick up profiles as per selected contact types with subtypes
251 //CRM-5521
252 if ($selectedTypes = CRM_Utils_Array::value('contact_type', self::$_searchFormValues)) {
253 if (!is_array($selectedTypes)) {
254 $selectedTypes = explode(' ', $selectedTypes);
255 }
256 foreach ($selectedTypes as $ct => $dontcare) {
257 if (strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR) === FALSE) {
258 $form->_contactTypes[] = $ct;
259 }
260 else {
261 $separator = strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR);
262 $form->_contactTypes[] = substr($ct, $separator + 1);
263 }
264 }
265 }
266
267 if (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel'
268 && ($form->_action != CRM_Core_Action::COPY)
269 ) {
270 $sel = CRM_Utils_Array::value('radio_ts', self::$_searchFormValues);
271 $form->assign('searchtype', $sel);
272 $result = self::getSelectedContactNames();
273 $form->assign("value", $result);
274 }
275
276 if (!empty($form->_contactIds)) {
277 $form->_componentClause = ' contact_a.id IN ( ' . implode(',', $form->_contactIds) . ' ) ';
278 $form->assign('totalSelectedContacts', count($form->_contactIds));
279
280 $form->_componentIds = $form->_contactIds;
281 }
282 }
283
284 /**
285 * Get the contact ids for:
286 * - "Select Records: All xx records"
287 * - custom search (FIXME: does this still apply to custom search?).
288 * When we call this function we are not using the prev/next cache
289 *
290 * @param $form CRM_Core_Form
291 *
292 * @return array $contactIds
293 */
294 public static function getContactIds($form) {
295 // need to perform action on all contacts
296 // fire the query again and get the contact id's + display name
297 $sortID = NULL;
298 if ($form->get(CRM_Utils_Sort::SORT_ID)) {
299 $sortID = CRM_Utils_Sort::sortIDValue($form->get(CRM_Utils_Sort::SORT_ID),
300 $form->get(CRM_Utils_Sort::SORT_DIRECTION)
301 );
302 }
303
304 $selectorName = $form->controller->selectorName();
305
306 $fv = $form->get('formValues');
307 $customClass = $form->get('customSearchClass');
308 $returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
309
310 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
311
312 $params = $form->get('queryParams');
313
314 // fix for CRM-5165
315 $sortByCharacter = $form->get('sortByCharacter');
316 if ($sortByCharacter && $sortByCharacter != 1) {
317 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
318 }
319 $queryOperator = $form->get('queryOperator');
320 if (!$queryOperator) {
321 $queryOperator = 'AND';
322 }
323 $dao = $selector->contactIDQuery($params, $sortID,
324 CRM_Utils_Array::value('display_relationship_type', $fv),
325 $queryOperator
326 );
327
328 $contactIds = [];
329 while ($dao->fetch()) {
330 $contactIds[$dao->contact_id] = $dao->contact_id;
331 }
332
333 return $contactIds;
334 }
335
336 /**
337 * Set default values for the form. Relationship that in edit/view action.
338 *
339 * The default values are retrieved from the database.
340 *
341 * @return array
342 */
343 public function setDefaultValues() {
344 $defaults = [];
345 return $defaults;
346 }
347
348 /**
349 * Add the rules for form.
350 */
351 public function addRules() {
352 }
353
354 /**
355 * Build the form object.
356 */
357 public function buildQuickForm() {
358 $this->addDefaultButtons(ts('Confirm Action'));
359 }
360
361 /**
362 * Process the form after the input has been submitted and validated.
363 */
364 public function postProcess() {
365 }
366
367 /**
368 * Simple shell that derived classes can call to add form buttons.
369 *
370 * Allows customized title for the main Submit
371 *
372 * @param string $title
373 * Title of the main button.
374 * @param string $nextType
375 * Button type for the form after processing.
376 * @param string $backType
377 * @param bool $submitOnce
378 */
379 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
380 $this->addButtons([
381 [
382 'type' => $nextType,
383 'name' => $title,
384 'isDefault' => TRUE,
385 ],
386 [
387 'type' => $backType,
388 'name' => ts('Cancel'),
389 'icon' => 'fa-times',
390 ],
391 ]);
392 }
393
394 /**
395 * Replace ids of household members in $this->_contactIds with the id of their household.
396 *
397 * CRM-8338
398 */
399 public function mergeContactIdsByHousehold() {
400 if (empty($this->_contactIds)) {
401 return;
402 }
403
404 $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
405 NULL,
406 NULL,
407 NULL,
408 NULL,
409 TRUE,
410 'name',
411 FALSE
412 );
413
414 // Get Head of Household & Household Member relationships
415 $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
416 $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
417 $householdRelationshipTypes = [
418 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
419 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
420 ];
421
422 $relID = implode(',', $this->_contactIds);
423
424 foreach ($householdRelationshipTypes as $rel => $dnt) {
425 list($id, $direction) = explode('_', $rel, 2);
426 // identify the relationship direction
427 $contactA = 'contact_id_a';
428 $contactB = 'contact_id_b';
429 if ($direction == 'b_a') {
430 $contactA = 'contact_id_b';
431 $contactB = 'contact_id_a';
432 }
433
434 // Find related households.
435 $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact ";
436 $relationFrom = " FROM civicrm_contact contact_household
437 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_household.id AND crel.relationship_type_id = {$id} ";
438
439 // Check for active relationship status only.
440 $today = date('Ymd');
441 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
442 $relationWhere = " WHERE contact_household.is_deleted = 0 AND crel.{$contactA} IN ( {$relID} ) {$relationActive}";
443 $relationGroupBy = " GROUP BY crel.{$contactA}, contact_household.id";
444 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationGroupBy";
445
446 $householdsDAO = CRM_Core_DAO::executeQuery($relationQueryString);
447 while ($householdsDAO->fetch()) {
448 // Remove contact's id from $this->_contactIds and replace with their household's id.
449 foreach (array_keys($this->_contactIds, $householdsDAO->refContact) as $idKey) {
450 unset($this->_contactIds[$idKey]);
451 }
452 if (!in_array($householdsDAO->household_id, $this->_contactIds)) {
453 $this->_contactIds[] = $householdsDAO->household_id;
454 }
455 }
456 $householdsDAO->free();
457 }
458
459 // If contact list has changed, households will probably be at the end of
460 // the list. Sort it again by sort_name.
461 if (implode(',', $this->_contactIds) != $relID) {
462 $result = civicrm_api3('Contact', 'get', [
463 'return' => ['id'],
464 'id' => ['IN' => $this->_contactIds],
465 'options' => [
466 'limit' => 0,
467 'sort' => "sort_name",
468 ],
469 ]);
470 $this->_contactIds = array_keys($result['values']);
471 }
472 }
473
474 /**
475 * @return array
476 * List of contact names.
477 * NOTE: These are raw values from the DB. In current data-model, that means
478 * they are pre-encoded HTML.
479 */
480 private static function getSelectedContactNames() {
481 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
482 $cacheKey = "civicrm search {$qfKey}";
483
484 $cids = [];
485 // Gymanstic time!
486 foreach (Civi::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
487 $cids = array_unique(array_merge($cids, array_keys($values)));
488 }
489
490 $result = CRM_Utils_SQL_Select::from('civicrm_contact')
491 ->where('id IN (#cids)', ['cids' => $cids])
492 ->execute()
493 ->fetchMap('id', 'sort_name');
494 return $result;
495 }
496
497 /**
498 * Given this task's list of targets, produce a hidden group.
499 *
500 * @return array
501 * Array(0 => int $groupID, 1 => int|NULL $ssID).
502 * @throws Exception
503 */
504 public function createHiddenGroup() {
505 // Did the user select "All" matches or cherry-pick a few records?
506 $searchParams = $this->controller->exportValues();
507 if ($searchParams['radio_ts'] == 'ts_sel') {
508 // Create a static group.
509 // groups require a unique name
510 $randID = md5(time() . rand(1, 1000));
511 $grpTitle = "Hidden Group {$randID}";
512 $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
513
514 if (!$grpID) {
515 $groupParams = [
516 'title' => $grpTitle,
517 'is_active' => 1,
518 'is_hidden' => 1,
519 'group_type' => ['2' => 1],
520 ];
521
522 $group = CRM_Contact_BAO_Group::create($groupParams);
523 $grpID = $group->id;
524
525 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
526
527 $newGroupTitle = "Hidden Group {$grpID}";
528 $groupParams = [
529 'id' => $grpID,
530 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
531 'title' => $newGroupTitle,
532 'group_type' => ['2' => 1],
533 ];
534 CRM_Contact_BAO_Group::create($groupParams);
535 }
536
537 // note at this point its a static group
538 return [$grpID, NULL];
539 }
540 else {
541 // Create a smart group.
542 $ssId = $this->get('ssID');
543 $hiddenSmartParams = [
544 'group_type' => ['2' => 1],
545 // queryParams have been preprocessed esp WRT any entity reference fields - see +
546 // https://github.com/civicrm/civicrm-core/pull/13250
547 'form_values' => $this->get('queryParams'),
548 'saved_search_id' => $ssId,
549 'search_custom_id' => $this->get('customSearchID'),
550 'search_context' => $this->get('context'),
551 ];
552
553 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
554 return [$smartGroupId, $savedSearchId];
555 }
556
557 }
558
559 }