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
<?php
/**
***********************************************************************************************
* @copyright 2004-2016 The Admidio Team
* @see http://www.admidio.org/
* @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2.0 only
***********************************************************************************************
*/
/**
* @class ConditionParser
* @brief Creates from a custom condition syntax a sql condition
*
* The user can write a condition in a special syntax. This class will parse
* that condition and creates a valid SQL statement which can be used in
* another SQL statement to select data with these conditions.
* This class uses AdmExceptions when an error occurred. Make sure you catch these
* exceptions when using the class.
* @par Examples
* @code // create a valid SQL condition out of the special syntax
* $parser = new ConditionParser;
* $sqlCondition = $parser->makeSqlStatement('> 5 AND <= 100', 'usd_value', 'int');
* $sql = 'SELECT * FROM '.TBL_USER_DATA.' WHERE usd_id > 0 AND '.$sqlCondition; @endcode
*/
class ConditionParser
{
private $mSrcCond; ///< The source condition with the user specific condition
private $mDestCond; ///< The destination string with the valid sql statement
private $mSrcCondArray; ///< An array from the string @b mSrcCond where every char is one array element
private $mNotExistsSql = ''; ///< Stores the sql statement if a record should not exists when user wants to exclude a column
private $mOpenQuotes = false; ///< Flag if there is a open quote in this condition that must be closed before the next condition will be parsed
/**
* Creates a valid date format @b YYYY-MM-DD for the SQL statement
* @param string $date The unformated date from user input e.g. @b 12.04.2012
* @param string $operator The actual operator for the @b date parameter
* @return string String with a SQL valid date format @b YYYY-MM-DD
*/
private function getFormatDate($date, $operator)
{
global $gPreferences;
$formatDate = '';
// if last char is Y or J then user searches for age
$last = substr($date, -1);
$last = admStrToUpper($last);
if($last === 'J' || $last === 'Y')
{
$age = (int) substr($date, 0, -1);
$date = DateTime::createFromFormat('Y-m-d', date('Y').'-'.date('m').'-'.date('d'));
$ageCondition = '';
switch ($operator)
{
case '=':
// first remove = from destination condition
$this->mDestCond = substr($this->mDestCond, 0, -4);
// now compute the dates for a valid birthday with that age
$date->modify('-'.$age.' years');
$dateTo = $date->format('Y-m-d');
$date->modify('-1 year');
$date->modify('+1 day');
$dateFrom = $date->format('Y-m-d');
$ageCondition = ' BETWEEN \''.$dateFrom.'\' AND \''.$dateTo.'\'';
$this->mOpenQuotes = false;
break;
case '}':
// search for dates that are older than the age
// because the age itself takes 1 year we must add 1 year and 1 day to age
$date->modify('-'.($age + 1).' years');
$date->modify('+1 day');
$ageCondition = $date->format('Y-m-d');
break;
case '{':
// search for dates that are younger than the age
// we must add 1 day to the date because the day itself belongs to the age
$date->modify('-'.$age.' years');
$date->modify('+1 day');
$ageCondition = $date->format('Y-m-d');
break;
}
return $ageCondition;
}
// validate date and return it in database format
if($date !== '')
{
$dateObject = DateTime::createFromFormat($gPreferences['system_date'], $date);
if($dateObject !== false)
{
$formatDate = $dateObject->format('Y-m-d');
}
}
return $formatDate;
}
/**
* Replace different user conditions with predefined chars that
* represents a special condition e.g. @b ! represents @b != and @b <>
* @param string $sourceCondition The user condition string
* @return string String with the predefined chars for conditions
*/
public function makeStandardCondition($sourceCondition)
{
global $gL10n;
$this->mSrcCond = admStrToUpper(trim($sourceCondition));
$replaceArray = array(
'*' => '%',
// valid 'not null' is '#'
admStrToUpper($gL10n->get('SYS_NOT_EMPTY')) => ' # ',
' NOT NULL ' => ' # ',
// valid 'null' is '_'
admStrToUpper($gL10n->get('SYS_EMPTY')) => ' _ ',
' NULL ' => ' _ ',
// valid 'is not' is '!'
'{}' => ' ! ',
'!=' => ' ! ',
// valid 'is' is '='
'==' => ' = ',
' LIKE ' => ' = ',
' IS ' => ' = ',
' IST ' => ' = ',
// valid 'less than' is '['
'{=' => ' [ ',
'={' => ' [ ',
// valid 'greater than' is ']'
'}=' => ' ] ',
'=}' => ' ] ',
// valid 'and' is '&'
' AND ' => ' & ',
' UND ' => ' & ',
'&&' => ' & ',
'+' => ' & ',
// valid 'or' is '|'
' OR ' => ' | ',
' ODER ' => ' | ',
'||' => ' | '
);
$this->mSrcCond = str_replace(array_keys($replaceArray), array_values($replaceArray), $this->mSrcCond);
return $this->mSrcCond;
}
/**
* Creates from a user defined condition a valid SQL condition
* @param string $sourceCondition The user condition string
* @param string $columnName The name of the database column for which the condition should be created
* @param string $columnType The type of the column. Valid types are @b string, @b int, @b date and @b checkbox
* @param string $fieldName The name of the profile field. This is used for error output to the end user
* @throws AdmException LST_NOT_VALID_DATE_FORMAT
* LST_NOT_NUMERIC
* @return string Returns a valid SQL string with the condition for that column
*/
public function makeSqlStatement($sourceCondition, $columnName, $columnType, $fieldName)
{
$bStartCondition = true; // gibt an, dass eine neue Bedingung angefangen wurde
$bNewCondition = true; // in Stringfeldern wird nach einem neuen Wort gesucht -> neue Bedingung
$bStartOperand = false; // gibt an, ob bei num. oder Datumsfeldern schon <>= angegeben wurde
$this->mOpenQuotes = false; // set to true if quotes for conditions are open
$date = ''; // Variable speichert bei Datumsfeldern das gesamte Datum
$operator = '='; // saves the actual operator, if no operator is set then = will be default
$this->mDestCond = '';
if($sourceCondition !== '' && $columnName !== '' && $columnType !== '')
{
$this->mSrcCond = $this->makeStandardCondition($sourceCondition);
$this->mSrcCondArray = str_split($this->mSrcCond);
// Bedingungen fuer das Feld immer mit UND starten
if($columnType === 'string')
{
$this->mDestCond = ' AND ( UPPER('.$columnName.') ';
}
elseif($columnType === 'checkbox')
{
// Sonderfall !!!
// bei einer Checkbox kann es nur 1 oder 0 geben und keine komplizierten Verknuepfungen
if($sourceCondition === '1')
{
$this->mDestCond = ' AND '.$columnName.' = 1 ';
}
else
{
$this->mDestCond = ' AND ('.$columnName.' IS NULL OR '.$columnName.' = 0) ';
}
return $this->mDestCond;
}
else
{
$this->mDestCond = ' AND ( '.$columnName.' ';
}
// Zeichen fuer Zeichen aus dem Bedingungsstring wird hier verarbeitet
for($mCount = 0, $mCountMax = strlen($this->mSrcCond); $mCount < $mCountMax; ++$mCount)
{
$character = $this->mSrcCondArray[$mCount];
if($character === '&' || $character === '|')
{
if($bNewCondition)
{
// neue Bedingung, also Verknuepfen
if($character === '&')
{
$this->mDestCond .= ' AND ';
}
elseif($character === '|')
{
$this->mDestCond .= ' OR ';
}
// Feldname noch dahinter
if($columnType === 'string')
{
$this->mDestCond .= ' UPPER('.$columnName.') ';
}
else
{
$this->mDestCond .= ' '.$columnName.' ';
}
$bStartCondition = true;
}
}
else
{
// Verleich der Werte wird hier verarbeitet
if($character === '='
|| $character === '!'
|| $character === '_'
|| $character === '#'
|| $character === '{'
|| $character === '}'
|| $character === '['
|| $character === ']')
{
// save actual operator for later use
$operator = $character;
if(!$bStartCondition)
{
$this->mDestCond .= ' AND '.$columnName.' ';
$bStartCondition = true;
}
switch ($character)
{
case '=':
if ($columnType === 'string')
{
$this->mDestCond .= ' LIKE ';
}
else
{
$this->mDestCond .= ' = ';
}
break;
case '!':
if ($columnType === 'string')
{
$this->mDestCond .= ' NOT LIKE ';
}
else
{
$this->mDestCond .= ' <> ';
}
break;
case '_':
$this->mDestCond .= ' IS NULL ';
if($this->mNotExistsSql !== '')
{
$this->mDestCond .= ' OR NOT EXISTS ('.$this->mNotExistsSql.') ';
}
break;
case '#':
$this->mDestCond .= ' IS NOT NULL ';
if($this->mNotExistsSql !== '')
{
$this->mDestCond .= ' OR EXISTS ('.$this->mNotExistsSql.') ';
}
break;
case '{':
// bastwe: invert condition on age search
if($columnType === 'date'
&& (strpos(admStrToUpper($sourceCondition), 'J') !== false
|| strpos(admStrToUpper($sourceCondition), 'Y') !== false))
{
$this->mDestCond .= ' > ';
}
else
{
$this->mDestCond .= ' < ';
}
break;
case '}':
// bastwe: invert condition on age search
if($columnType === 'date'
&& (strpos(admStrToUpper($sourceCondition), 'J') !== false
|| strpos(admStrToUpper($sourceCondition), 'Y') !== false))
{
$this->mDestCond .= ' < ';
}
else
{
$this->mDestCond .= ' > ';
}
break;
case '[':
// bastwe: invert condition on age search
if($columnType === 'date'
&& (strpos(admStrToUpper($sourceCondition), 'J') !== false
|| strpos(admStrToUpper($sourceCondition), 'Y') !== false))
{
$this->mDestCond .= ' >= ';
}
else
{
$this->mDestCond .= ' <= ';
}
break;
case ']':
// bastwe: invert condition on age search
if($columnType === 'date'
&& (strpos(admStrToUpper($sourceCondition), 'J') !== false
|| strpos(admStrToUpper($sourceCondition), 'Y') !== false))
{
$this->mDestCond .= ' <= ';
}
else
{
$this->mDestCond .= ' >= ';
}
break;
default:
$this->mDestCond .= $character;
}
if($character !== '_' && $character !== '#')
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->mDestCond .= ' \'';
$this->mOpenQuotes = true;
$bStartOperand = true;
}
}
else
{
// pruefen, ob ein neues Wort anfaengt
if($character === ' ' && !$bNewCondition)
{
// if date column than the date will be saved in $date.
// This variable must then be parsed and changed in a valid database format
if($columnType === 'date' && $date !== '')
{
if($this->getFormatDate($date, $operator) !== '')
{
$this->mDestCond .= $this->getFormatDate($date, $operator);
}
else
{
throw new AdmException('LST_NOT_VALID_DATE_FORMAT', $fieldName);
}
$date = '';
}
if($this->mOpenQuotes)
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->mDestCond .= '\' ';
$this->mOpenQuotes = false;
}
$bNewCondition = true;
}
elseif($character !== ' ')
{
// neues Suchwort, aber noch keine Bedingung
if($bNewCondition && !$bStartCondition)
{
if($columnType === 'string')
{
$this->mDestCond .= ' AND UPPER('.$columnName.') ';
}
else
{
$this->mDestCond .= ' AND '.$columnName.' = ';
}
$this->mOpenQuotes = false;
}
elseif($bNewCondition && !$bStartOperand)
{
// first condition of these column
if($columnType === 'string')
{
$this->mDestCond .= ' LIKE \'';
}
else
{
$this->mDestCond .= ' = \'';
}
$this->mOpenQuotes = true;
}
// Zeichen an Zielstring dranhaengen
if($columnType === 'date')
{
$date .= $character;
}
elseif($columnType === 'int' && !is_numeric($character))
{
// if numeric field than only numeric characters are allowed
throw new AdmException('LST_NOT_NUMERIC', $fieldName);
}
else
{
$this->mDestCond .= $character;
}
$bNewCondition = false;
$bStartCondition = false;
}
}
}
}
// if date column than the date will be saved in $date.
// This variable must then be parsed and changed in a valid database format
if($columnType === 'date' && $date !== '')
{
if($this->getFormatDate($date, $operator) !== '')
{
$this->mDestCond .= $this->getFormatDate($date, $operator);
}
else
{
throw new AdmException('LST_NOT_VALID_DATE_FORMAT', $fieldName);
}
}
if($this->mOpenQuotes)
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->mDestCond .= '\' ';
}
$this->mDestCond .= ' ) ';
}
return $this->mDestCond;
}
/**
* Stores an sql statement that checks if a record in a table does exists or not exists.
* This must bei a full subselect that starts with SELECT. The statement is used if
* a condition with EMPTY or NOT EMPTY is used.
* @param string $sqlStatement String with the full subselect
* @par Examples
* @code $parser->setNotExistsStatement('SELECT 1 FROM adm_user_data WHERE usd_usr_id = 1 AND usd_usf_id = 9'); @endcode
*/
public function setNotExistsStatement($sqlStatement)
{
$this->mNotExistsSql = $sqlStatement;
}
}