From 04b0b3d8552412de5e3bb68afdf2d838e076f584 Mon Sep 17 00:00:00 2001 From: ldestailleur Date: Tue, 4 Mar 2025 20:50:54 +0100 Subject: [PATCH] FIX in dev for #33324 --- htdocs/core/lib/functions.lib.php | 14 ++++++++++---- test/phpunit/FunctionsLibTest.php | 18 +++++++++++++++++- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index d6fd9f751ff..fee55e6481a 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -11959,15 +11959,20 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) $value = preg_replace('/\s*\|\s*/', '|', $value); - // Split criteria on ' ' but not if we are inside quotes - $crits = dolExplodeKeepIfQuotes($value); + // Split criteria on ' ' but not if we are inside quotes. + // For mode 3, the split is done later on the , only and not on the ' '. + if ($mode != -3 && $mode != 3) { + $crits = dolExplodeKeepIfQuotes($value); + } else { + $crits = array($value); + } $res = ''; if (!is_array($fields)) { $fields = array($fields); } - $i1 = 0; // count the nb of and criteria added (all fields / criteria) + $i1 = 0; // count the nb of "and" criteria added (all fields / criteria) foreach ($crits as $crit) { // Loop on each AND criteria $crit = trim($crit); $i2 = 0; // count the nb of valid criteria added for this this first criteria @@ -12022,7 +12027,8 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) $listofcodes .= "'".$db->escape($val)."'"; } } - $newres .= ($i2 > 0 ? ' OR ' : '').$db->sanitize($field)." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")"; + + $newres .= ($i2 > 0 ? ' OR ' : '').$db->sanitize($field)." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1, 0, 1).")"; $i2++; // a criteria for 1 more field was added to string } if ($mode == -3) { diff --git a/test/phpunit/FunctionsLibTest.php b/test/phpunit/FunctionsLibTest.php index 135a83de392..30fb513b859 100644 --- a/test/phpunit/FunctionsLibTest.php +++ b/test/phpunit/FunctionsLibTest.php @@ -1894,7 +1894,6 @@ class FunctionsLibTest extends CommonClassTest return true; } - /** * testRoundUpToNextMultiple * @@ -1918,4 +1917,21 @@ class FunctionsLibTest extends CommonClassTest $this->assertEquals(roundUpToNextMultiple(40.5, 6), 42); $this->assertEquals(roundUpToNextMultiple(44.5, 6), 48); } + + /** + * testNaturalSearch + * + * @return void; + */ + public function testNaturalSearch() + { + $s = natural_search("t.field", "abc def"); + $this->assertEquals($s, " AND (t.field LIKE '%abc%' AND t.field LIKE '%def%')"); + + $s = natural_search("t.field", "'abc def' ghi"); + $this->assertEquals($s, " AND (t.field LIKE '%abc def%' AND t.field LIKE '%ghi%')"); + + $s = natural_search("t.field", "abc def,ghi", 3); + $this->assertEquals($s, " AND (t.field IN ('abc def','ghi'))"); + } }