3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business object for Saved searches.
21 class CRM_Contact_BAO_SavedSearch
extends CRM_Contact_DAO_SavedSearch
{
26 public function __construct() {
27 parent
::__construct();
31 * Query the db for all saved searches.
34 * contains the search name as value and and id as key
36 public function getAll() {
37 $savedSearch = new CRM_Contact_DAO_SavedSearch();
38 $savedSearch->selectAdd();
39 $savedSearch->selectAdd('id, name');
41 while ($savedSearch->fetch()) {
42 $aSavedSearch[$savedSearch->id
] = $savedSearch->name
;
48 * Retrieve DB object based on input parameters.
50 * It also stores all the retrieved values in the default array.
52 * @param array $params
53 * (reference ) an assoc array of name/value pairs.
54 * @param array $defaults
55 * (reference ) an assoc array to hold the flattened values.
57 * @return CRM_Contact_BAO_SavedSearch
59 public static function retrieve(&$params, &$defaults) {
60 $savedSearch = new CRM_Contact_DAO_SavedSearch();
61 $savedSearch->copyValues($params);
62 if ($savedSearch->find(TRUE)) {
63 CRM_Core_DAO
::storeValues($savedSearch, $defaults);
70 * Given an id, extract the formValues of the saved search.
73 * The id of the saved search.
76 * the values of the posted saved search used as default values in various Search Form
78 public static function getFormValues($id) {
79 $specialDateFields = [
80 'event_start_date_low' => 'event_date_low',
81 'event_end_date_high' => 'event_date_high',
84 $fv = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
87 // make sure u CRM_Utils_String::unserialize - since it's stored in serialized form
88 $result = CRM_Utils_String
::unserialize($fv);
91 $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'];
92 foreach ($result as $element => $value) {
93 if (CRM_Contact_BAO_Query
::isAlreadyProcessedForQueryFormat($value)) {
94 $id = CRM_Utils_Array
::value(0, $value);
95 $value = CRM_Utils_Array
::value(2, $value);
96 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
98 $value = CRM_Utils_Array
::value($op, $value);
99 if (in_array($op, ['BETWEEN', '>=', '<='])) {
100 self
::decodeRelativeFields($result, $id, $op, $value);
101 unset($result[$element]);
105 // Check for a date range field, which might be a standard date
106 // range or a relative date.
107 if (strpos($id, '_date_low') !== FALSE ||
strpos($id, '_date_high') !== FALSE) {
108 $entityName = strstr($id, '_date', TRUE);
110 // This is the default, for non relative dates. We will overwrite
111 // it if we determine this is a relative date.
112 $result[$id] = $value;
113 $result["{$entityName}_date_relative"] = 0;
115 if (!empty($result['relative_dates'])) {
116 if (array_key_exists($entityName, $result['relative_dates'])) {
117 // We have a match from a regular field.
119 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
121 elseif (!empty($specialDateFields[$id])) {
122 // We may have a match on a special date field.
123 $entityName = strstr($specialDateFields[$id], '_date', TRUE);
124 if (array_key_exists($entityName, $result['relative_dates'])) {
126 $result["{$entityName}_relative"] = $result['relative_dates'][$entityName];
132 $result[$id] = $value;
134 unset($result[$element]);
137 if (!empty($value) && is_array($value)) {
138 if (in_array($element, $specialFields)) {
139 // Remove the element to minimise support for legacy formats. It is stored in $value
140 // so will be re-set with the right name.
141 unset($result[$element]);
142 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
143 $element = str_replace('member_status_id', 'membership_status_id', $element);
144 CRM_Contact_BAO_Query
::legacyConvertFormValues($element, $value);
145 $result[$element] = $value;
147 // As per the OK (Operator as Key) value format, value array may contain key
148 // as an operator so to ensure the default is always set actual value
149 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
150 $result[$element] = CRM_Utils_Array
::value(key($value), $value);
151 if (is_string($result[$element])) {
152 $result[$element] = str_replace("%", '', $result[$element]);
156 // We should only set the relative key for custom date fields if it is not already set in the array.
157 $realField = str_replace(['_relative', '_low', '_high', '_to', '_high'], '', $element);
158 if (substr($element, 0, 7) == 'custom_' && CRM_Contact_BAO_Query
::isCustomDateField($realField)) {
159 if (!isset($result[$realField . '_relative'])) {
160 $result[$realField . '_relative'] = 0;
163 // check to see if we need to convert the old privacy array
165 if (!empty($result['privacy'])) {
166 if (is_array($result['privacy'])) {
167 $result['privacy_operator'] = 'AND';
168 $result['privacy_toggle'] = 1;
169 if (isset($result['privacy']['do_not_toggle'])) {
170 if ($result['privacy']['do_not_toggle']) {
171 $result['privacy_toggle'] = 2;
173 unset($result['privacy']['do_not_toggle']);
176 $result['privacy_options'] = [];
177 foreach ($result['privacy'] as $name => $val) {
179 $result['privacy_options'][] = $name;
183 unset($result['privacy']);
187 if ($customSearchClass = CRM_Utils_Array
::value('customSearchClass', $result)) {
188 // check if there is a special function - formatSavedSearchFields defined in the custom search form
189 if (method_exists($customSearchClass, 'formatSavedSearchFields')) {
190 $customSearchClass::formatSavedSearchFields($result);
198 * Get search parameters.
204 public static function getSearchParams($id) {
205 $fv = self
::getFormValues($id);
206 //check if the saved search has mapping id
207 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
208 return CRM_Core_BAO_Mapping
::formattedFields($fv);
210 elseif (!empty($fv['customSearchID'])) {
214 return CRM_Contact_BAO_Query
::convertFormValues($fv);
219 * Get the where clause for a saved search.
223 * @param array $tables
224 * (reference ) add the tables that are needed for the select clause.
225 * @param array $whereTables
226 * (reference ) add the tables that are needed for the where clause.
229 * the where clause for this saved search
231 public static function whereClause($id, &$tables, &$whereTables) {
232 $params = self
::getSearchParams($id);
234 if (!empty($params['customSearchID'])) {
235 // this has not yet been implemented
238 return CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
245 * Contact IDS Sql (whatever that means!).
251 public static function contactIDsSQL($id) {
252 $params = self
::getSearchParams($id);
253 if ($params && !empty($params['customSearchID'])) {
254 return CRM_Contact_BAO_SearchCustom
::contactIDSQL(NULL, $id);
257 $tables = $whereTables = ['civicrm_contact' => 1];
258 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
262 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
271 * Get from where email (whatever that means!).
277 public static function fromWhereEmail($id) {
278 $params = self
::getSearchParams($id);
281 if (!empty($params['customSearchID'])) {
282 return CRM_Contact_BAO_SearchCustom
::fromWhereEmail(NULL, $id);
285 $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1];
286 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
287 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
288 return [$from, $where];
294 FROM civicrm_contact contact_a
295 LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
298 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
299 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
300 return [$from, $where];
305 * Given an id, get the name of the saved search.
308 * The id of the saved search.
310 * @param string $value
313 * the name of the saved search
315 public static function getName($id, $value = 'name') {
316 $group = new CRM_Contact_DAO_Group();
317 $group->saved_search_id
= $id;
318 if ($group->find(TRUE)) {
319 return $group->$value;
325 * Create a smart group from normalised values.
327 * @param array $params
329 * @return \CRM_Contact_DAO_SavedSearch
331 public static function create(&$params) {
332 $savedSearch = new CRM_Contact_DAO_SavedSearch();
333 if (isset($params['formValues']) &&
334 !empty($params['formValues'])
336 $savedSearch->form_values
= serialize($params['formValues']);
339 $savedSearch->form_values
= NULL;
342 $savedSearch->is_active
= CRM_Utils_Array
::value('is_active', $params, 1);
343 $savedSearch->mapping_id
= CRM_Utils_Array
::value('mapping_id', $params, 'null');
344 $savedSearch->custom_search_id
= CRM_Utils_Array
::value('custom_search_id', $params, 'null');
345 $savedSearch->id
= CRM_Utils_Array
::value('id', $params, NULL);
347 $savedSearch->save();
355 * @param string $fieldName
356 * @param array $fieldDef
357 * @param int $counter
359 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
360 if ($fieldName == 'form_values') {
361 // A dummy value for form_values.
362 $this->{$fieldName} = serialize(
363 ['sort_name' => "SortName{$counter}"]);
366 parent
::assignTestValues($fieldName, $fieldDef, $counter);
371 * Store search variables in $queryParams which were skipped while processing query params,
372 * precisely at CRM_Contact_BAO_Query::fixWhereValues(...). But these variable are required in
373 * building smart group criteria otherwise it will cause issues like CRM-18585,CRM-19571
375 * @param array $queryParams
376 * @param array $formValues
378 public static function saveSkippedElement(&$queryParams, $formValues) {
379 // these are elements which are skipped in a smart group criteria
383 'display_relationship_type',
386 foreach ($specialElements as $element) {
387 if (!empty($formValues[$element])) {
388 $queryParams[] = [$element, '=', $formValues[$element], 0, 0];
394 * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...))
395 * into desired formValues
397 * @param array $formValues
398 * @param string $fieldName
400 * @param array|string|int $value
402 * @throws \CiviCRM_API3_Exception
404 public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) {
405 // check if its a custom date field, if yes then 'searchDate' format the value
406 if (CRM_Contact_BAO_Query
::isCustomDateField($fieldName)) {
412 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value;
416 $formValues[$fieldName . '_from'] = $value;
420 $formValues[$fieldName . '_to'] = $value;