3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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-2020
35 * Business object for Saved searches.
37 class CRM_Contact_BAO_SavedSearch
extends CRM_Contact_DAO_SavedSearch
{
42 public function __construct() {
43 parent
::__construct();
47 * Query the db for all saved searches.
50 * contains the search name as value and and id as key
52 public function getAll() {
53 $savedSearch = new CRM_Contact_DAO_SavedSearch();
54 $savedSearch->selectAdd();
55 $savedSearch->selectAdd('id, name');
57 while ($savedSearch->fetch()) {
58 $aSavedSearch[$savedSearch->id
] = $savedSearch->name
;
64 * Retrieve DB object based on input parameters.
66 * It also stores all the retrieved values in the default array.
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.
73 * @return CRM_Contact_BAO_SavedSearch
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);
86 * Given an id, extract the formValues of the saved search.
89 * The id of the saved search.
92 * the values of the posted saved search used as default values in various Search Form
94 public static function getFormValues($id) {
95 $specialDateFields = [
96 'event_start_date_low' => 'event_date_low',
97 'event_end_date_high' => 'event_date_high',
100 $fv = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
103 // make sure u unserialize - since it's stored in serialized form
104 $result = unserialize($fv);
107 $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'];
108 foreach ($result as $element => $value) {
109 if (CRM_Contact_BAO_Query
::isAlreadyProcessedForQueryFormat($value)) {
110 $id = CRM_Utils_Array
::value(0, $value);
111 $value = CRM_Utils_Array
::value(2, $value);
112 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
114 $value = CRM_Utils_Array
::value($op, $value);
115 if (in_array($op, ['BETWEEN', '>=', '<='])) {
116 self
::decodeRelativeFields($result, $id, $op, $value);
117 unset($result[$element]);
121 // Check for a date range field, which might be a standard date
122 // range or a relative date.
123 if (strpos($id, '_date_low') !== FALSE ||
strpos($id, '_date_high') !== FALSE) {
124 $entityName = strstr($id, '_date', TRUE);
126 // This is the default, for non relative dates. We will overwrite
127 // it if we determine this is a relative date.
128 $result[$id] = $value;
129 $result["{$entityName}_date_relative"] = 0;
131 if (!empty($result['relative_dates'])) {
132 if (array_key_exists($entityName, $result['relative_dates'])) {
133 // We have a match from a regular field.
135 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
137 elseif (!empty($specialDateFields[$id])) {
138 // We may have a match on a special date field.
139 $entityName = strstr($specialDateFields[$id], '_date', TRUE);
140 if (array_key_exists($entityName, $result['relative_dates'])) {
142 $result["{$entityName}_relative"] = $result['relative_dates'][$entityName];
148 $result[$id] = $value;
150 unset($result[$element]);
153 if (!empty($value) && is_array($value)) {
154 if (in_array($element, $specialFields)) {
155 // Remove the element to minimise support for legacy formats. It is stored in $value
156 // so will be re-set with the right name.
157 unset($result[$element]);
158 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
159 $element = str_replace('member_status_id', 'membership_status_id', $element);
160 CRM_Contact_BAO_Query
::legacyConvertFormValues($element, $value);
161 $result[$element] = $value;
163 // As per the OK (Operator as Key) value format, value array may contain key
164 // as an operator so to ensure the default is always set actual value
165 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
166 $result[$element] = CRM_Utils_Array
::value(key($value), $value);
167 if (is_string($result[$element])) {
168 $result[$element] = str_replace("%", '', $result[$element]);
172 if (substr($element, 0, 7) == 'custom_' &&
173 (substr($element, -5, 5) == '_from' ||
substr($element, -3, 3) == '_to')
175 // Ensure the _relative field is set if from or to are set to ensure custom date
176 // fields with 'from' or 'to' values are displayed when the are set in the smart group
177 // being loaded. (CRM-17116)
178 if (!isset($result[CRM_Contact_BAO_Query
::getCustomFieldName($element) . '_relative'])) {
179 $result[CRM_Contact_BAO_Query
::getCustomFieldName($element) . '_relative'] = 0;
182 // check to see if we need to convert the old privacy array
184 if (!empty($result['privacy'])) {
185 if (is_array($result['privacy'])) {
186 $result['privacy_operator'] = 'AND';
187 $result['privacy_toggle'] = 1;
188 if (isset($result['privacy']['do_not_toggle'])) {
189 if ($result['privacy']['do_not_toggle']) {
190 $result['privacy_toggle'] = 2;
192 unset($result['privacy']['do_not_toggle']);
195 $result['privacy_options'] = [];
196 foreach ($result['privacy'] as $name => $val) {
198 $result['privacy_options'][] = $name;
202 unset($result['privacy']);
206 if ($customSearchClass = CRM_Utils_Array
::value('customSearchClass', $result)) {
207 // check if there is a special function - formatSavedSearchFields defined in the custom search form
208 if (method_exists($customSearchClass, 'formatSavedSearchFields')) {
209 $customSearchClass::formatSavedSearchFields($result);
217 * Get search parameters.
223 public static function getSearchParams($id) {
224 $fv = self
::getFormValues($id);
225 //check if the saved search has mapping id
226 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
227 return CRM_Core_BAO_Mapping
::formattedFields($fv);
229 elseif (!empty($fv['customSearchID'])) {
233 return CRM_Contact_BAO_Query
::convertFormValues($fv);
238 * Get the where clause for a saved search.
242 * @param array $tables
243 * (reference ) add the tables that are needed for the select clause.
244 * @param array $whereTables
245 * (reference ) add the tables that are needed for the where clause.
248 * the where clause for this saved search
250 public static function whereClause($id, &$tables, &$whereTables) {
251 $params = self
::getSearchParams($id);
253 if (!empty($params['customSearchID'])) {
254 // this has not yet been implemented
257 return CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
264 * Contact IDS Sql (whatever that means!).
270 public static function contactIDsSQL($id) {
271 $params = self
::getSearchParams($id);
272 if ($params && !empty($params['customSearchID'])) {
273 return CRM_Contact_BAO_SearchCustom
::contactIDSQL(NULL, $id);
276 $tables = $whereTables = ['civicrm_contact' => 1];
277 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
281 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
290 * Get from where email (whatever that means!).
296 public static function fromWhereEmail($id) {
297 $params = self
::getSearchParams($id);
300 if (!empty($params['customSearchID'])) {
301 return CRM_Contact_BAO_SearchCustom
::fromWhereEmail(NULL, $id);
304 $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1];
305 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
306 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
307 return [$from, $where];
313 FROM civicrm_contact contact_a
314 LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
317 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
318 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
319 return [$from, $where];
324 * Given an id, get the name of the saved search.
327 * The id of the saved search.
329 * @param string $value
332 * the name of the saved search
334 public static function getName($id, $value = 'name') {
335 $group = new CRM_Contact_DAO_Group();
336 $group->saved_search_id
= $id;
337 if ($group->find(TRUE)) {
338 return $group->$value;
344 * Create a smart group from normalised values.
346 * @param array $params
348 * @return \CRM_Contact_DAO_SavedSearch
350 public static function create(&$params) {
351 $savedSearch = new CRM_Contact_DAO_SavedSearch();
352 if (isset($params['formValues']) &&
353 !empty($params['formValues'])
355 $savedSearch->form_values
= serialize($params['formValues']);
358 $savedSearch->form_values
= NULL;
361 $savedSearch->is_active
= CRM_Utils_Array
::value('is_active', $params, 1);
362 $savedSearch->mapping_id
= CRM_Utils_Array
::value('mapping_id', $params, 'null');
363 $savedSearch->custom_search_id
= CRM_Utils_Array
::value('custom_search_id', $params, 'null');
364 $savedSearch->id
= CRM_Utils_Array
::value('id', $params, NULL);
366 $savedSearch->save();
374 * @param string $fieldName
375 * @param array $fieldDef
376 * @param int $counter
378 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
379 if ($fieldName == 'form_values') {
380 // A dummy value for form_values.
381 $this->{$fieldName} = serialize(
382 ['sort_name' => "SortName{$counter}"]);
385 parent
::assignTestValues($fieldName, $fieldDef, $counter);
390 * Store search variables in $queryParams which were skipped while processing query params,
391 * precisely at CRM_Contact_BAO_Query::fixWhereValues(...). But these variable are required in
392 * building smart group criteria otherwise it will cause issues like CRM-18585,CRM-19571
394 * @param array $queryParams
395 * @param array $formValues
397 public static function saveSkippedElement(&$queryParams, $formValues) {
398 // these are elements which are skipped in a smart group criteria
402 'display_relationship_type',
405 foreach ($specialElements as $element) {
406 if (!empty($formValues[$element])) {
407 $queryParams[] = [$element, '=', $formValues[$element], 0, 0];
413 * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...))
414 * into desired formValues
416 * @param array $formValues
417 * @param string $fieldName
419 * @param array|string|int $value
421 * @throws \CiviCRM_API3_Exception
423 public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) {
424 // check if its a custom date field, if yes then 'searchDate' format the value
425 if (CRM_Contact_BAO_Query
::isCustomDateField($fieldName)) {
431 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value;
435 $formValues[$fieldName . '_from'] = $value;
439 $formValues[$fieldName . '_to'] = $value;