CRM-19434 - fix notice errors for child groups
[civicrm-core.git] / CRM / Contact / BAO / SavedSearch.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33
34/**
c037736a 35 * Business object for Saved searches.
6a488035
TO
36 */
37class CRM_Contact_BAO_SavedSearch extends CRM_Contact_DAO_SavedSearch {
38
39 /**
fe482240 40 * Class constructor.
6a488035 41 */
00be9182 42 public function __construct() {
6a488035
TO
43 parent::__construct();
44 }
45
46 /**
100fef9d 47 * Query the db for all saved searches.
6a488035 48 *
a6c01b45
CW
49 * @return array
50 * contains the search name as value and and id as key
6a488035 51 */
00be9182 52 public function getAll() {
6a488035
TO
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 /**
fe482240
EM
64 * Retrieve DB object based on input parameters.
65 *
66 * It also stores all the retrieved values in the default array.
6a488035 67 *
77c5b619
TO
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.
6a488035 72 *
c490a46a 73 * @return CRM_Contact_BAO_SavedSearch
6a488035 74 */
00be9182 75 public static function retrieve(&$params, &$defaults) {
6a488035
TO
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 /**
54957108 86 * Given an id, extract the formValues of the saved search.
6a488035 87 *
77c5b619
TO
88 * @param int $id
89 * The id of the saved search.
6a488035 90 *
a6c01b45 91 * @return array
9406ae0b 92 * the values of the posted saved search used as default values in various Search Form
6a488035 93 */
e5ad0335 94 public static function getFormValues($id) {
6a488035
TO
95 $fv = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
96 $result = NULL;
97 if ($fv) {
98 // make sure u unserialize - since it's stored in serialized form
99 $result = unserialize($fv);
100 }
101
709355aa 102 //CRM-19250: fetch the default date format to format mysql value as per CRM_Core_Error::addDate()
103 $dateFormat = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate', 'searchDate', 'date_format', 'name');
104 $dateFormat = empty($dateFormat) ? CRM_Core_Config::singleton()->dateInputFormat : $dateFormat;
105 $dateFormat = CRM_Utils_Array::value($dateFormat, CRM_Core_SelectValues::datePluginToPHPFormats());
106
06d67d53 107 $specialFields = array('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)) {
113 $value = CRM_Utils_Array::value(key($value), $value);
114 }
709355aa 115 if (strpos($id, '_date_low') !== FALSE || strpos($id, '_date_high') !== FALSE) {
5aa7bc38 116 $entityName = strstr($id, '_date', TRUE);
9451fffa 117 if (!empty($result['relative_dates']) && array_key_exists($entityName, $result['relative_dates'])) {
118 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
119 }
120 else {
121 $result[$id] = date($dateFormat, strtotime($value));
122 $result["{$entityName}_date_relative"] = 0;
123 }
709355aa 124 }
125 else {
126 $result[$id] = $value;
127 }
06d67d53 128 unset($result[$element]);
129 continue;
130 }
131 if (!empty($value) && is_array($value)) {
132 if (in_array($element, $specialFields)) {
e5ad0335
E
133 // Remove the element to minimise support for legacy formats. It is stored in $value
134 // so will be re-set with the right name.
135 unset($result[$element]);
06d67d53 136 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
137 $element = str_replace('member_status_id', 'membership_status_id', $element);
138 CRM_Contact_BAO_Query::legacyConvertFormValues($element, $value);
139 $result[$element] = $value;
140 }
141 // As per the OK (Operator as Key) value format, value array may contain key
142 // as an operator so to ensure the default is always set actual value
143 elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
144 $result[$element] = CRM_Utils_Array::value(key($value), $value);
145 if (is_string($result[$element])) {
146 $result[$element] = str_replace("%", '', $result[$element]);
6a488035 147 }
6a488035 148 }
06d67d53 149 }
150 if (substr($element, 0, 7) == 'custom_' &&
151 (substr($element, -5, 5) == '_from' || substr($element, -3, 3) == '_to')
152 ) {
153 // Ensure the _relative field is set if from or to are set to ensure custom date
154 // fields with 'from' or 'to' values are displayed when the are set in the smart group
155 // being loaded. (CRM-17116)
156 if (!isset($result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'])) {
157 $result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'] = 0;
158 }
159 }
160 // check to see if we need to convert the old privacy array
161 // CRM-9180
162 if (!empty($result['privacy'])) {
163 if (is_array($result['privacy'])) {
164 $result['privacy_operator'] = 'AND';
165 $result['privacy_toggle'] = 1;
166 if (isset($result['privacy']['do_not_toggle'])) {
167 if ($result['privacy']['do_not_toggle']) {
168 $result['privacy_toggle'] = 2;
169 }
170 unset($result['privacy']['do_not_toggle']);
171 }
6a488035 172
06d67d53 173 $result['privacy_options'] = array();
d0d565e0 174 foreach ($result['privacy'] as $name => $val) {
175 if ($val) {
06d67d53 176 $result['privacy_options'][] = $name;
177 }
6a488035
TO
178 }
179 }
06d67d53 180 unset($result['privacy']);
6a488035 181 }
6a488035
TO
182 }
183
184 return $result;
185 }
186
86538308 187 /**
54957108 188 * Get search parameters.
189 *
100fef9d 190 * @param int $id
86538308
EM
191 *
192 * @return array
193 */
00be9182 194 public static function getSearchParams($id) {
6a488035 195 $fv = self::getFormValues($id);
959528d2 196 //check if the saved search has mapping id
6a488035
TO
197 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
198 return CRM_Core_BAO_Mapping::formattedFields($fv);
199 }
a7488080 200 elseif (!empty($fv['customSearchID'])) {
6a488035
TO
201 return $fv;
202 }
203 else {
204 return CRM_Contact_BAO_Query::convertFormValues($fv);
205 }
206 }
207
208 /**
fe482240 209 * Get the where clause for a saved search.
6a488035 210 *
77c5b619
TO
211 * @param int $id
212 * Saved search id.
213 * @param array $tables
214 * (reference ) add the tables that are needed for the select clause.
215 * @param array $whereTables
216 * (reference ) add the tables that are needed for the where clause.
6a488035 217 *
a6c01b45
CW
218 * @return string
219 * the where clause for this saved search
6a488035 220 */
00be9182 221 public static function whereClause($id, &$tables, &$whereTables) {
6a488035
TO
222 $params = self::getSearchParams($id);
223 if ($params) {
a7488080 224 if (!empty($params['customSearchID'])) {
6a488035 225 // this has not yet been implemented
0db6c3e1
TO
226 }
227 else {
353ffa53
TO
228 return CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
229 }
6a488035
TO
230 }
231 return NULL;
232 }
233
86538308 234 /**
54957108 235 * Contact IDS Sql (whatever that means!).
236 *
100fef9d 237 * @param int $id
86538308
EM
238 *
239 * @return string
240 */
00be9182 241 public static function contactIDsSQL($id) {
6a488035 242 $params = self::getSearchParams($id);
8cc574cf 243 if ($params && !empty($params['customSearchID'])) {
6a488035
TO
244 return CRM_Contact_BAO_SearchCustom::contactIDSQL(NULL, $id);
245 }
246 else {
247 $tables = $whereTables = array('civicrm_contact' => 1);
248 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
249 if (!$where) {
250 $where = '( 1 )';
251 }
252 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
253 return "
254SELECT contact_a.id
255$from
256WHERE $where";
257 }
258 }
259
86538308 260 /**
54957108 261 * Get from where email (whatever that means!).
262 *
100fef9d 263 * @param int $id
86538308
EM
264 *
265 * @return array
266 */
00be9182 267 public static function fromWhereEmail($id) {
6a488035
TO
268 $params = self::getSearchParams($id);
269
270 if ($params) {
a7488080 271 if (!empty($params['customSearchID'])) {
6a488035
TO
272 return CRM_Contact_BAO_SearchCustom::fromWhereEmail(NULL, $id);
273 }
274 else {
275 $tables = $whereTables = array('civicrm_contact' => 1, 'civicrm_email' => 1);
353ffa53
TO
276 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
277 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
6a488035
TO
278 return array($from, $where);
279 }
280 }
281 else {
282 // fix for CRM-7240
283 $from = "
284FROM civicrm_contact contact_a
285LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
286";
287 $where = " ( 1 ) ";
288 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
289 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
290 return array($from, $where);
291 }
292 }
293
294 /**
54957108 295 * Given a saved search compute the clause and the tables and store it for future use.
6a488035 296 */
00be9182 297 public function buildClause() {
6a488035
TO
298 $fv = unserialize($this->form_values);
299
300 if ($this->mapping_id) {
301 $params = CRM_Core_BAO_Mapping::formattedFields($fv);
302 }
303 else {
304 $params = CRM_Contact_BAO_Query::convertFormValues($fv);
305 }
306
307 if (!empty($params)) {
308 $tables = $whereTables = array();
309 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
310 if (!empty($tables)) {
311 $this->select_tables = serialize($tables);
312 }
313 if (!empty($whereTables)) {
314 $this->where_tables = serialize($whereTables);
315 }
316 }
6a488035
TO
317 }
318
54957108 319 /**
320 * Save the search.
321 *
322 * @param bool $hook
323 */
8ab09481 324 public function save($hook = TRUE) {
6a488035
TO
325 // first build the computed fields
326 $this->buildClause();
327
8ab09481 328 parent::save($hook);
6a488035
TO
329 }
330
331 /**
e8e8f3ad 332 * Given an id, get the name of the saved search.
6a488035 333 *
77c5b619
TO
334 * @param int $id
335 * The id of the saved search.
6a488035 336 *
77b97be7
EM
337 * @param string $value
338 *
a6c01b45
CW
339 * @return string
340 * the name of the saved search
6a488035 341 */
00be9182 342 public static function getName($id, $value = 'name') {
6a488035
TO
343 $group = new CRM_Contact_DAO_Group();
344 $group->saved_search_id = $id;
345 if ($group->find(TRUE)) {
346 return $group->$value;
347 }
348 return NULL;
349 }
350
351 /**
e8e8f3ad 352 * Create a smart group from normalised values.
54957108 353 *
354 * @param array $params
355 *
356 * @return \CRM_Contact_DAO_SavedSearch
6a488035 357 */
00be9182 358 public static function create(&$params) {
6a488035
TO
359 $savedSearch = new CRM_Contact_DAO_SavedSearch();
360 if (isset($params['formValues']) &&
361 !empty($params['formValues'])
362 ) {
363 $savedSearch->form_values = serialize($params['formValues']);
364 }
365 else {
1c18b4d5 366 $savedSearch->form_values = NULL;
6a488035
TO
367 }
368
369 $savedSearch->is_active = CRM_Utils_Array::value('is_active', $params, 1);
370 $savedSearch->mapping_id = CRM_Utils_Array::value('mapping_id', $params, 'null');
371 $savedSearch->custom_search_id = CRM_Utils_Array::value('custom_search_id', $params, 'null');
372 $savedSearch->id = CRM_Utils_Array::value('id', $params, NULL);
373
374 $savedSearch->save();
375
376 return $savedSearch;
377 }
96025800 378
54957108 379 /**
380 * Assign test value.
381 *
382 * @param string $fieldName
383 * @param array $fieldDef
384 * @param int $counter
385 */
4f0a0e58
JV
386 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
387 if ($fieldName == 'form_values') {
388 // A dummy value for form_values.
389 $this->{$fieldName} = serialize(
390 array('sort_name' => "SortName{$counter}"));
391 }
392 else {
393 parent::assignTestValues($fieldName, $fieldDef, $counter);
394 }
395 }
396
9451fffa 397 /**
398 * Store relative dates in separate array format
399 *
400 * @param array $queryParams
401 * @param array $formValues
402 */
403 public static function saveRelativeDates(&$queryParams, $formValues) {
404 $relativeDates = array('relative_dates' => array());
405 foreach ($formValues as $id => $value) {
406 if (preg_match('/_date_relative$/', $id) && !empty($value)) {
407 $entityName = strstr($id, '_date', TRUE);
408 $relativeDates['relative_dates'][$entityName] = $value;
409 }
410 }
411 // merge with original queryParams if relative date value(s) found
412 if (count($relativeDates['relative_dates'])) {
413 $queryParams = array_merge($queryParams, $relativeDates);
414 }
415 }
416
6a488035 417}