3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class generates form components for search-result tasks.
37 class CRM_Contact_Form_Task
extends CRM_Core_Form_Task
{
40 * The task being performed
47 * The array that holds all the contact ids
54 * The array that holds all the contact types
58 public $_contactTypes;
61 * The additional clause that we restrict the search with
65 protected $_componentClause = NULL;
68 * The name of the temp table where we store the contact IDs
72 protected $_componentTable = NULL;
75 * The array that holds all the component ids
79 protected $_componentIds;
82 * This includes the submitted values of the search form
85 static protected $_searchFormValues;
88 * Build all the data structures needed to build the form.
90 public function preProcess() {
91 self
::preProcessCommon($this);
95 * Common pre-processing function.
97 * @param CRM_Core_Form $form
99 * @throws \CRM_Core_Exception
101 public static function preProcessCommon(&$form) {
102 $form->_contactIds
= [];
103 $form->_contactTypes
= [];
105 $useTable = (CRM_Utils_System
::getClassName($form->controller
->getStateMachine()) == 'CRM_Export_StateMachine_Standalone');
107 $isStandAlone = in_array('task', $form->urlPath
) ||
in_array('standalone', $form->urlPath
);
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.'));
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'));
117 $form->setTitle($title);
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';
127 elseif ($form->_action
== CRM_Core_Action
::PROFILE
) {
128 self
::$_searchFormValues = $form->controller
->exportValues('Builder');
129 $fragment .= '/builder';
131 elseif ($form->_action
== CRM_Core_Action
::COPY
) {
132 self
::$_searchFormValues = $form->controller
->exportValues('Custom');
133 $fragment .= '/custom';
135 elseif (!$isStandAlone) {
136 self
::$_searchFormValues = $form->controller
->exportValues('Basic');
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";
146 $cacheKey = "civicrm search {$qfKey}";
148 $url = CRM_Utils_System
::url('civicrm/contact/' . $fragment, $urlParams);
149 $session = CRM_Core_Session
::singleton();
150 $session->replaceUserContext($url);
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));
157 $tempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('tskact')->setDurable()->setId($qfKey)->setUtf8();
158 $form->_componentTable
= $tempTable->getName();
160 $tempTable->createWithColumns('contact_id int primary key');
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
)
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
171 $allCids = Civi
::service('prevnext')->getSelection($cacheKey, "getall");
174 $allCids[$cacheKey] = self
::getContactIds($form);
177 $form->_contactIds
= [];
181 foreach ($allCids[$cacheKey] as $cid => $ignore) {
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);
191 if (!empty($insertString)) {
192 $string = implode(',', $insertString);
193 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
194 CRM_Core_DAO
::executeQuery($sql);
197 elseif (empty($form->_contactIds
)) {
198 // filter duplicates here
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.
204 foreach ($allCids[$cacheKey] as $cid => $ignore) {
205 $form->_contactIds
[] = $cid;
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
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
);
222 $insertString[] = " ( {$contactID} ) ";
225 $form->_contactIds
[] = substr($name, CRM_Core_Form
::CB_PREFIX_LEN
);
231 // fetching selected contact ids of passed cache key
232 $selectedCids = Civi
::service('prevnext')->getSelection($cacheKey);
233 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
235 $insertString[] = " ( {$selectedCid} ) ";
238 $form->_contactIds
[] = $selectedCid;
243 if (!empty($insertString)) {
244 $string = implode(',', $insertString);
245 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
246 CRM_Core_DAO
::executeQuery($sql);
250 //contact type for pick up profiles as per selected contact types with subtypes
252 if ($selectedTypes = CRM_Utils_Array
::value('contact_type', self
::$_searchFormValues)) {
253 if (!is_array($selectedTypes)) {
254 $selectedTypes = explode(' ', $selectedTypes);
256 foreach ($selectedTypes as $ct => $dontcare) {
257 if (strpos($ct, CRM_Core_DAO
::VALUE_SEPARATOR
) === FALSE) {
258 $form->_contactTypes
[] = $ct;
261 $separator = strpos($ct, CRM_Core_DAO
::VALUE_SEPARATOR
);
262 $form->_contactTypes
[] = substr($ct, $separator +
1);
267 if (CRM_Utils_Array
::value('radio_ts', self
::$_searchFormValues) == 'ts_sel'
268 && ($form->_action
!= CRM_Core_Action
::COPY
)
270 $sel = CRM_Utils_Array
::value('radio_ts', self
::$_searchFormValues);
271 $form->assign('searchtype', $sel);
272 $result = self
::getSelectedContactNames();
273 $form->assign("value", $result);
276 if (!empty($form->_contactIds
)) {
277 $form->_componentClause
= ' contact_a.id IN ( ' . implode(',', $form->_contactIds
) . ' ) ';
278 $form->assign('totalSelectedContacts', count($form->_contactIds
));
280 $form->_componentIds
= $form->_contactIds
;
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
290 * @param $form CRM_Core_Form
292 * @return array $contactIds
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
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
)
304 $selectorName = $form->controller
->selectorName();
306 $fv = $form->get('formValues');
307 $customClass = $form->get('customSearchClass');
308 $returnProperties = CRM_Core_BAO_Mapping
::returnProperties(self
::$_searchFormValues);
310 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
312 $params = $form->get('queryParams');
315 $sortByCharacter = $form->get('sortByCharacter');
316 if ($sortByCharacter && $sortByCharacter != 1) {
317 $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
319 $queryOperator = $form->get('queryOperator');
320 if (!$queryOperator) {
321 $queryOperator = 'AND';
323 $dao = $selector->contactIDQuery($params, $sortID,
324 CRM_Utils_Array
::value('display_relationship_type', $fv),
329 while ($dao->fetch()) {
330 $contactIds[$dao->contact_id
] = $dao->contact_id
;
337 * Set default values for the form. Relationship that in edit/view action.
339 * The default values are retrieved from the database.
343 public function setDefaultValues() {
349 * Add the rules for form.
351 public function addRules() {
355 * Build the form object.
357 public function buildQuickForm() {
358 $this->addDefaultButtons(ts('Confirm Action'));
362 * Process the form after the input has been submitted and validated.
364 public function postProcess() {
368 * Simple shell that derived classes can call to add form buttons.
370 * Allows customized title for the main Submit
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
379 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
388 'name' => ts('Cancel'),
389 'icon' => 'fa-times',
395 * Replace ids of household members in $this->_contactIds with the id of their household.
399 public function mergeContactIdsByHousehold() {
400 if (empty($this->_contactIds
)) {
404 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
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],
422 $relID = implode(',', $this->_contactIds
);
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';
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} ";
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";
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]);
452 if (!in_array($householdsDAO->household_id
, $this->_contactIds
)) {
453 $this->_contactIds
[] = $householdsDAO->household_id
;
458 // If contact list has changed, households will probably be at the end of
459 // the list. Sort it again by sort_name.
460 if (implode(',', $this->_contactIds
) != $relID) {
461 $result = civicrm_api3('Contact', 'get', [
463 'id' => ['IN' => $this->_contactIds
],
466 'sort' => "sort_name",
469 $this->_contactIds
= array_keys($result['values']);
475 * List of contact names.
476 * NOTE: These are raw values from the DB. In current data-model, that means
477 * they are pre-encoded HTML.
479 private static function getSelectedContactNames() {
480 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String');
481 $cacheKey = "civicrm search {$qfKey}";
485 foreach (Civi
::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
486 $cids = array_unique(array_merge($cids, array_keys($values)));
489 $result = CRM_Utils_SQL_Select
::from('civicrm_contact')
490 ->where('id IN (#cids)', ['cids' => $cids])
492 ->fetchMap('id', 'sort_name');
497 * Given this task's list of targets, produce a hidden group.
500 * Array(0 => int $groupID, 1 => int|NULL $ssID).
503 public function createHiddenGroup() {
504 // Did the user select "All" matches or cherry-pick a few records?
505 $searchParams = $this->controller
->exportValues();
506 if ($searchParams['radio_ts'] == 'ts_sel') {
507 // Create a static group.
508 // groups require a unique name
509 $randID = md5(time() . rand(1, 1000));
510 $grpTitle = "Hidden Group {$randID}";
511 $grpID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
515 'title' => $grpTitle,
518 'group_type' => ['2' => 1],
521 $group = CRM_Contact_BAO_Group
::create($groupParams);
524 CRM_Contact_BAO_GroupContact
::addContactsToGroup($this->_contactIds
, $group->id
);
526 $newGroupTitle = "Hidden Group {$grpID}";
529 'name' => CRM_Utils_String
::titleToVar($newGroupTitle),
530 'title' => $newGroupTitle,
531 'group_type' => ['2' => 1],
533 CRM_Contact_BAO_Group
::create($groupParams);
536 // note at this point its a static group
537 return [$grpID, NULL];
540 // Create a smart group.
541 $ssId = $this->get('ssID');
542 $hiddenSmartParams = [
543 'group_type' => ['2' => 1],
544 // queryParams have been preprocessed esp WRT any entity reference fields - see +
545 // https://github.com/civicrm/civicrm-core/pull/13250
546 'form_values' => $this->get('queryParams'),
547 'saved_search_id' => $ssId,
548 'search_custom_id' => $this->get('customSearchID'),
549 'search_context' => $this->get('context'),
552 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group
::createHiddenSmartGroup($hiddenSmartParams);
553 return [$smartGroupId, $savedSearchId];