Merge pull request #14891 from eileenmcnaughton/saved_search
[civicrm-core.git] / CRM / Contact / BAO / SavedSearch.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 * Business object for Saved searches.
36 */
37 class CRM_Contact_BAO_SavedSearch extends CRM_Contact_DAO_SavedSearch {
38
39 /**
40 * Class constructor.
41 */
42 public function __construct() {
43 parent::__construct();
44 }
45
46 /**
47 * Query the db for all saved searches.
48 *
49 * @return array
50 * contains the search name as value and and id as key
51 */
52 public function getAll() {
53 $savedSearch = new CRM_Contact_DAO_SavedSearch();
54 $savedSearch->selectAdd();
55 $savedSearch->selectAdd('id, name');
56 $savedSearch->find();
57 while ($savedSearch->fetch()) {
58 $aSavedSearch[$savedSearch->id] = $savedSearch->name;
59 }
60 return $aSavedSearch;
61 }
62
63 /**
64 * Retrieve DB object based on input parameters.
65 *
66 * It also stores all the retrieved values in the default array.
67 *
68 * @param array $params
69 * (reference ) an assoc array of name/value pairs.
70 * @param array $defaults
71 * (reference ) an assoc array to hold the flattened values.
72 *
73 * @return CRM_Contact_BAO_SavedSearch
74 */
75 public static function retrieve(&$params, &$defaults) {
76 $savedSearch = new CRM_Contact_DAO_SavedSearch();
77 $savedSearch->copyValues($params);
78 if ($savedSearch->find(TRUE)) {
79 CRM_Core_DAO::storeValues($savedSearch, $defaults);
80 return $savedSearch;
81 }
82 return NULL;
83 }
84
85 /**
86 * Given an id, extract the formValues of the saved search.
87 *
88 * @param int $id
89 * The id of the saved search.
90 *
91 * @return array
92 * the values of the posted saved search used as default values in various Search Form
93 */
94 public static function getFormValues($id) {
95 $specialDateFields = [
96 'event_start_date_low' => 'event_date_low',
97 'event_end_date_high' => 'event_date_high',
98 'case_from_start_date_low' => 'case_from_date_low',
99 'case_from_start_date_high' => 'case_from_date_high',
100 'case_to_end_date_low' => 'case_to_date_low',
101 'case_to_end_date_high' => 'case_to_date_high',
102 ];
103
104 $fv = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
105 $result = NULL;
106 if ($fv) {
107 // make sure u unserialize - since it's stored in serialized form
108 $result = unserialize($fv);
109 }
110
111 $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'];
112 foreach ($result as $element => $value) {
113 if (CRM_Contact_BAO_Query::isAlreadyProcessedForQueryFormat($value)) {
114 $id = CRM_Utils_Array::value(0, $value);
115 $value = CRM_Utils_Array::value(2, $value);
116 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
117 $op = key($value);
118 $value = CRM_Utils_Array::value($op, $value);
119 if (in_array($op, ['BETWEEN', '>=', '<='])) {
120 self::decodeRelativeFields($result, $id, $op, $value);
121 unset($result[$element]);
122 continue;
123 }
124 }
125 // Check for a date range field, which might be a standard date
126 // range or a relative date.
127 if (strpos($id, '_date_low') !== FALSE || strpos($id, '_date_high') !== FALSE) {
128 $entityName = strstr($id, '_date', TRUE);
129
130 // This is the default, for non relative dates. We will overwrite
131 // it if we determine this is a relative date.
132 $result[$id] = $value;
133 $result["{$entityName}_date_relative"] = 0;
134
135 if (!empty($result['relative_dates'])) {
136 if (array_key_exists($entityName, $result['relative_dates'])) {
137 // We have a match from a regular field.
138 $result[$id] = NULL;
139 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
140 }
141 elseif (!empty($specialDateFields[$id])) {
142 // We may have a match on a special date field.
143 $entityName = strstr($specialDateFields[$id], '_date', TRUE);
144 if (array_key_exists($entityName, $result['relative_dates'])) {
145 $result[$id] = NULL;
146 $result["{$entityName}_relative"] = $result['relative_dates'][$entityName];
147 }
148 }
149 }
150 }
151 else {
152 $result[$id] = $value;
153 }
154 unset($result[$element]);
155 continue;
156 }
157 if (!empty($value) && is_array($value)) {
158 if (in_array($element, $specialFields)) {
159 // Remove the element to minimise support for legacy formats. It is stored in $value
160 // so will be re-set with the right name.
161 unset($result[$element]);
162 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
163 $element = str_replace('member_status_id', 'membership_status_id', $element);
164 CRM_Contact_BAO_Query::legacyConvertFormValues($element, $value);
165 $result[$element] = $value;
166 }
167 // As per the OK (Operator as Key) value format, value array may contain key
168 // as an operator so to ensure the default is always set actual value
169 elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
170 $result[$element] = CRM_Utils_Array::value(key($value), $value);
171 if (is_string($result[$element])) {
172 $result[$element] = str_replace("%", '', $result[$element]);
173 }
174 }
175 }
176 if (substr($element, 0, 7) == 'custom_' &&
177 (substr($element, -5, 5) == '_from' || substr($element, -3, 3) == '_to')
178 ) {
179 // Ensure the _relative field is set if from or to are set to ensure custom date
180 // fields with 'from' or 'to' values are displayed when the are set in the smart group
181 // being loaded. (CRM-17116)
182 if (!isset($result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'])) {
183 $result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'] = 0;
184 }
185 }
186 // check to see if we need to convert the old privacy array
187 // CRM-9180
188 if (!empty($result['privacy'])) {
189 if (is_array($result['privacy'])) {
190 $result['privacy_operator'] = 'AND';
191 $result['privacy_toggle'] = 1;
192 if (isset($result['privacy']['do_not_toggle'])) {
193 if ($result['privacy']['do_not_toggle']) {
194 $result['privacy_toggle'] = 2;
195 }
196 unset($result['privacy']['do_not_toggle']);
197 }
198
199 $result['privacy_options'] = [];
200 foreach ($result['privacy'] as $name => $val) {
201 if ($val) {
202 $result['privacy_options'][] = $name;
203 }
204 }
205 }
206 unset($result['privacy']);
207 }
208 }
209
210 if ($customSearchClass = CRM_Utils_Array::value('customSearchClass', $result)) {
211 // check if there is a special function - formatSavedSearchFields defined in the custom search form
212 if (method_exists($customSearchClass, 'formatSavedSearchFields')) {
213 $customSearchClass::formatSavedSearchFields($result);
214 }
215 }
216
217 return $result;
218 }
219
220 /**
221 * Get search parameters.
222 *
223 * @param int $id
224 *
225 * @return array
226 */
227 public static function getSearchParams($id) {
228 $fv = self::getFormValues($id);
229 //check if the saved search has mapping id
230 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
231 return CRM_Core_BAO_Mapping::formattedFields($fv);
232 }
233 elseif (!empty($fv['customSearchID'])) {
234 return $fv;
235 }
236 else {
237 return CRM_Contact_BAO_Query::convertFormValues($fv);
238 }
239 }
240
241 /**
242 * Get the where clause for a saved search.
243 *
244 * @param int $id
245 * Saved search id.
246 * @param array $tables
247 * (reference ) add the tables that are needed for the select clause.
248 * @param array $whereTables
249 * (reference ) add the tables that are needed for the where clause.
250 *
251 * @return string
252 * the where clause for this saved search
253 */
254 public static function whereClause($id, &$tables, &$whereTables) {
255 $params = self::getSearchParams($id);
256 if ($params) {
257 if (!empty($params['customSearchID'])) {
258 // this has not yet been implemented
259 }
260 else {
261 return CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
262 }
263 }
264 return NULL;
265 }
266
267 /**
268 * Contact IDS Sql (whatever that means!).
269 *
270 * @param int $id
271 *
272 * @return string
273 */
274 public static function contactIDsSQL($id) {
275 $params = self::getSearchParams($id);
276 if ($params && !empty($params['customSearchID'])) {
277 return CRM_Contact_BAO_SearchCustom::contactIDSQL(NULL, $id);
278 }
279 else {
280 $tables = $whereTables = ['civicrm_contact' => 1];
281 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
282 if (!$where) {
283 $where = '( 1 )';
284 }
285 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
286 return "
287 SELECT contact_a.id
288 $from
289 WHERE $where";
290 }
291 }
292
293 /**
294 * Get from where email (whatever that means!).
295 *
296 * @param int $id
297 *
298 * @return array
299 */
300 public static function fromWhereEmail($id) {
301 $params = self::getSearchParams($id);
302
303 if ($params) {
304 if (!empty($params['customSearchID'])) {
305 return CRM_Contact_BAO_SearchCustom::fromWhereEmail(NULL, $id);
306 }
307 else {
308 $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1];
309 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
310 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
311 return [$from, $where];
312 }
313 }
314 else {
315 // fix for CRM-7240
316 $from = "
317 FROM civicrm_contact contact_a
318 LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
319 ";
320 $where = " ( 1 ) ";
321 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
322 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
323 return [$from, $where];
324 }
325 }
326
327 /**
328 * Given an id, get the name of the saved search.
329 *
330 * @param int $id
331 * The id of the saved search.
332 *
333 * @param string $value
334 *
335 * @return string
336 * the name of the saved search
337 */
338 public static function getName($id, $value = 'name') {
339 $group = new CRM_Contact_DAO_Group();
340 $group->saved_search_id = $id;
341 if ($group->find(TRUE)) {
342 return $group->$value;
343 }
344 return NULL;
345 }
346
347 /**
348 * Create a smart group from normalised values.
349 *
350 * @param array $params
351 *
352 * @return \CRM_Contact_DAO_SavedSearch
353 */
354 public static function create(&$params) {
355 $savedSearch = new CRM_Contact_DAO_SavedSearch();
356 if (isset($params['formValues']) &&
357 !empty($params['formValues'])
358 ) {
359 $savedSearch->form_values = serialize($params['formValues']);
360 }
361 else {
362 $savedSearch->form_values = NULL;
363 }
364
365 $savedSearch->is_active = CRM_Utils_Array::value('is_active', $params, 1);
366 $savedSearch->mapping_id = CRM_Utils_Array::value('mapping_id', $params, 'null');
367 $savedSearch->custom_search_id = CRM_Utils_Array::value('custom_search_id', $params, 'null');
368 $savedSearch->id = CRM_Utils_Array::value('id', $params, NULL);
369
370 $savedSearch->save();
371
372 return $savedSearch;
373 }
374
375 /**
376 * Assign test value.
377 *
378 * @param string $fieldName
379 * @param array $fieldDef
380 * @param int $counter
381 */
382 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
383 if ($fieldName == 'form_values') {
384 // A dummy value for form_values.
385 $this->{$fieldName} = serialize(
386 ['sort_name' => "SortName{$counter}"]);
387 }
388 else {
389 parent::assignTestValues($fieldName, $fieldDef, $counter);
390 }
391 }
392
393 /**
394 * Store relative dates in separate array format
395 *
396 * @param array $queryParams
397 * @param array $formValues
398 */
399 public static function saveRelativeDates(&$queryParams, $formValues) {
400 // This is required only until all fields are converted to datepicker fields as the new format is truer to the
401 // form format and simply saves (e.g) custom_3_relative => "this.year"
402 $relativeDates = ['relative_dates' => []];
403 $specialDateFields = [
404 'event_relative',
405 'case_from_relative',
406 'case_to_relative',
407 'participant_relative',
408 'log_date_relative',
409 'birth_date_relative',
410 'deceased_date_relative',
411 'mailing_date_relative',
412 'relation_date_relative',
413 'relation_start_date_relative',
414 'relation_end_date_relative',
415 'relation_action_date_relative',
416 ];
417 foreach ($formValues as $id => $value) {
418 if (in_array($id, $specialDateFields) && !empty($value)) {
419 $entityName = strstr($id, '_date', TRUE);
420 if (empty($entityName)) {
421 $entityName = strstr($id, '_relative', TRUE);
422 }
423 $relativeDates['relative_dates'][$entityName] = $value;
424 }
425 }
426 // merge with original queryParams if relative date value(s) found
427 if (count($relativeDates['relative_dates'])) {
428 $queryParams = array_merge($queryParams, $relativeDates);
429 }
430 }
431
432 /**
433 * Store search variables in $queryParams which were skipped while processing query params,
434 * precisely at CRM_Contact_BAO_Query::fixWhereValues(...). But these variable are required in
435 * building smart group criteria otherwise it will cause issues like CRM-18585,CRM-19571
436 *
437 * @param array $queryParams
438 * @param array $formValues
439 */
440 public static function saveSkippedElement(&$queryParams, $formValues) {
441 // these are elements which are skipped in a smart group criteria
442 $specialElements = [
443 'operator',
444 'component_mode',
445 'display_relationship_type',
446 'uf_group_id',
447 ];
448 foreach ($specialElements as $element) {
449 if (!empty($formValues[$element])) {
450 $queryParams[] = [$element, '=', $formValues[$element], 0, 0];
451 }
452 }
453 }
454
455 /**
456 * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...))
457 * into desired formValues
458 *
459 * @param array $formValues
460 * @param string $fieldName
461 * @param string $op
462 * @param array|string|int $value
463 */
464 public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) {
465 // check if its a custom date field, if yes then 'searchDate' format the value
466 $isCustomDateField = CRM_Contact_BAO_Query::isCustomDateField($fieldName);
467
468 // select date range as default
469 if ($isCustomDateField) {
470 if (array_key_exists('relative_dates', $formValues) && array_key_exists($fieldName, $formValues['relative_dates'])) {
471 $formValues[$fieldName . '_relative'] = $formValues['relative_dates'][$fieldName];
472 }
473 else {
474 $formValues[$fieldName . '_relative'] = 0;
475 }
476 }
477 switch ($op) {
478 case 'BETWEEN':
479 if ($isCustomDateField) {
480 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date::setDateDefaults($value[0], 'searchDate');
481 list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date::setDateDefaults($value[1], 'searchDate');
482 }
483 else {
484 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value;
485 }
486 break;
487
488 case '>=':
489 if ($isCustomDateField) {
490 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date::setDateDefaults($value, 'searchDate');
491 }
492 else {
493 $formValues[$fieldName . '_from'] = $value;
494 }
495 break;
496
497 case '<=':
498 if ($isCustomDateField) {
499 list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date::setDateDefaults($value, 'searchDate');
500 }
501 else {
502 $formValues[$fieldName . '_to'] = $value;
503 }
504 break;
505 }
506 }
507
508 }