File: BooleanParser.class.inc

package info (click to toggle)
opendb 0.81p18-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 4,716 kB
  • ctags: 6,787
  • sloc: php: 50,213; sql: 3,098; sh: 272; makefile: 54; xml: 48
file content (512 lines) | stat: -rw-r--r-- 11,339 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
<?php
/* 	OpenDb - Open Media Lending Database
	Copyright (C) 2001,2002 by Jason Pell

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
class BooleanLexer
{
	var $round_brace;
	var $dbl_quote;
	var $error;
	
	var $stackPtr;
	var $tokenStack;
	var $lookahead;
	
	var $tokText;
	var $tokPtr;
	
	var $string;
	var $stringLen;
	
	// Do nothing.
	function BooleanLexer(){}
	
	function parse($string, $lookahead=NULL)
	{
		$this->string = $string;
        $this->stringLen = strlen($string);

		// Initialise		
		$this->round_brace = 0;
		
		if(is_numeric($lookahead))
			$this->lookahead = $lookahead;
		else
			$this->lookahead = 0; // no lookahead
		
		// Initialise lookahead stack
		$this->stackPtr = 0;
		$this->tokenStack = NULL;
	}
	
	/*
	* To get very last character, use get(-1), to get previous character from
	* current one, use -2.  To get next character,without iterating the pointer (to sneek a look),
	* use get(0)
	*/
	function get($idx=NULL)
	{
		if(is_numeric($idx))
		{
			// If idx is negative, this should work as well.
			$index = $this->tokPtr + $idx;
			if($index>=0 && $index < $this->stringLen)
				return $this->string{$index};
			else
				return NULL;
		}
		else
		{
			if($this->tokPtr < $this->stringLen)
				return $this->string{$this->tokPtr++};
			else
				return NULL;// reached end of string
		}
    }
	
	function unget()
	{
        --$this->tokPtr;
	}
	
	function getError()
	{
		return $this->error;
	}
	
	/*
	* Return current token, as returned from nextToken
	*/
	function getToken()
	{
		return $this->tokText;
	}
	
	/**
	*/
	function skipWhiteSpace()
	{
		$c = $this->get();
		if($c != NULL)//end of string
		{
			while($c == ' ' || $c == '\t' || $c == '\n' || $c == '\n')
			{
				$c = $this->get();
			}
		
			// unget last whitespace character.
			$this->unget();
		}			
	}

	/*
	* Convert and / or / not (or any case deviations ) to AND / OR / NOT
	*/
	function normaliseToken($token)
	{
		if(strcasecmp($token,'and')===0)
			return 'AND';
		else if(strcasecmp($token,'or')===0)
			return 'OR';
		else if(strcasecmp($token,'not')===0)
			return 'NOT';
		else
			return $token;
	}
	
	function nextToken()
	{
		if($this->lookahead>0)
		{
        	// The stackPtr, should always be the same as the count of
        	// elements in the tokenStack.  The stackPtr, can be thought
        	// of as pointing to the next token to be added.  If however
        	// a pushBack() call is made, the stackPtr, will be less than the
        	// count, to indicate that we should take that token from the
        	// stack, instead of calling nextToken for a new token.
			if($this->stackPtr < count($this->tokenStack))
			{
				$this->tokText = $this->tokenStack[$this->stackPtr];
            
            	// We have read the token, so now iterate again.
	            $this->stackPtr++;
    	        return $this->tokText;
			}
			else
			{
        	    // If $tokenStack is full (equal to lookahead), pop the oldest
            	// element off, to make room for the new one.
	            if ($this->stackPtr == $this->lookahead)
				{
        	        // For some reason array_shift and
            	    // array_pop screw up the indexing, so we do it manually.
                	for($i=0; $i<(count($this->tokenStack)-1); $i++)
					{
    	                $this->tokenStack[$i] = $this->tokenStack[$i+1];
        	        }
                
            	    // Indicate that we should put the element in
                	// at the stackPtr position.
	                $this->stackPtr--;
    	        }
        
				$this->tokText = $this->normaliseToken($this->_nextToken());
				$this->tokenStack[$this->stackPtr] = $this->tokText;
				$this->stackPtr++;
            	return $this->tokText;
			}				
        }
	    else
    	{
			$this->tokText = $this->normaliseToken($this->_nextToken());
        	return $this->tokText;
		}			
	}
	
	function pushBack()
	{
    	if($this->lookahead>0 && count($this->tokenStack)>0 && $this->stackPtr>0)
		{
        	$this->stackPtr--;
	    }
	}

	/*
	* Hidden function
	*/
	function _nextToken()
	{
		$this->tokText = NULL;
		$dbl_quote = FALSE;
		$expr = "";

		$this->skipWhiteSpace();	
		while(true)
		{
			$c = $this->get();
			switch($c)
			{
				case '"':
					if($this->get(-2)=="\\")
						$expr .= $c;
					else
					{
						if($dbl_quote)
							return $expr;
						else
							$dbl_quote = TRUE;
					}
					break;
			
				case '\\':
					if($this->get(0)!="\"")//Only support escaping double quotes, otherwise
					{						//pass through the escaping characters
						$expr .= $c;
					}
					// else ignore
					break;
			
				case '(':
					if(!$dbl_quote)
					{
						if(strlen($expr)>0)
						{						
							// Unget quote
							$this->unget();
							return $expr;
						}
						else
						{
							$this->round_brace++;
							return $c;
						}
					}
					else
						$expr .= $c;
					break;
			
				case ')':
					if(!$dbl_quote)
					{
						if($this->round_brace>0)
						{
							if(strlen($expr)>0)
							{						
								// Unget bracket
								$this->unget();
								return $expr;
							}
							else
							{
								$this->round_brace--;
								return $c;
							}
						}
						else
						{
							$this->error = "Mismatched braces";
							return FALSE;
						}
					}
					else
						$expr .= $c;
					break;
		
				case ' ':
				case '\t':
				case '\n':
				case '\r':
					if($dbl_quote)
						$expr .= $c;
					else
						return $expr; // Indicates end of token
						
					break;
				
				case NULL: // end of string
					if(strlen($expr)>0)
						return $expr;
					else
						return NULL;
					
				default:
					$expr .= $c;
			}//switch
		}//while
	}
}

