Add test for DB error on search add to group CRM-21159
[civicrm-core.git] / CRM / Contact / Form / Task.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
5a409b50 35 * This class generates form components for search-result tasks.
6a488035
TO
36 */
37class CRM_Contact_Form_Task extends CRM_Core_Form {
38
39 /**
100fef9d 40 * The task being performed
6a488035
TO
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 */
84 static protected $_searchFormValues;
85
86 /**
d8689418 87 * Build all the data structures needed to build the form.
8ef12e64 88 */
00be9182 89 public function preProcess() {
6a488035
TO
90 self::preProcessCommon($this);
91 }
92
86538308 93 /**
d8689418
EM
94 * Common pre-processing function.
95 *
c490a46a 96 * @param CRM_Core_Form $form
86538308
EM
97 * @param bool $useTable
98 */
00be9182 99 public static function preProcessCommon(&$form, $useTable = FALSE) {
6a488035
TO
100 $form->_contactIds = array();
101 $form->_contactTypes = array();
102
78b22ce9 103 $isStandAlone = in_array('task', $form->urlPath) || in_array('standalone', $form->urlPath);
061ff68c 104 if ($isStandAlone) {
105 list($form->_task, $title) = CRM_Contact_Task::getTaskAndTitleByClass(get_class($form));
106 if (!array_key_exists($form->_task, CRM_Contact_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()))) {
6bc234fa 107 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
061ff68c 108 }
78b22ce9 109 $form->_contactIds = explode(',', CRM_Utils_Request::retrieve('cids', 'CommaSeparatedIntegers', $form, TRUE));
061ff68c 110 if (empty($form->_contactIds)) {
6bc234fa 111 CRM_Core_Error::statusBounce(ts('No Contacts Selected'));
061ff68c 112 }
113 $form->setTitle($title);
114 }
115
6a488035
TO
116 // get the submitted values of the search form
117 // we'll need to get fv from either search or adv search in the future
118 $fragment = 'search';
119 if ($form->_action == CRM_Core_Action::ADVANCED) {
120 self::$_searchFormValues = $form->controller->exportValues('Advanced');
121 $fragment .= '/advanced';
122 }
123 elseif ($form->_action == CRM_Core_Action::PROFILE) {
124 self::$_searchFormValues = $form->controller->exportValues('Builder');
125 $fragment .= '/builder';
126 }
127 elseif ($form->_action == CRM_Core_Action::COPY) {
128 self::$_searchFormValues = $form->controller->exportValues('Custom');
129 $fragment .= '/custom';
130 }
061ff68c 131 elseif (!$isStandAlone) {
6a488035
TO
132 self::$_searchFormValues = $form->controller->exportValues('Basic');
133 }
134
135 //set the user context for redirection of task actions
136 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
137 $urlParams = 'force=1';
138 if (CRM_Utils_Rule::qfKey($qfKey)) {
139 $urlParams .= "&qfKey=$qfKey";
140 }
141
142 $cacheKey = "civicrm search {$qfKey}";
143
144 $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
145 $session = CRM_Core_Session::singleton();
146 $session->replaceUserContext($url);
147
148 $form->_task = CRM_Utils_Array::value('task', self::$_searchFormValues);
149 $crmContactTaskTasks = CRM_Contact_Task::taskTitles();
150 $form->assign('taskName', CRM_Utils_Array::value($form->_task, $crmContactTaskTasks));
151
152 if ($useTable) {
153 $form->_componentTable = CRM_Core_DAO::createTempTableName('civicrm_task_action', TRUE, $qfKey);
154 $sql = " DROP TABLE IF EXISTS {$form->_componentTable}";
155 CRM_Core_DAO::executeQuery($sql);
156
75f1cd78 157 $sql = "CREATE TABLE {$form->_componentTable} ( contact_id int primary key) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
6a488035
TO
158 CRM_Core_DAO::executeQuery($sql);
159 }
160
161 // all contacts or action = save a search
162 if ((CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_all') ||
163 ($form->_task == CRM_Contact_Task::SAVE_SEARCH)
164 ) {
165 $sortByCharacter = $form->get('sortByCharacter');
5d272ea2 166 $cacheKey = ($sortByCharacter && $sortByCharacter != 'all') ? "{$cacheKey}_alphabet" : $cacheKey;
8ef12e64 167
66ceb5d9 168 // since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
8e1a7c71 169 // rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
170 // final result set
171 if ($useTable) {
172 $allCids = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey, "getall");
173 }
174 else {
175 $allCids[$cacheKey] = $form->getContactIds();
176 }
6a488035
TO
177
178 $form->_contactIds = array();
179 if ($useTable) {
180 $count = 0;
181 $insertString = array();
182 foreach ($allCids[$cacheKey] as $cid => $ignore) {
183 $count++;
184 $insertString[] = " ( {$cid} ) ";
185 if ($count % 200 == 0) {
186 $string = implode(',', $insertString);
187 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
188 CRM_Core_DAO::executeQuery($sql);
189 $insertString = array();
190 }
191 }
192 if (!empty($insertString)) {
193 $string = implode(',', $insertString);
194 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
195 CRM_Core_DAO::executeQuery($sql);
196 }
197 }
061ff68c 198 elseif (empty($form->_contactIds)) {
6a488035
TO
199 // filter duplicates here
200 // CRM-7058
201 // might be better to do this in the query, but that logic is a bit complex
202 // and it decides when to use distinct based on input criteria, which needs
203 // to be fixed and optimized.
204
205 foreach ($allCids[$cacheKey] as $cid => $ignore) {
206 $form->_contactIds[] = $cid;
207 }
208 }
209 }
210 elseif (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel') {
211 // selected contacts only
212 // need to perform action on only selected contacts
213 $insertString = array();
214
b44e3f84 215 // refire sql in case of custom search
6a488035
TO
216 if ($form->_action == CRM_Core_Action::COPY) {
217 // selected contacts only
218 // need to perform action on only selected contacts
219 foreach (self::$_searchFormValues as $name => $value) {
220 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
221 $contactID = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
222 if ($useTable) {
223 $insertString[] = " ( {$contactID} ) ";
224 }
225 else {
226 $form->_contactIds[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
227 }
228 }
229 }
230 }
231 else {
5d272ea2 232 // fetching selected contact ids of passed cache key
233 $selectedCids = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
234 foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
235 if ($useTable) {
236 $insertString[] = " ( {$selectedCid} ) ";
237 }
238 else {
239 $form->_contactIds[] = $selectedCid;
240 }
6a488035
TO
241 }
242 }
8ef12e64 243
6a488035
TO
244 if (!empty($insertString)) {
245 $string = implode(',', $insertString);
246 $sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
247 CRM_Core_DAO::executeQuery($sql);
248 }
249 }
250
251 //contact type for pick up profiles as per selected contact types with subtypes
252 //CRM-5521
253 if ($selectedTypes = CRM_Utils_Array::value('contact_type', self::$_searchFormValues)) {
254 if (!is_array($selectedTypes)) {
255 $selectedTypes = explode(' ', $selectedTypes);
256 }
257 foreach ($selectedTypes as $ct => $dontcare) {
258 if (strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR) === FALSE) {
259 $form->_contactTypes[] = $ct;
260 }
261 else {
262 $separator = strpos($ct, CRM_Core_DAO::VALUE_SEPARATOR);
263 $form->_contactTypes[] = substr($ct, $separator + 1);
264 }
265 }
266 }
267
6a488035 268 if (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel'
5d272ea2 269 && ($form->_action != CRM_Core_Action::COPY)
270 ) {
6a488035 271 $sel = CRM_Utils_Array::value('radio_ts', self::$_searchFormValues);
5d272ea2 272 $form->assign('searchtype', $sel);
6a488035
TO
273 $result = CRM_Core_BAO_PrevNextCache::getSelectedContacts();
274 $form->assign("value", $result);
275 }
8ef12e64 276
6a488035
TO
277 if (!empty($form->_contactIds)) {
278 $form->_componentClause = ' contact_a.id IN ( ' . implode(',', $form->_contactIds) . ' ) ';
279 $form->assign('totalSelectedContacts', count($form->_contactIds));
280
281 $form->_componentIds = $form->_contactIds;
282 }
283 }
284
285 /**
d8689418
EM
286 * Get the contact id for custom search.
287 *
288 * we are not using prev/next table in case of custom search
6a488035
TO
289 */
290 public function getContactIds() {
291 // need to perform action on all contacts
292 // fire the query again and get the contact id's + display name
293 $sortID = NULL;
294 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
295 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
296 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
297 );
298 }
299
300 $selectorName = $this->controller->selectorName();
6a488035
TO
301
302 $fv = $this->get('formValues');
303 $customClass = $this->get('customSearchClass');
6a488035
TO
304 $returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
305
5d272ea2 306 $selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
6a488035
TO
307
308 $params = $this->get('queryParams');
309
310 // fix for CRM-5165
311 $sortByCharacter = $this->get('sortByCharacter');
a7cddb8c 312 if ($sortByCharacter && $sortByCharacter != 1) {
6a488035
TO
313 $params[] = array('sortByCharacter', '=', $sortByCharacter, 0, 0);
314 }
315 $queryOperator = $this->get('queryOperator');
316 if (!$queryOperator) {
317 $queryOperator = 'AND';
318 }
ae066a2b 319 $dao = $selector->contactIDQuery($params, $sortID,
5d272ea2 320 CRM_Utils_Array::value('display_relationship_type', $fv),
6a488035
TO
321 $queryOperator
322 );
323
324 $contactIds = array();
5d272ea2 325 while ($dao->fetch()) {
6a488035
TO
326 $contactIds[$dao->contact_id] = $dao->contact_id;
327 }
328
329 return $contactIds;
330 }
331
332
333 /**
ee0ce2ef 334 * Set default values for the form. Relationship that in edit/view action.
6a488035 335 *
ee0ce2ef 336 * The default values are retrieved from the database.
6a488035 337 *
e2046b33 338 * @return array
6a488035 339 */
00be9182 340 public function setDefaultValues() {
6a488035
TO
341 $defaults = array();
342 return $defaults;
343 }
344
345 /**
57507ae6 346 * Add the rules for form.
6a488035 347 */
00be9182 348 public function addRules() {
5d272ea2 349 }
6a488035
TO
350
351 /**
5c9ff055 352 * Build the form object.
6a488035
TO
353 */
354 public function buildQuickForm() {
355 $this->addDefaultButtons(ts('Confirm Action'));
356 }
357
358 /**
ee0ce2ef 359 * Process the form after the input has been submitted and validated.
6a488035 360 */
5d272ea2 361 public function postProcess() {
362 }
363
6a488035 364 /**
57507ae6
EM
365 * Simple shell that derived classes can call to add form buttons.
366 *
367 * Allows customized title for the main Submit
6a488035 368 *
77c5b619
TO
369 * @param string $title
370 * Title of the main button.
371 * @param string $nextType
372 * Button type for the form after processing.
77b97be7
EM
373 * @param string $backType
374 * @param bool $submitOnce
6a488035 375 */
00be9182 376 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
6a488035
TO
377 $this->addButtons(array(
378 array(
379 'type' => $nextType,
380 'name' => $title,
381 'isDefault' => TRUE,
382 ),
383 array(
384 'type' => $backType,
385 'name' => ts('Cancel'),
0291a521 386 'icon' => 'fa-times',
6a488035
TO
387 ),
388 )
389 );
390 }
57884c26
DJ
391
392 /**
100fef9d 393 * Replace ids of household members in $this->_contactIds with the id of their household.
57884c26 394 *
5c9ff055 395 * CRM-8338
57884c26
DJ
396 */
397 public function mergeContactIdsByHousehold() {
398 if (empty($this->_contactIds)) {
399 return;
400 }
401
402 $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
403 NULL,
404 NULL,
405 NULL,
406 NULL,
407 TRUE,
408 'name',
409 FALSE
410 );
411
412 // Get Head of Household & Household Member relationships
413 $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
414 $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
415 $householdRelationshipTypes = array(
416 $relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
417 $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
418 );
419
420 $relID = implode(',', $this->_contactIds);
421
422 foreach ($householdRelationshipTypes as $rel => $dnt) {
423 list($id, $direction) = explode('_', $rel, 2);
424 // identify the relationship direction
425 $contactA = 'contact_id_a';
426 $contactB = 'contact_id_b';
427 if ($direction == 'b_a') {
428 $contactA = 'contact_id_b';
429 $contactB = 'contact_id_a';
430 }
431
432 // Find related households.
353ffa53 433 $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact ";
57884c26
DJ
434 $relationFrom = " FROM civicrm_contact contact_household
435 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_household.id AND crel.relationship_type_id = {$id} ";
436
437 // Check for active relationship status only.
353ffa53
TO
438 $today = date('Ymd');
439 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
440 $relationWhere = " WHERE contact_household.is_deleted = 0 AND crel.{$contactA} IN ( {$relID} ) {$relationActive}";
0ee5581e 441 $relationGroupBy = " GROUP BY crel.{$contactA}, contact_household.id";
57884c26
DJ
442 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationGroupBy";
443
444 $householdsDAO = CRM_Core_DAO::executeQuery($relationQueryString);
445 while ($householdsDAO->fetch()) {
446 // Remove contact's id from $this->_contactIds and replace with their household's id.
447 foreach (array_keys($this->_contactIds, $householdsDAO->refContact) as $idKey) {
448 unset($this->_contactIds[$idKey]);
449 }
450 if (!in_array($householdsDAO->household_id, $this->_contactIds)) {
451 $this->_contactIds[] = $householdsDAO->household_id;
452 }
453 }
454 $householdsDAO->free();
455 }
31fd348d
AS
456
457 // If contact list has changed, households will probably be at the end of
458 // the list. Sort it again by sort_name.
459 if (implode(',', $this->_contactIds) != $relID) {
31fd348d
AS
460 $result = civicrm_api3('Contact', 'get', array(
461 'return' => array('id'),
462 'id' => array('IN' => $this->_contactIds),
463 'options' => array(
464 'limit' => 0,
351b2dd9 465 'sort' => "sort_name",
31fd348d
AS
466 ),
467 ));
468 $this->_contactIds = array_keys($result['values']);
469 }
57884c26 470 }
96025800 471
36c74cd6
TO
472 /**
473 * Given this task's list of targets, produce a hidden group.
474 *
475 * @return array
476 * Array(0 => int $groupID, 1 => int|NULL $ssID).
477 * @throws Exception
478 */
479 public function createHiddenGroup() {
480 // Did the user select "All" matches or cherry-pick a few records?
481 $searchParams = $this->controller->exportValues();
482 if ($searchParams['radio_ts'] == 'ts_sel') {
483 // Create a static group.
36c74cd6
TO
484 $randID = md5(time() . rand(1, 1000)); // groups require a unique name
485 $grpTitle = "Hidden Group {$randID}";
486 $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
487
488 if (!$grpID) {
489 $groupParams = array(
490 'title' => $grpTitle,
491 'is_active' => 1,
492 'is_hidden' => 1,
493 'group_type' => array('2' => 1),
494 );
495
496 $group = CRM_Contact_BAO_Group::create($groupParams);
497 $grpID = $group->id;
498
499 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
500
501 $newGroupTitle = "Hidden Group {$grpID}";
502 $groupParams = array(
503 'id' => $grpID,
504 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
505 'title' => $newGroupTitle,
506 'group_type' => array('2' => 1),
507 );
5ab8fe4a 508 CRM_Contact_BAO_Group::create($groupParams);
36c74cd6
TO
509 }
510
511 // note at this point its a static group
512 return array($grpID, NULL);
513 }
514 else {
515 // Create a smart group.
36c74cd6
TO
516 $ssId = $this->get('ssID');
517 $hiddenSmartParams = array(
518 'group_type' => array('2' => 1),
519 'form_values' => $this->get('formValues'),
520 'saved_search_id' => $ssId,
521 'search_custom_id' => $this->get('customSearchID'),
522 'search_context' => $this->get('context'),
523 );
524
525 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
526 return array($smartGroupId, $savedSearchId);
527 }
528
529 }
530
6a488035 531}