Merge pull request #6617 from colemanw/CRM-17102
[civicrm-core.git] / CRM / Contact / Form / Search / Builder.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34 /**
35 * This class is for search builder processing.
36 */
37 class CRM_Contact_Form_Search_Builder extends CRM_Contact_Form_Search {
38
39 /**
40 * Number of columns in where.
41 *
42 * @var int
43 */
44 public $_columnCount;
45
46 /**
47 * Number of blocks to be shown.
48 *
49 * @var int
50 */
51 public $_blockCount;
52
53 /**
54 * Build the form object.
55 */
56 public function preProcess() {
57 $this->set('searchFormName', 'Builder');
58
59 $this->set('context', 'builder');
60 parent::preProcess();
61
62 // Get the block count
63 $this->_blockCount = $this->get('blockCount');
64 // Initialize new form
65 if (!$this->_blockCount) {
66 $this->_blockCount = 4;
67 $this->set('newBlock', 1);
68 }
69
70 //get the column count
71 $this->_columnCount = $this->get('columnCount');
72
73 for ($i = 1; $i < $this->_blockCount; $i++) {
74 if (empty($this->_columnCount[$i])) {
75 $this->_columnCount[$i] = 5;
76 }
77 }
78
79 $this->_loadedMappingId = $this->get('savedMapping');
80
81 if ($this->get('showSearchForm')) {
82 $this->assign('showSearchForm', TRUE);
83 }
84 else {
85 $this->assign('showSearchForm', FALSE);
86 }
87 }
88
89 public function buildQuickForm() {
90 $fields = self::fields();
91 // Get fields of type date
92 // FIXME: This is a hack until our fields contain this meta-data
93 $dateFields = array();
94 foreach ($fields as $name => $field) {
95 if (strpos($name, '_date') || CRM_Utils_Array::value('data_type', $field) == 'Date') {
96 $dateFields[] = $name;
97 }
98 }
99 // Add javascript
100 CRM_Core_Resources::singleton()
101 ->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Search/Builder.js', 1, 'html-header')
102 ->addSetting(array(
103 'searchBuilder' => array(
104 // Index of newly added/expanded block (1-based index)
105 'newBlock' => $this->get('newBlock'),
106 'dateFields' => $dateFields,
107 'fieldOptions' => self::fieldOptions(),
108 ),
109 ));
110 //get the saved search mapping id
111 $mappingId = NULL;
112 if ($this->_ssID) {
113 $mappingId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $this->_ssID, 'mapping_id');
114 }
115
116 CRM_Core_BAO_Mapping::buildMappingForm($this, 'Search Builder', $mappingId, $this->_columnCount, $this->_blockCount);
117
118 parent::buildQuickForm();
119 }
120
121 /**
122 * Add local and global form rules.
123 */
124 public function addRules() {
125 $this->addFormRule(array('CRM_Contact_Form_Search_Builder', 'formRule'), $this);
126 }
127
128 /**
129 * Global validation rules for the form.
130 *
131 * @param array $values
132 * @param array $files
133 * @param CRM_Core_Form $self
134 *
135 * @return array
136 * list of errors to be posted back to the form
137 */
138 public static function formRule($values, $files, $self) {
139 if (!empty($values['addMore']) || !empty($values['addBlock'])) {
140 return TRUE;
141 }
142 $fields = self::fields();
143 $fld = CRM_Core_BAO_Mapping::formattedFields($values, TRUE);
144
145 $errorMsg = array();
146 foreach ($fld as $k => $v) {
147 if (!$v[1]) {
148 $errorMsg["operator[$v[3]][$v[4]]"] = ts("Please enter the operator.");
149 }
150 else {
151 // CRM-10338
152 $v[2] = self::checkArrayKeyEmpty($v[2]);
153
154 if (in_array($v[1], array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) &&
155 !empty($v[2])
156 ) {
157 $errorMsg["value[$v[3]][$v[4]]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1]));
158 }
159 elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
160 if (isset($v[2])) {
161 $v2 = array($v[2]);
162 if (!isset($v[2])) {
163 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
164 }
165
166 $error = CRM_Utils_Type::validate($v2[0], 'Integer', FALSE);
167 if ($error != $v2[0]) {
168 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
169 }
170 }
171 else {
172 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
173 }
174 }
175 else {
176 if (substr($v[0], 0, 7) == 'custom_') {
177 // Get rid of appended location type id
178 list($fieldKey) = explode('-', $v[0]);
179 $type = $fields[$fieldKey]['data_type'];
180
181 // hack to handle custom data of type state and country
182 if (in_array($type, array(
183 'Country',
184 'StateProvince',
185 ))) {
186 $type = "Integer";
187 }
188 }
189 else {
190 $fldName = $v[0];
191 // FIXME: no idea at this point what to do with this,
192 // FIXME: but definitely needs fixing.
193 if (substr($v[0], 0, 13) == 'contribution_') {
194 $fldName = substr($v[0], 13);
195 }
196
197 $fldValue = CRM_Utils_Array::value($fldName, $fields);
198 $fldType = CRM_Utils_Array::value('type', $fldValue);
199 $type = CRM_Utils_Type::typeToString($fldType);
200
201 if (strstr($v[1], 'IN')) {
202 if (empty($v[2])) {
203 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
204 }
205 }
206 // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
207 elseif (!in_array($v[1],
208 array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))
209 ) {
210 if ((($type == 'Int' || $type == 'Boolean') && !is_array($v[2]) && !trim($v[2])) && $v[2] != '0') {
211 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
212 }
213 elseif ($type == 'Date' && !trim($v[2])) {
214 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
215 }
216 }
217 }
218
219 if ($type && empty($errorMsg)) {
220 // check for valid format while using IN Operator
221 if (strstr($v[1], 'IN')) {
222 if (!is_array($v[2])) {
223 $inVal = trim($v[2]);
224 //checking for format to avoid db errors
225 if ($type == 'Int') {
226 if (!preg_match('/^[A-Za-z0-9\,]+$/', $inVal)) {
227 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
228 }
229 }
230 else {
231 if (!preg_match('/^[A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ()\,\s]+$/', $inVal)) {
232 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
233 }
234 }
235 }
236
237 // Validate each value in parenthesis to avoid db errors
238 if (empty($errorMsg)) {
239 $parenValues = array();
240 $parenValues = is_array($v[2]) ? (array_key_exists($v[1], $v[2])) ? $v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)"));
241 foreach ($parenValues as $val) {
242 if ($type == 'Date' || $type == 'Timestamp') {
243 $val = CRM_Utils_Date::processDate($val);
244 if ($type == 'Date') {
245 $val = substr($val, 0, 8);
246 }
247 }
248 else {
249 $val = trim($val);
250 }
251 if (!$val && $val != '0') {
252 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter the values correctly.");
253 }
254 if (empty($errorMsg)) {
255 $error = CRM_Utils_Type::validate($val, $type, FALSE);
256 if ($error != $val) {
257 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
258 }
259 }
260 }
261 }
262 }
263 elseif (trim($v[2])) {
264 //else check value for rest of the Operators
265 $error = CRM_Utils_Type::validate($v[2], $type, FALSE);
266 if ($error != $v[2]) {
267 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
268 }
269 }
270 }
271 }
272 }
273 }
274
275 if (!empty($errorMsg)) {
276 $self->set('showSearchForm', TRUE);
277 $self->assign('rows', NULL);
278 return $errorMsg;
279 }
280
281 return TRUE;
282 }
283
284 public function normalizeFormValues() {
285 }
286
287 /**
288 * @param $formValues
289 *
290 * @return array
291 */
292 public function convertFormValues(&$formValues) {
293 return CRM_Core_BAO_Mapping::formattedFields($formValues);
294 }
295
296 /**
297 * @return array
298 */
299 public function &returnProperties() {
300 return CRM_Core_BAO_Mapping::returnProperties($this->_formValues);
301 }
302
303 /**
304 * Process the uploaded file.
305 */
306 public function postProcess() {
307 $this->set('isAdvanced', '2');
308 $this->set('isSearchBuilder', '1');
309 $this->set('showSearchForm', FALSE);
310
311 $params = $this->controller->exportValues($this->_name);
312 if (!empty($params)) {
313 // Add another block
314 if (!empty($params['addBlock'])) {
315 $this->set('newBlock', $this->_blockCount);
316 $this->_blockCount += 3;
317 $this->set('blockCount', $this->_blockCount);
318 $this->set('showSearchForm', TRUE);
319 return;
320 }
321 // Add another field
322 $addMore = CRM_Utils_Array::value('addMore', $params);
323 for ($x = 1; $x <= $this->_blockCount; $x++) {
324 if (!empty($addMore[$x])) {
325 $this->set('newBlock', $x);
326 $this->_columnCount[$x] = $this->_columnCount[$x] + 5;
327 $this->set('columnCount', $this->_columnCount);
328 $this->set('showSearchForm', TRUE);
329 return;
330 }
331 }
332 $this->set('newBlock', NULL);
333 $checkEmpty = NULL;
334 foreach ($params['mapper'] as $key => $value) {
335 foreach ($value as $k => $v) {
336 if ($v[0]) {
337 $checkEmpty++;
338 }
339 }
340 }
341
342 if (!$checkEmpty) {
343 $this->set('newBlock', 1);
344 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/search/builder', '_qf_Builder_display=true'));
345 }
346 }
347
348 // get user submitted values
349 // get it from controller only if form has been submitted, else preProcess has set this
350 if (!empty($_POST)) {
351 $this->_formValues = $this->controller->exportValues($this->_name);
352
353 // set the group if group is submitted
354 if (!empty($this->_formValues['uf_group_id'])) {
355 $this->set('id', $this->_formValues['uf_group_id']);
356 }
357 else {
358 $this->set('id', '');
359 }
360 }
361
362 // we dont want to store the sortByCharacter in the formValue, it is more like
363 // a filter on the result set
364 // this filter is reset if we click on the search button
365 if ($this->_sortByCharacter !== NULL && empty($_POST)) {
366 if (strtolower($this->_sortByCharacter) == 'all') {
367 $this->_formValues['sortByCharacter'] = NULL;
368 }
369 else {
370 $this->_formValues['sortByCharacter'] = $this->_sortByCharacter;
371 }
372 }
373 else {
374 $this->_sortByCharacter = NULL;
375 }
376
377 $this->_params = $this->convertFormValues($this->_formValues);
378 $this->_returnProperties = &$this->returnProperties();
379
380 // CRM-10338 check if value is empty array
381 foreach ($this->_params as $k => $v) {
382 $this->_params[$k][2] = self::checkArrayKeyEmpty($v[2]);
383 }
384
385 parent::postProcess();
386 }
387
388 /**
389 * @return array
390 */
391 public static function fields() {
392 $fields = array_merge(
393 CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE),
394 CRM_Core_Component::getQueryFields(),
395 CRM_Contact_BAO_Query_Hook::singleton()->getFields(),
396 CRM_Activity_BAO_Activity::exportableFields()
397 );
398 return $fields;
399 }
400
401 /**
402 * CRM-9434 Hackish function to fetch fields with options.
403 * FIXME: When our core fields contain reliable metadata this will be much simpler.
404 * @return array
405 * (string => string) key: field_name value: api entity name
406 * Note: options are fetched via ajax using the api "getoptions" method
407 */
408 public static function fieldOptions() {
409 // Hack to add options not retrieved by getfields
410 // This list could go on and on, but it would be better to fix getfields
411 $options = array(
412 'group' => 'group_contact',
413 'tag' => 'entity_tag',
414 'on_hold' => 'yesno',
415 'is_bulkmail' => 'yesno',
416 'payment_instrument' => 'contribution',
417 'membership_status' => 'membership',
418 'membership_type' => 'membership',
419 'member_campaign_id' => 'membership',
420 'member_is_test' => 'yesno',
421 'member_is_pay_later' => 'yesno',
422 'is_override' => 'yesno',
423 );
424 $entities = array(
425 'contact',
426 'address',
427 'activity',
428 'participant',
429 'pledge',
430 'member',
431 'contribution',
432 'case',
433 'grant',
434 );
435 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchBuilderOptions($entities, $options);
436 foreach ($entities as $entity) {
437 $fields = civicrm_api3($entity, 'getfields');
438 foreach ($fields['values'] as $field => $info) {
439 if (!empty($info['options']) || !empty($info['pseudoconstant']) || !empty($info['option_group_id'])) {
440 $options[$field] = $entity;
441 // Hack for when search field doesn't match db field - e.g. "country" instead of "country_id"
442 if (substr($field, -3) == '_id') {
443 $options[substr($field, 0, -3)] = $entity;
444 }
445 }
446 elseif (!empty($info['data_type']) && in_array($info['data_type'], array('StateProvince', 'Country'))) {
447 $options[$field] = $entity;
448 }
449 elseif (in_array(substr($field, 0, 3), array(
450 'is_',
451 'do_',
452 )) || CRM_Utils_Array::value('data_type', $info) == 'Boolean'
453 ) {
454 $options[$field] = 'yesno';
455 if ($entity != 'contact') {
456 $options[$entity . '_' . $field] = 'yesno';
457 }
458 }
459 elseif (strpos($field, '_is_')) {
460 $options[$field] = 'yesno';
461 }
462 }
463 }
464 return $options;
465 }
466
467 /**
468 * CRM-10338
469 * tags and groups use array keys for selection list.
470 * if using IS NULL/NOT NULL, an array with no array key is created
471 * convert that to simple NULL so processing can proceed
472 */
473 public static function checkArrayKeyEmpty($val) {
474 if (is_array($val)) {
475 $v2empty = TRUE;
476 foreach ($val as $vk => $vv) {
477 if (!empty($vk)) {
478 $v2empty = FALSE;
479 }
480 }
481 if ($v2empty) {
482 $val = NULL;
483 }
484 }
485 return $val;
486 }
487
488 }