class BooleanParser
{
	var $lexer = NULL;
	
	// Do nothing.
	function BooleanParser(){}
	
	function parseBooleanStatement($statement)
	{
		if($this->lexer == NULL)
			$this->lexer = new BooleanLexer();
			
		$this->lexer->parse($statement,1);
		
		while( true )
		{
			$statement = $this->parseStatement();
			if($statement===FALSE)
				return FALSE;
			else if($statement!==NULL)
				$statements[] = $statement;
			else
				break; // finished
		}
		
		return $statements;
	}
	
	function getError()
	{
		return $this->lexer->getError();
	}
	
	function parseStatement()
	{
		$conditions[] = $this->parseCompoundStatement();
		$token = $this->lexer->nextToken();
		while($token == 'OR')
		{
			$conditions[] = $this->parseCompoundStatement();
			$token = $this->lexer->nextToken();
		}
		$this->lexer->pushBack();
		
		if(is_array($conditions) && count($conditions)>1)
			return array('or'=>$conditions);
		else
			return $conditions[0];
	}
	
	/*
	* Will parse several basic 'left <op> right' condition statements, as
	* long as they are separated by AND tokens.
	* 
	* Will also support conditions, enclosed in brackets, and treat them
	* as normal compound conditions.
	* 
	* So the following will be supported
	* 
	* 	<left> <op> <right> AND (<left> <op> <right> OR <left> <op> <right>)
	*/
	function parseCompoundStatement()
	{
		$token = $this->lexer->nextToken();
		if($token == 'NOT')
		{
			return array('not'=>
				$this->parseStatement());
		}
		else if($token == '(')
		{
			$condition = $this->parseStatement();
			$token = $this->lexer->nextToken();
			if($token != ')')
			{
				return FALSE; // should never happen!
			}
		}
		else if($this->isTextToken($token))
		{
			$condition = $token;
		}
		
		if($condition !== FALSE)
		{
			$conditions[] = $condition;
			while(true)
			{
				$token = $this->lexer->nextToken();
				if($token == 'AND')
				{
					$condition = $this->parseCompoundStatement();
					if($condition !== FALSE)
						$conditions[] = $condition;
					else
						return FALSE;
				}//if($token == 'and')
				else
				{
					$this->lexer->pushBack();
					break;
				}
			}

			if(is_array($conditions) && count($conditions)>1)
				return array('and'=>$conditions);
			else
				return $conditions[0];
		}
		else//if($condition !== FALSE)
		{
			return FALSE;
		}
	}
	
