Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-09-05-17-42-45
[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 (($v[0] == 'group' || $v[0] == 'tag') && !empty($v[2])) {
160 $grpId = array_keys($v[2]);
161 if (!key($v[2])) {
162 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
163 }
164
165 if (count($grpId) > 1) {
166 if ($v[1] != 'IN' && $v[1] != 'NOT IN') {
167 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
168 }
169 foreach ($grpId as $val) {
170 $error = CRM_Utils_Type::validate($val, 'Integer', FALSE);
171 if ($error != $val) {
172 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
173 break;
174 }
175 }
176 }
177 else {
178 $error = CRM_Utils_Type::validate($grpId[0], 'Integer', FALSE);
179 if ($error != $grpId[0]) {
180 $errorMsg["value[$v[3]][$v[4]]"] = ts('Please enter valid %1 id.', array(1 => $v[0]));
181 }
182 }
183 }
184 elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
185 if (isset($v[2])) {
186 $v2 = array($v[2]);
187 if (!isset($v[2])) {
188 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
189 }
190
191 $error = CRM_Utils_Type::validate($v2[0], 'Integer', FALSE);
192 if ($error != $v2[0]) {
193 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
194 }
195 }
196 else {
197 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
198 }
199 }
200 else {
201 if (substr($v[0], 0, 7) == 'custom_') {
202 // Get rid of appended location type id
203 list($fieldKey) = explode('-', $v[0]);
204 $type = $fields[$fieldKey]['data_type'];
205
206 // hack to handle custom data of type state and country
207 if (in_array($type, array(
208 'Country',
209 'StateProvince',
210 ))) {
211 $type = "Integer";
212 }
213 }
214 else {
215 $fldName = $v[0];
216 // FIXME: no idea at this point what to do with this,
217 // FIXME: but definitely needs fixing.
218 if (substr($v[0], 0, 13) == 'contribution_') {
219 $fldName = substr($v[0], 13);
220 }
221
222 $fldValue = CRM_Utils_Array::value($fldName, $fields);
223 $fldType = CRM_Utils_Array::value('type', $fldValue);
224 $type = CRM_Utils_Type::typeToString($fldType);
225
226 if (strstr($v[1], 'IN')) {
227 if (empty($v[2])) {
228 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
229 }
230 }
231 // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
232 elseif (!in_array($v[1],
233 array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))
234 ) {
235 if ((($type == 'Int' || $type == 'Boolean') && !is_array($v[2]) && !trim($v[2])) && $v[2] != '0') {
236 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
237 }
238 elseif ($type == 'Date' && !trim($v[2])) {
239 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
240 }
241 }
242 }
243
244 if ($type && empty($errorMsg)) {
245 // check for valid format while using IN Operator
246 if (strstr($v[1], 'IN')) {
247 if (!is_array($v[2])) {
248 $inVal = trim($v[2]);
249 //checking for format to avoid db errors
250 if ($type == 'Int') {
251 if (!preg_match('/^[A-Za-z0-9\,]+$/', $inVal)) {
252 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
253 }
254 }
255 else {
256 if (!preg_match('/^[A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ()\,\s]+$/', $inVal)) {
257 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
258 }
259 }
260 }
261
262 // Validate each value in parenthesis to avoid db errors
263 if (empty($errorMsg)) {
264 $parenValues = array();
265 $parenValues = is_array($v[2]) ? (array_key_exists($v[1], $v[2])) ? $v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)"));
266 foreach ($parenValues as $val) {
267 if ($type == 'Date' || $type == 'Timestamp') {
268 $val = CRM_Utils_Date::processDate($val);
269 if ($type == 'Date') {
270 $val = substr($val, 0, 8);
271 }
272 }
273 else {
274 $val = trim($val);
275 }
276 if (!$val && $val != '0') {
277 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter the values correctly.");
278 }
279 if (empty($errorMsg)) {
280 $error = CRM_Utils_Type::validate($val, $type, FALSE);
281 if ($error != $val) {
282 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
283 }
284 }
285 }
286 }
287 }
288 elseif (trim($v[2])) {
289 //else check value for rest of the Operators
290 $error = CRM_Utils_Type::validate($v[2], $type, FALSE);
291 if ($error != $v[2]) {
292 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
293 }
294 }
295 }
296 }
297 }
298 }
299
300 if (!empty($errorMsg)) {
301 $self->set('showSearchForm', TRUE);
302 $self->assign('rows', NULL);
303 return $errorMsg;
304 }
305
306 return TRUE;
307 }
308
309 public function normalizeFormValues() {
310 }
311
312 /**
313 * @param $formValues
314 *
315 * @return array
316 */
317 public function convertFormValues(&$formValues) {
318 return CRM_Core_BAO_Mapping::formattedFields($formValues);
319 }
320
321 /**
322 * @return array
323 */
324 public function &returnProperties() {
325 return CRM_Core_BAO_Mapping::returnProperties($this->_formValues);
326 }
327
328 /**
329 * Process the uploaded file.
330 */
331 public function postProcess() {
332 $this->set('isAdvanced', '2');
333 $this->set('isSearchBuilder', '1');
334 $this->set('showSearchForm', FALSE);
335
336 $params = $this->controller->exportValues($this->_name);
337 if (!empty($params)) {
338 // Add another block
339 if (!empty($params['addBlock'])) {
340 $this->set('newBlock', $this->_blockCount);
341 $this->_blockCount += 3;
342 $this->set('blockCount', $this->_blockCount);
343 $this->set('showSearchForm', TRUE);
344 return;
345 }
346 // Add another field
347 $addMore = CRM_Utils_Array::value('addMore', $params);
348 for ($x = 1; $x <= $this->_blockCount; $x++) {
349 if (!empty($addMore[$x])) {
350 $this->set('newBlock', $x);
351 $this->_columnCount[$x] = $this->_columnCount[$x] + 5;
352 $this->set('columnCount', $this->_columnCount);
353 $this->set('showSearchForm', TRUE);
354 return;
355 }
356 }
357 $this->set('newBlock', NULL);
358 $checkEmpty = NULL;
359 foreach ($params['mapper'] as $key => $value) {
360 foreach ($value as $k => $v) {
361 if ($v[0]) {
362 $checkEmpty++;
363 }
364 }
365 }
366
367 if (!$checkEmpty) {
368 $this->set('newBlock', 1);
369 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/search/builder', '_qf_Builder_display=true'));
370 }
371 }
372
373 // get user submitted values
374 // get it from controller only if form has been submitted, else preProcess has set this
375 if (!empty($_POST)) {
376 $this->_formValues = $this->controller->exportValues($this->_name);
377
378 // set the group if group is submitted
379 if (!empty($this->_formValues['uf_group_id'])) {
380 $this->set('id', $this->_formValues['uf_group_id']);
381 }
382 else {
383 $this->set('id', '');
384 }
385 }
386
387 // we dont want to store the sortByCharacter in the formValue, it is more like
388 // a filter on the result set
389 // this filter is reset if we click on the search button
390 if ($this->_sortByCharacter !== NULL && empty($_POST)) {
391 if (strtolower($this->_sortByCharacter) == 'all') {
392 $this->_formValues['sortByCharacter'] = NULL;
393 }
394 else {
395 $this->_formValues['sortByCharacter'] = $this->_sortByCharacter;
396 }
397 }
398 else {
399 $this->_sortByCharacter = NULL;
400 }
401
402 $this->_params = $this->convertFormValues($this->_formValues);
403 $this->_returnProperties = &$this->returnProperties();
404
405 // CRM-10338 check if value is empty array
406 foreach ($this->_params as $k => $v) {
407 $this->_params[$k][2] = self::checkArrayKeyEmpty($v[2]);
408 }
409
410 parent::postProcess();
411 }
412
413 /**
414 * @return array
415 */
416 public static function fields() {
417 $fields = array_merge(
418 CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE),
419 CRM_Core_Component::getQueryFields(),
420 CRM_Contact_BAO_Query_Hook::singleton()->getFields(),
421 CRM_Activity_BAO_Activity::exportableFields()
422 );
423 return $fields;
424 }
425
426 /**
427 * CRM-9434 Hackish function to fetch fields with options.
428 * FIXME: When our core fields contain reliable metadata this will be much simpler.
429 * @return array
430 * (string => string) key: field_name value: api entity name
431 * Note: options are fetched via ajax using the api "getoptions" method
432 */
433 public static function fieldOptions() {
434 // Hack to add options not retrieved by getfields
435 // This list could go on and on, but it would be better to fix getfields
436 $options = array(
437 'group' => 'group_contact',
438 'tag' => 'entity_tag',
439 'on_hold' => 'yesno',
440 'is_bulkmail' => 'yesno',
441 'payment_instrument' => 'contribution',
442 'membership_status' => 'membership',
443 'membership_type' => 'membership',
444 'member_campaign_id' => 'membership',
445 'member_is_test' => 'yesno',
446 'member_is_pay_later' => 'yesno',
447 'is_override' => 'yesno',
448 );
449 $entities = array(
450 'contact',
451 'address',
452 'activity',
453 'participant',
454 'pledge',
455 'member',
456 'contribution',
457 'case',
458 'grant',
459 );
460 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchBuilderOptions($entities, $options);
461 foreach ($entities as $entity) {
462 $fields = civicrm_api3($entity, 'getfields');
463 foreach ($fields['values'] as $field => $info) {
464 if (!empty($info['options']) || !empty($info['pseudoconstant']) || !empty($info['option_group_id'])) {
465 $options[$field] = $entity;
466 // Hack for when search field doesn't match db field - e.g. "country" instead of "country_id"
467 if (substr($field, -3) == '_id') {
468 $options[substr($field, 0, -3)] = $entity;
469 }
470 }
471 elseif (!empty($info['data_type']) && in_array($info['data_type'], array('StateProvince', 'Country'))) {
472 $options[$field] = $entity;
473 }
474 elseif (in_array(substr($field, 0, 3), array(
475 'is_',
476 'do_',
477 )) || CRM_Utils_Array::value('data_type', $info) == 'Boolean'
478 ) {
479 $options[$field] = 'yesno';
480 if ($entity != 'contact') {
481 $options[$entity . '_' . $field] = 'yesno';
482 }
483 }
484 elseif (strpos($field, '_is_')) {
485 $options[$field] = 'yesno';
486 }
487 }
488 }
489 return $options;
490 }
491
492 /**
493 * CRM-10338
494 * tags and groups use array keys for selection list.
495 * if using IS NULL/NOT NULL, an array with no array key is created
496 * convert that to simple NULL so processing can proceed
497 */
498 public static function checkArrayKeyEmpty($val) {
499 if (is_array($val)) {
500 $v2empty = TRUE;
501 foreach ($val as $vk => $vv) {
502 if (!empty($vk)) {
503 $v2empty = FALSE;
504 }
505 }
506 if ($v2empty) {
507 $val = NULL;
508 }
509 }
510 return $val;
511 }
512
513 }