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 * 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',
98 'participant_register_date_low' => 'participant_date_low',
99 'participant_register_date_high' => 'participant_date_high',
100 'case_from_start_date_low' => 'case_from_date_low',
101 'case_from_start_date_high' => 'case_from_date_high',
102 'case_to_end_date_low' => 'case_to_date_low',
103 'case_to_end_date_high' => 'case_to_date_high',
106 $fv = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
109 // make sure u unserialize - since it's stored in serialized form
110 $result = unserialize($fv);
113 $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'];
114 foreach ($result as $element => $value) {
115 if (CRM_Contact_BAO_Query
::isAlreadyProcessedForQueryFormat($value)) {
116 $id = CRM_Utils_Array
::value(0, $value);
117 $value = CRM_Utils_Array
::value(2, $value);
118 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
120 $value = CRM_Utils_Array
::value($op, $value);
121 if (in_array($op, ['BETWEEN', '>=', '<='])) {
122 self
::decodeRelativeFields($result, $id, $op, $value);
123 unset($result[$element]);
127 // Check for a date range field, which might be a standard date
128 // range or a relative date.
129 if (strpos($id, '_date_low') !== FALSE ||
strpos($id, '_date_high') !== FALSE) {
130 $entityName = strstr($id, '_date', TRUE);
132 // This is the default, for non relative dates. We will overwrite
133 // it if we determine this is a relative date.
134 $result[$id] = $value;
135 $result["{$entityName}_date_relative"] = 0;
137 if (!empty($result['relative_dates'])) {
138 if (array_key_exists($entityName, $result['relative_dates'])) {
139 // We have a match from a regular field.
141 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
143 elseif (!empty($specialDateFields[$id])) {
144 // We may have a match on a special date field.
145 $entityName = strstr($specialDateFields[$id], '_date', TRUE);
146 if (array_key_exists($entityName, $result['relative_dates'])) {
148 $result["{$entityName}_relative"] = $result['relative_dates'][$entityName];
154 $result[$id] = $value;
156 unset($result[$element]);
159 if (!empty($value) && is_array($value)) {
160 if (in_array($element, $specialFields)) {
161 // Remove the element to minimise support for legacy formats. It is stored in $value
162 // so will be re-set with the right name.
163 unset($result[$element]);
164 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
165 $element = str_replace('member_status_id', 'membership_status_id', $element);
166 CRM_Contact_BAO_Query
::legacyConvertFormValues($element, $value);
167 $result[$element] = $value;
169 // As per the OK (Operator as Key) value format, value array may contain key
170 // as an operator so to ensure the default is always set actual value
171 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
172 $result[$element] = CRM_Utils_Array
::value(key($value), $value);
173 if (is_string($result[$element])) {
174 $result[$element] = str_replace("%", '', $result[$element]);
178 if (substr($element, 0, 7) == 'custom_' &&
179 (substr($element, -5, 5) == '_from' ||
substr($element, -3, 3) == '_to')
181 // Ensure the _relative field is set if from or to are set to ensure custom date
182 // fields with 'from' or 'to' values are displayed when the are set in the smart group
183 // being loaded. (CRM-17116)
184 if (!isset($result[CRM_Contact_BAO_Query
::getCustomFieldName($element) . '_relative'])) {
185 $result[CRM_Contact_BAO_Query
::getCustomFieldName($element) . '_relative'] = 0;
188 // check to see if we need to convert the old privacy array
190 if (!empty($result['privacy'])) {
191 if (is_array($result['privacy'])) {
192 $result['privacy_operator'] = 'AND';
193 $result['privacy_toggle'] = 1;
194 if (isset($result['privacy']['do_not_toggle'])) {
195 if ($result['privacy']['do_not_toggle']) {
196 $result['privacy_toggle'] = 2;
198 unset($result['privacy']['do_not_toggle']);
201 $result['privacy_options'] = [];
202 foreach ($result['privacy'] as $name => $val) {
204 $result['privacy_options'][] = $name;
208 unset($result['privacy']);
212 if ($customSearchClass = CRM_Utils_Array
::value('customSearchClass', $result)) {
213 // check if there is a special function - formatSavedSearchFields defined in the custom search form
214 if (method_exists($customSearchClass, 'formatSavedSearchFields')) {
215 $customSearchClass::formatSavedSearchFields($result);
223 * Get search parameters.
229 public static function getSearchParams($id) {
230 $fv = self
::getFormValues($id);
231 //check if the saved search has mapping id
232 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
233 return CRM_Core_BAO_Mapping
::formattedFields($fv);
235 elseif (!empty($fv['customSearchID'])) {
239 return CRM_Contact_BAO_Query
::convertFormValues($fv);
244 * Get the where clause for a saved search.
248 * @param array $tables
249 * (reference ) add the tables that are needed for the select clause.
250 * @param array $whereTables
251 * (reference ) add the tables that are needed for the where clause.
254 * the where clause for this saved search
256 public static function whereClause($id, &$tables, &$whereTables) {
257 $params = self
::getSearchParams($id);
259 if (!empty($params['customSearchID'])) {
260 // this has not yet been implemented
263 return CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
270 * Contact IDS Sql (whatever that means!).
276 public static function contactIDsSQL($id) {
277 $params = self
::getSearchParams($id);
278 if ($params && !empty($params['customSearchID'])) {
279 return CRM_Contact_BAO_SearchCustom
::contactIDSQL(NULL, $id);
282 $tables = $whereTables = ['civicrm_contact' => 1];
283 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
287 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
296 * Get from where email (whatever that means!).
302 public static function fromWhereEmail($id) {
303 $params = self
::getSearchParams($id);
306 if (!empty($params['customSearchID'])) {
307 return CRM_Contact_BAO_SearchCustom
::fromWhereEmail(NULL, $id);
310 $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1];
311 $where = CRM_Contact_BAO_SavedSearch
::whereClause($id, $tables, $whereTables);
312 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
313 return [$from, $where];
319 FROM civicrm_contact contact_a
320 LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
323 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
324 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
325 return [$from, $where];
330 * Given a saved search compute the clause and the tables and store it for future use.
332 public function buildClause() {
333 $fv = unserialize($this->form_values
);
335 if ($this->mapping_id
) {
336 $params = CRM_Core_BAO_Mapping
::formattedFields($fv);
339 $params = CRM_Contact_BAO_Query
::convertFormValues($fv);
342 if (!empty($params)) {
343 $tables = $whereTables = [];
344 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
345 if (!empty($tables)) {
346 $this->select_tables
= serialize($tables);
348 if (!empty($whereTables)) {
349 $this->where_tables
= serialize($whereTables);
359 public function save($hook = TRUE) {
360 // first build the computed fields
361 $this->buildClause();
367 * Given an id, get the name of the saved search.
370 * The id of the saved search.
372 * @param string $value
375 * the name of the saved search
377 public static function getName($id, $value = 'name') {
378 $group = new CRM_Contact_DAO_Group();
379 $group->saved_search_id
= $id;
380 if ($group->find(TRUE)) {
381 return $group->$value;
387 * Create a smart group from normalised values.
389 * @param array $params
391 * @return \CRM_Contact_DAO_SavedSearch
393 public static function create(&$params) {
394 $savedSearch = new CRM_Contact_DAO_SavedSearch();
395 if (isset($params['formValues']) &&
396 !empty($params['formValues'])
398 $savedSearch->form_values
= serialize($params['formValues']);
401 $savedSearch->form_values
= NULL;
404 $savedSearch->is_active
= CRM_Utils_Array
::value('is_active', $params, 1);
405 $savedSearch->mapping_id
= CRM_Utils_Array
::value('mapping_id', $params, 'null');
406 $savedSearch->custom_search_id
= CRM_Utils_Array
::value('custom_search_id', $params, 'null');
407 $savedSearch->id
= CRM_Utils_Array
::value('id', $params, NULL);
409 $savedSearch->save();
417 * @param string $fieldName
418 * @param array $fieldDef
419 * @param int $counter
421 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
422 if ($fieldName == 'form_values') {
423 // A dummy value for form_values.
424 $this->{$fieldName} = serialize(
425 ['sort_name' => "SortName{$counter}"]);
428 parent
::assignTestValues($fieldName, $fieldDef, $counter);
433 * Store relative dates in separate array format
435 * @param array $queryParams
436 * @param array $formValues
438 public static function saveRelativeDates(&$queryParams, $formValues) {
439 $relativeDates = ['relative_dates' => []];
440 $specialDateFields = ['event_relative', 'case_from_relative', 'case_to_relative', 'participant_relative'];
441 foreach ($formValues as $id => $value) {
442 if ((preg_match('/(_date|custom_[0-9]+)_relative$/', $id) ||
in_array($id, $specialDateFields)) && !empty($value)) {
443 $entityName = strstr($id, '_date', TRUE);
444 if (empty($entityName)) {
445 $entityName = strstr($id, '_relative', TRUE);
447 $relativeDates['relative_dates'][$entityName] = $value;
450 // merge with original queryParams if relative date value(s) found
451 if (count($relativeDates['relative_dates'])) {
452 $queryParams = array_merge($queryParams, $relativeDates);
457 * Store search variables in $queryParams which were skipped while processing query params,
458 * precisely at CRM_Contact_BAO_Query::fixWhereValues(...). But these variable are required in
459 * building smart group criteria otherwise it will cause issues like CRM-18585,CRM-19571
461 * @param array $queryParams
462 * @param array $formValues
464 public static function saveSkippedElement(&$queryParams, $formValues) {
465 // these are elements which are skipped in a smart group criteria
469 'display_relationship_type',
472 foreach ($specialElements as $element) {
473 if (!empty($formValues[$element])) {
474 $queryParams[] = [$element, '=', $formValues[$element], 0, 0];
480 * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...))
481 * into desired formValues
483 * @param array $formValues
484 * @param string $fieldName
486 * @param array|string|int $value
488 public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) {
489 // check if its a custom date field, if yes then 'searchDate' format the value
490 $isCustomDateField = CRM_Contact_BAO_Query
::isCustomDateField($fieldName);
492 // select date range as default
493 if ($isCustomDateField) {
494 if (array_key_exists('relative_dates', $formValues) && array_key_exists($fieldName, $formValues['relative_dates'])) {
495 $formValues[$fieldName . '_relative'] = $formValues['relative_dates'][$fieldName];
498 $formValues[$fieldName . '_relative'] = 0;
503 if ($isCustomDateField) {
504 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date
::setDateDefaults($value[0], 'searchDate');
505 list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date
::setDateDefaults($value[1], 'searchDate');
508 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value;
513 if ($isCustomDateField) {
514 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date
::setDateDefaults($value, 'searchDate');
517 $formValues[$fieldName . '_from'] = $value;
522 if ($isCustomDateField) {
523 list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date
::setDateDefaults($value, 'searchDate');
526 $formValues[$fieldName . '_to'] = $value;