	function isTextToken($token)
	{
		if($token == NULL || $token == '(' || $token == ')' || $token == 'AND' || $token == 'OR' || $token == 'NOT')
			return FALSE;
		else
			return TRUE;
	}
}

// ------------------------------------------------
// Utility Functions
// ------------------------------------------------

/*
* @param $column_name
* @param $column_value
* @param $match_mode ["word" | "exact" | "partial"]
*/
function get_compare_clause($column_name, $column_value, $match_mode)
{
	$column_value_wildcard = FALSE;
	for($i=0; $i<strlen($column_value); $i++)
	{
		if( ($column_value[$i] == '%' || $column_value[$i] == '_') && ($i == 0 || $column_value[$i-1] != '\\'))
		{
			$column_value_wildcard = TRUE;
		}
	}

	if($column_value_wildcard)
	{
		return "UPPER($column_name) LIKE '".strtoupper(trim($column_value))."'";
	}
	else
	{
		if(strcasecmp($match_mode,"word")===0)
		{	
			$column_value = strtoupper(trim($column_value));
			
			return "(UPPER($column_name) = '".str_replace('\_','_',$column_value)."' OR ".
				"UPPER($column_name) LIKE '% ".$column_value." %' OR ".
				"UPPER($column_name) LIKE '".$column_value." %' OR ".
				"UPPER($column_name) LIKE '% ".$column_value."')";
		}
		else if(strcasecmp($match_mode,"partial")===0)
		{
			$column_value = strtoupper(trim($column_value));
			
			return "UPPER($column_name) LIKE '%".$column_value."%'";
		}
		else if(strcasecmp($match_mode,"exact")===0)
		{
			return "UPPER($column_name) = '".str_replace('\_','_',strtoupper(trim($column_value)))."'";
		}
		else // plain
		{
			return "$column_name = '".str_replace('\_','_',$column_value)."'";
		}
	}
}

/*
* Builds a where sub-clause based on the statements array returned 
* from BooleanParser::parseBooleanStatement(...)
*/
function build_boolean_clause($statement_rs, $column_name, $match_mode, $mode='AND')
{
	$query = "";
	
	while(list($key,$statement) = each($statement_rs))
	{
		if(strlen($query)>0)
			$query .= " $mode ";
			
		if(is_array($statement['not']))
		{
			$query .= "NOT (".build_boolean_clause($statement['not'], $column_name, $match_mode, $mode).")";
		}
		else if(is_array($statement['and']))
		{
			$query .= "(".build_boolean_clause($statement['and'], $column_name, $match_mode, 'AND').")";
		}
		else if(is_array($statement['or']))
		{
			$query .= "(".build_boolean_clause($statement['or'], $column_name, $match_mode, 'OR').")";
		}
		else if(is_array($statement))
		{
			$query .= "(";
			
			if(isset($statement['not']))
				$query .= "NOT ";
			
			$query .= "(".build_boolean_clause($statement, $column_name, $match_mode, $key=='or'?'OR':$mode).")";

			$query .= ")";
		}
		else
		{
			$query .= get_compare_clause($column_name, $statement, $match_mode);
		}
	}
	return $query;
}
?>