3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class is for search builder processing.
37 class CRM_Contact_Form_Search_Builder
extends CRM_Contact_Form_Search
{
40 * Number of columns in where.
47 * Number of blocks to be shown.
54 * Build the form object.
56 public function preProcess() {
57 $this->set('searchFormName', 'Builder');
59 $this->set('context', 'builder');
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);
70 //get the column count
71 $this->_columnCount
= $this->get('columnCount');
73 for ($i = 1; $i < $this->_blockCount
; $i++
) {
74 if (empty($this->_columnCount
[$i])) {
75 $this->_columnCount
[$i] = 5;
79 $this->_loadedMappingId
= $this->get('savedMapping');
81 if ($this->get('showSearchForm')) {
82 $this->assign('showSearchForm', TRUE);
85 $this->assign('showSearchForm', FALSE);
92 public function buildQuickForm() {
93 $fields = self
::fields();
94 $searchByLabelFields = array();
95 // This array contain list of available fields and their corresponding data type,
96 // later assigned as json string, to be used to filter list of mysql operators
98 foreach ($fields as $name => $field) {
99 // Assign date type to respective field name, which will be later used to modify operator list
100 $fieldNameTypes[$name] = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
101 // it's necessary to know which of the fields are searchable by label
102 if (isset($field['searchByLabel']) && $field['searchByLabel']) {
103 $searchByLabelFields[] = $name;
107 CRM_Core_Resources
::singleton()
108 ->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Search/Builder.js', 1, 'html-header')
110 'searchBuilder' => array(
111 // Index of newly added/expanded block (1-based index)
112 'newBlock' => $this->get('newBlock'),
113 'fieldOptions' => self
::fieldOptions(),
114 'searchByLabelFields' => $searchByLabelFields,
115 'fieldTypes' => $fieldNameTypes,
116 'generalOperators' => array('' => ts('-operator-')) + CRM_Core_SelectValues
::getSearchBuilderOperators(),
119 //get the saved search mapping id
122 $mappingId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $this->_ssID
, 'mapping_id');
125 CRM_Core_BAO_Mapping
::buildMappingForm($this, 'Search Builder', $mappingId, $this->_columnCount
, $this->_blockCount
);
127 parent
::buildQuickForm();
131 * Add local and global form rules.
133 public function addRules() {
134 $this->addFormRule(array('CRM_Contact_Form_Search_Builder', 'formRule'), $this);
138 * Global validation rules for the form.
140 * @param array $values
141 * @param array $files
142 * @param CRM_Core_Form $self
145 * list of errors to be posted back to the form
147 public static function formRule($values, $files, $self) {
148 if (!empty($values['addMore']) ||
!empty($values['addBlock'])) {
151 $fields = self
::fields();
152 $fld = CRM_Core_BAO_Mapping
::formattedFields($values, TRUE);
155 foreach ($fld as $k => $v) {
157 $errorMsg["operator[$v[3]][$v[4]]"] = ts("Please enter the operator.");
161 $v[2] = self
::checkArrayKeyEmpty($v[2]);
163 if (in_array($v[1], array(
171 $errorMsg["value[$v[3]][$v[4]]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1]));
173 elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
177 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
180 $error = CRM_Utils_Type
::validate($v2[0], 'Integer', FALSE);
181 if ($error != $v2[0]) {
182 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
186 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
190 if (substr($v[0], 0, 7) == 'custom_') {
191 // Get rid of appended location type id
192 list($fieldKey) = explode('-', $v[0]);
193 $type = $fields[$fieldKey]['data_type'];
195 // hack to handle custom data of type state and country
196 if (in_array($type, array(
205 // FIXME: no idea at this point what to do with this,
206 // FIXME: but definitely needs fixing.
207 if (substr($v[0], 0, 13) == 'contribution_') {
208 $fldName = substr($v[0], 13);
211 $fldValue = CRM_Utils_Array
::value($fldName, $fields);
212 $fldType = CRM_Utils_Array
::value('type', $fldValue);
213 $type = CRM_Utils_Type
::typeToString($fldType);
215 if (strstr($v[1], 'IN')) {
217 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
220 // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
221 elseif (!in_array($v[1],
222 array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))
224 if ((($type == 'Int' ||
$type == 'Boolean') && !is_array($v[2]) && !trim($v[2])) && $v[2] != '0') {
225 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
227 elseif ($type == 'Date' && !trim($v[2])) {
228 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
233 if ($type && empty($errorMsg)) {
234 // check for valid format while using IN Operator
235 if (strstr($v[1], 'IN')) {
236 if (!is_array($v[2])) {
237 $inVal = trim($v[2]);
238 //checking for format to avoid db errors
239 if ($type == 'Int') {
240 if (!preg_match('/^[A-Za-z0-9\,]+$/', $inVal)) {
241 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
245 if (!preg_match('/^[A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ()\,\s]+$/', $inVal)) {
246 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
251 // Validate each value in parenthesis to avoid db errors
252 if (empty($errorMsg)) {
253 $parenValues = array();
254 $parenValues = is_array($v[2]) ?
(array_key_exists($v[1], $v[2])) ?
$v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)"));
255 foreach ($parenValues as $val) {
256 if ($type == 'Date' ||
$type == 'Timestamp') {
257 $val = CRM_Utils_Date
::processDate($val);
258 if ($type == 'Date') {
259 $val = substr($val, 0, 8);
265 if (!$val && $val != '0') {
266 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter the values correctly.");
268 if (empty($errorMsg)) {
269 $error = CRM_Utils_Type
::validate($val, $type, FALSE);
270 if ($error != $val) {
271 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
277 elseif (trim($v[2])) {
278 //else check value for rest of the Operators
279 if ($type == 'Date' ||
$type == 'Timestamp') {
280 $v[2] = CRM_Utils_Date
::processDate($v[2]);
281 if ($type == 'Date') {
282 $v[2] = substr($v[2], 0, 8);
285 $error = CRM_Utils_Type
::validate($v[2], $type, FALSE);
286 if ($error != $v[2]) {
287 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
295 if (!empty($errorMsg)) {
296 $self->set('showSearchForm', TRUE);
297 $self->assign('rows', NULL);
305 * Normalise form values.
307 public function normalizeFormValues() {
311 * Convert form values.
313 * @param array $formValues
317 public function convertFormValues(&$formValues) {
318 return CRM_Core_BAO_Mapping
::formattedFields($formValues);
322 * Get return properties.
326 public function &returnProperties() {
327 return CRM_Core_BAO_Mapping
::returnProperties($this->_formValues
);
331 * Process the uploaded file.
333 public function postProcess() {
334 $this->set('isAdvanced', '2');
335 $this->set('isSearchBuilder', '1');
336 $this->set('showSearchForm', FALSE);
338 $params = $this->controller
->exportValues($this->_name
);
339 if (!empty($params)) {
341 if (!empty($params['addBlock'])) {
342 $this->set('newBlock', $this->_blockCount
);
343 $this->_blockCount +
= 3;
344 $this->set('blockCount', $this->_blockCount
);
345 $this->set('showSearchForm', TRUE);
349 $addMore = CRM_Utils_Array
::value('addMore', $params);
350 for ($x = 1; $x <= $this->_blockCount
; $x++
) {
351 if (!empty($addMore[$x])) {
352 $this->set('newBlock', $x);
353 $this->_columnCount
[$x] = $this->_columnCount
[$x] +
5;
354 $this->set('columnCount', $this->_columnCount
);
355 $this->set('showSearchForm', TRUE);
359 $this->set('newBlock', NULL);
361 foreach ($params['mapper'] as $key => $value) {
362 foreach ($value as $k => $v) {
370 $this->set('newBlock', 1);
371 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/search/builder', '_qf_Builder_display=true'));
375 // get user submitted values
376 // get it from controller only if form has been submitted, else preProcess has set this
377 if (!empty($_POST)) {
378 $this->_formValues
= $this->controller
->exportValues($this->_name
);
380 // set the group if group is submitted
381 if (!empty($this->_formValues
['uf_group_id'])) {
382 $this->set('id', $this->_formValues
['uf_group_id']);
385 $this->set('id', '');
389 // we dont want to store the sortByCharacter in the formValue, it is more like
390 // a filter on the result set
391 // this filter is reset if we click on the search button
392 if ($this->_sortByCharacter
!== NULL && empty($_POST)) {
393 if (strtolower($this->_sortByCharacter
) == 'all') {
394 $this->_formValues
['sortByCharacter'] = NULL;
397 $this->_formValues
['sortByCharacter'] = $this->_sortByCharacter
;
401 $this->_sortByCharacter
= NULL;
404 $this->_params
= $this->convertFormValues($this->_formValues
);
405 $this->_returnProperties
= &$this->returnProperties();
407 // CRM-10338 check if value is empty array
408 foreach ($this->_params
as $k => $v) {
409 $this->_params
[$k][2] = self
::checkArrayKeyEmpty($v[2]);
412 parent
::postProcess();
420 public static function fields() {
421 $fields = array_merge(
422 CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE),
423 CRM_Core_Component
::getQueryFields(),
424 CRM_Contact_BAO_Query_Hook
::singleton()->getFields(),
425 CRM_Activity_BAO_Activity
::exportableFields()
431 * CRM-9434 Hackish function to fetch fields with options.
433 * FIXME: When our core fields contain reliable metadata this will be much simpler.
435 * (string => string) key: field_name value: api entity name
436 * Note: options are fetched via ajax using the api "getoptions" method
438 public static function fieldOptions() {
439 // Hack to add options not retrieved by getfields
440 // This list could go on and on, but it would be better to fix getfields
442 'group' => 'group_contact',
443 'tag' => 'entity_tag',
444 'on_hold' => 'yesno',
445 'is_bulkmail' => 'yesno',
446 'payment_instrument' => 'contribution',
447 'membership_status' => 'membership',
448 'membership_type' => 'membership',
449 'member_campaign_id' => 'membership',
450 'member_is_test' => 'yesno',
451 'member_is_pay_later' => 'yesno',
452 'is_override' => 'yesno',
465 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchBuilderOptions($entities, $options);
466 foreach ($entities as $entity) {
467 $fields = civicrm_api3($entity, 'getfields');
468 foreach ($fields['values'] as $field => $info) {
469 if (!empty($info['options']) ||
!empty($info['pseudoconstant']) ||
!empty($info['option_group_id'])) {
470 $options[$field] = $entity;
471 // Hack for when search field doesn't match db field - e.g. "country" instead of "country_id"
472 if (substr($field, -3) == '_id') {
473 $options[substr($field, 0, -3)] = $entity;
476 elseif (!empty($info['data_type'])) {
477 if (in_array($info['data_type'], array('StateProvince', 'Country'))) {
478 $options[$field] = $entity;
481 elseif (in_array(substr($field, 0, 3), array(
484 )) || CRM_Utils_Array
::value('data_type', $info) == 'Boolean'
486 $options[$field] = 'yesno';
487 if ($entity != 'contact') {
488 $options[$entity . '_' . $field] = 'yesno';
491 elseif (strpos($field, '_is_')) {
492 $options[$field] = 'yesno';
500 * CRM-10338 tags and groups use array keys for selection list.
502 * if using IS NULL/NOT NULL, an array with no array key is created
503 * convert that to simple NULL so processing can proceed
509 public static function checkArrayKeyEmpty($val) {
510 if (is_array($val)) {
512 foreach ($val as $vk => $vv) {