Merge pull request #9296 from michaelmcandrew/grant-api-contact-required
[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
06d67d53 102 $specialFields = array('contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id');
103 foreach ($result as $element => $value) {
104 if (CRM_Contact_BAO_Query::isAlreadyProcessedForQueryFormat($value)) {
105 $id = CRM_Utils_Array::value(0, $value);
106 $value = CRM_Utils_Array::value(2, $value);
107 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
8e2e771b 108 $op = key($value);
109 $value = CRM_Utils_Array::value($op, $value);
110 if (in_array($op, array('BETWEEN', '>=', '<='))) {
111 self::decodeRelativeFields($result, $id, $op, $value);
112 unset($result[$element]);
113 continue;
114 }
06d67d53 115 }
709355aa 116 if (strpos($id, '_date_low') !== FALSE || strpos($id, '_date_high') !== FALSE) {
5aa7bc38 117 $entityName = strstr($id, '_date', TRUE);
9451fffa 118 if (!empty($result['relative_dates']) && array_key_exists($entityName, $result['relative_dates'])) {
119 $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
120 }
121 else {
aeadc6bf 122 $result[$id] = $value;
9451fffa 123 $result["{$entityName}_date_relative"] = 0;
124 }
709355aa 125 }
126 else {
127 $result[$id] = $value;
128 }
06d67d53 129 unset($result[$element]);
130 continue;
131 }
132 if (!empty($value) && is_array($value)) {
133 if (in_array($element, $specialFields)) {
e5ad0335
E
134 // Remove the element to minimise support for legacy formats. It is stored in $value
135 // so will be re-set with the right name.
136 unset($result[$element]);
06d67d53 137 $element = str_replace('member_membership_type_id', 'membership_type_id', $element);
138 $element = str_replace('member_status_id', 'membership_status_id', $element);
139 CRM_Contact_BAO_Query::legacyConvertFormValues($element, $value);
140 $result[$element] = $value;
141 }
142 // As per the OK (Operator as Key) value format, value array may contain key
143 // as an operator so to ensure the default is always set actual value
144 elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
145 $result[$element] = CRM_Utils_Array::value(key($value), $value);
146 if (is_string($result[$element])) {
147 $result[$element] = str_replace("%", '', $result[$element]);
6a488035 148 }
6a488035 149 }
06d67d53 150 }
151 if (substr($element, 0, 7) == 'custom_' &&
152 (substr($element, -5, 5) == '_from' || substr($element, -3, 3) == '_to')
153 ) {
154 // Ensure the _relative field is set if from or to are set to ensure custom date
155 // fields with 'from' or 'to' values are displayed when the are set in the smart group
156 // being loaded. (CRM-17116)
157 if (!isset($result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'])) {
158 $result[CRM_Contact_BAO_Query::getCustomFieldName($element) . '_relative'] = 0;
159 }
160 }
161 // check to see if we need to convert the old privacy array
162 // CRM-9180
163 if (!empty($result['privacy'])) {
164 if (is_array($result['privacy'])) {
165 $result['privacy_operator'] = 'AND';
166 $result['privacy_toggle'] = 1;
167 if (isset($result['privacy']['do_not_toggle'])) {
168 if ($result['privacy']['do_not_toggle']) {
169 $result['privacy_toggle'] = 2;
170 }
171 unset($result['privacy']['do_not_toggle']);
172 }
6a488035 173
06d67d53 174 $result['privacy_options'] = array();
d0d565e0 175 foreach ($result['privacy'] as $name => $val) {
176 if ($val) {
06d67d53 177 $result['privacy_options'][] = $name;
178 }
6a488035
TO
179 }
180 }
06d67d53 181 unset($result['privacy']);
6a488035 182 }
6a488035
TO
183 }
184
185 return $result;
186 }
187
86538308 188 /**
54957108 189 * Get search parameters.
190 *
100fef9d 191 * @param int $id
86538308
EM
192 *
193 * @return array
194 */
00be9182 195 public static function getSearchParams($id) {
6a488035 196 $fv = self::getFormValues($id);
959528d2 197 //check if the saved search has mapping id
6a488035
TO
198 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'mapping_id')) {
199 return CRM_Core_BAO_Mapping::formattedFields($fv);
200 }
a7488080 201 elseif (!empty($fv['customSearchID'])) {
6a488035
TO
202 return $fv;
203 }
204 else {
205 return CRM_Contact_BAO_Query::convertFormValues($fv);
206 }
207 }
208
209 /**
fe482240 210 * Get the where clause for a saved search.
6a488035 211 *
77c5b619
TO
212 * @param int $id
213 * Saved search id.
214 * @param array $tables
215 * (reference ) add the tables that are needed for the select clause.
216 * @param array $whereTables
217 * (reference ) add the tables that are needed for the where clause.
6a488035 218 *
a6c01b45
CW
219 * @return string
220 * the where clause for this saved search
6a488035 221 */
00be9182 222 public static function whereClause($id, &$tables, &$whereTables) {
6a488035
TO
223 $params = self::getSearchParams($id);
224 if ($params) {
a7488080 225 if (!empty($params['customSearchID'])) {
6a488035 226 // this has not yet been implemented
0db6c3e1
TO
227 }
228 else {
353ffa53
TO
229 return CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
230 }
6a488035
TO
231 }
232 return NULL;
233 }
234
86538308 235 /**
54957108 236 * Contact IDS Sql (whatever that means!).
237 *
100fef9d 238 * @param int $id
86538308
EM
239 *
240 * @return string
241 */
00be9182 242 public static function contactIDsSQL($id) {
6a488035 243 $params = self::getSearchParams($id);
8cc574cf 244 if ($params && !empty($params['customSearchID'])) {
6a488035
TO
245 return CRM_Contact_BAO_SearchCustom::contactIDSQL(NULL, $id);
246 }
247 else {
248 $tables = $whereTables = array('civicrm_contact' => 1);
249 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
250 if (!$where) {
251 $where = '( 1 )';
252 }
253 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
254 return "
255SELECT contact_a.id
256$from
257WHERE $where";
258 }
259 }
260
86538308 261 /**
54957108 262 * Get from where email (whatever that means!).
263 *
100fef9d 264 * @param int $id
86538308
EM
265 *
266 * @return array
267 */
00be9182 268 public static function fromWhereEmail($id) {
6a488035
TO
269 $params = self::getSearchParams($id);
270
271 if ($params) {
a7488080 272 if (!empty($params['customSearchID'])) {
6a488035
TO
273 return CRM_Contact_BAO_SearchCustom::fromWhereEmail(NULL, $id);
274 }
275 else {
276 $tables = $whereTables = array('civicrm_contact' => 1, 'civicrm_email' => 1);
353ffa53
TO
277 $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
278 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
6a488035
TO
279 return array($from, $where);
280 }
281 }
282 else {
283 // fix for CRM-7240
284 $from = "
285FROM civicrm_contact contact_a
286LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)
287";
288 $where = " ( 1 ) ";
289 $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
290 $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
291 return array($from, $where);
292 }
293 }
294
295 /**
54957108 296 * Given a saved search compute the clause and the tables and store it for future use.
6a488035 297 */
00be9182 298 public function buildClause() {
6a488035
TO
299 $fv = unserialize($this->form_values);
300
301 if ($this->mapping_id) {
302 $params = CRM_Core_BAO_Mapping::formattedFields($fv);
303 }
304 else {
305 $params = CRM_Contact_BAO_Query::convertFormValues($fv);
306 }
307
308 if (!empty($params)) {
309 $tables = $whereTables = array();
310 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
311 if (!empty($tables)) {
312 $this->select_tables = serialize($tables);
313 }
314 if (!empty($whereTables)) {
315 $this->where_tables = serialize($whereTables);
316 }
317 }
6a488035
TO
318 }
319
54957108 320 /**
321 * Save the search.
322 *
323 * @param bool $hook
324 */
8ab09481 325 public function save($hook = TRUE) {
6a488035
TO
326 // first build the computed fields
327 $this->buildClause();
328
8ab09481 329 parent::save($hook);
6a488035
TO
330 }
331
332 /**
e8e8f3ad 333 * Given an id, get the name of the saved search.
6a488035 334 *
77c5b619
TO
335 * @param int $id
336 * The id of the saved search.
6a488035 337 *
77b97be7
EM
338 * @param string $value
339 *
a6c01b45
CW
340 * @return string
341 * the name of the saved search
6a488035 342 */
00be9182 343 public static function getName($id, $value = 'name') {
6a488035
TO
344 $group = new CRM_Contact_DAO_Group();
345 $group->saved_search_id = $id;
346 if ($group->find(TRUE)) {
347 return $group->$value;
348 }
349 return NULL;
350 }
351
352 /**
e8e8f3ad 353 * Create a smart group from normalised values.
54957108 354 *
355 * @param array $params
356 *
357 * @return \CRM_Contact_DAO_SavedSearch
6a488035 358 */
00be9182 359 public static function create(&$params) {
6a488035
TO
360 $savedSearch = new CRM_Contact_DAO_SavedSearch();
361 if (isset($params['formValues']) &&
362 !empty($params['formValues'])
363 ) {
364 $savedSearch->form_values = serialize($params['formValues']);
365 }
366 else {
1c18b4d5 367 $savedSearch->form_values = NULL;
6a488035
TO
368 }
369
370 $savedSearch->is_active = CRM_Utils_Array::value('is_active', $params, 1);
371 $savedSearch->mapping_id = CRM_Utils_Array::value('mapping_id', $params, 'null');
372 $savedSearch->custom_search_id = CRM_Utils_Array::value('custom_search_id', $params, 'null');
373 $savedSearch->id = CRM_Utils_Array::value('id', $params, NULL);
374
375 $savedSearch->save();
376
377 return $savedSearch;
378 }
96025800 379
54957108 380 /**
381 * Assign test value.
382 *
383 * @param string $fieldName
384 * @param array $fieldDef
385 * @param int $counter
386 */
4f0a0e58
JV
387 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
388 if ($fieldName == 'form_values') {
389 // A dummy value for form_values.
390 $this->{$fieldName} = serialize(
391 array('sort_name' => "SortName{$counter}"));
392 }
393 else {
394 parent::assignTestValues($fieldName, $fieldDef, $counter);
395 }
396 }
397
9451fffa 398 /**
399 * Store relative dates in separate array format
400 *
401 * @param array $queryParams
402 * @param array $formValues
403 */
404 public static function saveRelativeDates(&$queryParams, $formValues) {
405 $relativeDates = array('relative_dates' => array());
406 foreach ($formValues as $id => $value) {
407 if (preg_match('/_date_relative$/', $id) && !empty($value)) {
408 $entityName = strstr($id, '_date', TRUE);
409 $relativeDates['relative_dates'][$entityName] = $value;
410 }
411 }
412 // merge with original queryParams if relative date value(s) found
413 if (count($relativeDates['relative_dates'])) {
414 $queryParams = array_merge($queryParams, $relativeDates);
415 }
416 }
417
8e2e771b 418 /**
419 * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...))
420 * into desired formValues
421 *
422 * @param array $formValues
423 * @param string $fieldName
424 * @param string $op
425 * @param array|string|int $value
426 */
427 public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) {
d8766e36 428 // check if its a custom date field, if yes then ISO format the value
429 if (CRM_Contact_BAO_Query::isCustomDateField($fieldName)) {
430 $field = (array) CRM_Core_BAO_CustomField::getFieldObject(CRM_Core_BAO_CustomField::getKeyID($fieldName));
431 //CRM-18349, date value must be ISO formatted before being set as a default value for crmDatepicker custom field
432 $ISODateFormat = CRM_Utils_Array::value('time_format', $field) ? 'Y-m-d G:i:s' : 'Y-m-d';
433
434 if (is_array($value)) {
435 foreach ($value as $key => $v) {
436 $value[$key] = CRM_Utils_Date::processDate($v, NULL, FALSE, $ISODateFormat);
437 }
438 }
439 else {
440 $value = CRM_Utils_Date::processDate($value, NULL, FALSE, $ISODateFormat);
441 }
442 }
8e2e771b 443 switch ($op) {
444 case 'BETWEEN':
445 list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value;
446 break;
447
448 case '>=':
449 $formValues[$fieldName . '_from'] = $value;
450 break;
451
452 case '<=':
453 $formValues[$fieldName . '_to'] = $value;
454 break;
455 }
456 }
457
6a488035 458}