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