[FEATURE] TypoScript: Allow easy comparison against multiple values
[Packages/TYPO3.CMS.git] / t3lib / matchcondition / class.t3lib_matchcondition_abstract.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009-2011 Oliver Hader <oliver@typo3.org>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Matching TypoScript conditions
29 *
30 * Used with the TypoScript parser.
31 * Matches browserinfo, IPnumbers for use with templates
32 *
33 * @author Oliver Hader <oliver@typo3.org>
34 * @package TYPO3
35 * @subpackage t3lib
36 */
37 abstract class t3lib_matchCondition_abstract {
38 /**
39 * Id of the current page.
40 * @var integer
41 */
42 protected $pageId;
43 /**
44 * The rootline for the current page.
45 * @var array
46 */
47 protected $rootline;
48
49 /**
50 * Whether to simulate the behaviour and match all conditions
51 * (used in TypoScript object browser).
52 * @var boolean
53 */
54 protected $simulateMatchResult = FALSE;
55 /**
56 * Whether to simulat the behaviour and match specific conditions
57 * (used in TypoScript object browser).
58 * @var array
59 */
60 protected $simulateMatchConditions = array();
61
62 /**
63 * Sets the id of the page to evaluate conditions for.
64 *
65 * @param integer $pageId Id of the page (must be positive)
66 * @return void
67 */
68 public function setPageId($pageId) {
69 if (is_integer($pageId) && $pageId > 0) {
70 $this->pageId = $pageId;
71 }
72 }
73
74 /**
75 * Gets the id of the page to evaluate conditions for.
76 *
77 * @return integer Id of the page
78 */
79 public function getPageId() {
80 return $this->pageId;
81 }
82
83 /**
84 * Sets the rootline.
85 *
86 * @param array $rootline The rootline to be used for matching (must have elements)
87 * @return void
88 */
89 public function setRootline(array $rootline) {
90 if (count($rootline)) {
91 $this->rootline = $rootline;
92 }
93 }
94
95 /**
96 * Gets the rootline.
97 *
98 * @return array The rootline to be used for matching
99 */
100 public function getRootline() {
101 return $this->rootline;
102 }
103
104 /**
105 * Sets whether to simulate the behaviour and match all conditions.
106 *
107 * @param boolean $simulateMatchResult Whether to simulate positive matches
108 * @return void
109 */
110 public function setSimulateMatchResult($simulateMatchResult) {
111 if (is_bool($simulateMatchResult)) {
112 $this->simulateMatchResult = $simulateMatchResult;
113 }
114 }
115
116 /**
117 * Sets whether to simulate the behaviour and match specific conditions.
118 *
119 * @param array $simulateMatchConditions Conditions to simulate a match for
120 * @return void
121 */
122 public function setSimulateMatchConditions(array $simulateMatchConditions) {
123 $this->simulateMatchConditions = $simulateMatchConditions;
124 }
125
126 /**
127 * Normalizes an expression and removes the first and last square bracket.
128 * + OR normalization: "...]OR[...", "...]||[...", "...][..." --> "...]||[..."
129 * + AND normalization: "...]AND[...", "...]&&[..." --> "...]&&[..."
130 *
131 * @param string $expression The expression to be normalized (e.g. "[A] && [B] OR [C]")
132 * @return string The normalized expression (e.g. "[A]&&[B]||[C]")
133 */
134 protected function normalizeExpression($expression) {
135 $normalizedExpression = preg_replace(
136 array(
137 '/\]\s*(OR|\|\|)?\s*\[/i',
138 '/\]\s*(AND|&&)\s*\[/i',
139 ),
140 array(
141 ']||[',
142 ']&&[',
143 ),
144 trim($expression)
145 );
146
147 return $normalizedExpression;
148 }
149
150 /**
151 * Matches a TypoScript condition expression.
152 *
153 * @param string $expression The expression to match
154 * @return boolean Whether the expression matched
155 */
156 public function match($expression) {
157 // Return directly if result should be simulated:
158 if ($this->simulateMatchResult) {
159 return $this->simulateMatchResult;
160 }
161 // Return directly if matching for specific condition is simulated only:
162 if (count($this->simulateMatchConditions)) {
163 return in_array($expression, $this->simulateMatchConditions);
164 }
165 // Sets the current pageId if not defined yet:
166 if (!isset($this->pageId)) {
167 $this->pageId = $this->determinePageId();
168 }
169 // Sets the rootline if not defined yet:
170 if (!isset($this->rootline)) {
171 $this->rootline = $this->determineRootline();
172 }
173
174 $result = FALSE;
175 $normalizedExpression = $this->normalizeExpression($expression);
176
177 // First and last character must be square brackets (e.g. "[A]&&[B]":
178 if (substr($normalizedExpression, 0, 1) === '[' && substr($normalizedExpression, -1) === ']') {
179 $innerExpression = substr($normalizedExpression, 1, -1);
180
181 $orParts = explode(']||[', $innerExpression);
182 foreach ($orParts as $orPart) {
183 $andParts = explode(']&&[', $orPart);
184 foreach ($andParts as $andPart) {
185 $result = $this->evaluateCondition($andPart);
186 // If condition in AND context fails, the whole block is FALSE:
187 if ($result === FALSE) {
188 break;
189 }
190 }
191 // If condition in OR context succeeds, the whole expression is TRUE:
192 if ($result === TRUE) {
193 break;
194 }
195 }
196 }
197
198 return $result;
199 }
200
201 /**
202 * Evaluates a TypoScript condition given as input, eg. "[browser=net][...(other conditions)...]"
203 *
204 * @param string $key The condition to match against its criterias.
205 * @param string $value
206 * @return mixed Returns TRUE or FALSE based on the evaluation
207 */
208 protected function evaluateConditionCommon($key, $value) {
209 if (t3lib_div::inList('browser,version,system,useragent', strtolower($key))) {
210 $browserInfo = $this->getBrowserInfo(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
211 }
212 $keyParts = t3lib_div::trimExplode('|', $key);
213
214 switch ($keyParts[0]) {
215 case 'browser':
216 $values = t3lib_div::trimExplode(',', $value, TRUE);
217 // take all identified browsers into account, eg chrome deliver
218 // webkit=>532.5, chrome=>4.1, safari=>532.5
219 // so comparing string will be
220 // "webkit532.5 chrome4.1 safari532.5"
221 $all = '';
222 foreach ($browserInfo['all'] as $key => $value) {
223 $all .= $key . $value . ' ';
224 }
225 foreach ($values as $test) {
226 if (stripos($all, $test) !== FALSE) {
227 return TRUE;
228 }
229 }
230 break;
231 case 'version':
232 $values = t3lib_div::trimExplode(',', $value, TRUE);
233 foreach ($values as $test) {
234 if (strcspn($test, '=<>') == 0) {
235 switch (substr($test, 0, 1)) {
236 case '=':
237 if (doubleval(substr($test, 1)) == $browserInfo['version']) {
238 return TRUE;
239 }
240 break;
241 case '<':
242 if (doubleval(substr($test, 1)) > $browserInfo['version']) {
243 return TRUE;
244 }
245 break;
246 case '>':
247 if (doubleval(substr($test, 1)) < $browserInfo['version']) {
248 return TRUE;
249 }
250 break;
251 }
252 } elseif (strpos(' ' . $browserInfo['version'], $test) == 1) {
253 return TRUE;
254 }
255 }
256 break;
257 case 'system':
258 $values = t3lib_div::trimExplode(',', $value, TRUE);
259 // Take all identified systems into account, e.g. mac for iOS, Linux
260 // for android and Windows NT for Windows XP
261 $allSystems .= ' ' . implode(' ', $browserInfo['all_systems']);
262 foreach ($values as $test) {
263 if (stripos($allSystems, $test) !== FALSE) {
264 return TRUE;
265 }
266 }
267 break;
268 case 'device':
269 if (!isset($this->deviceInfo)) {
270 $this->deviceInfo = $this->getDeviceType(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
271 }
272 $values = t3lib_div::trimExplode(',', $value, TRUE);
273 foreach ($values as $test) {
274 if ($this->deviceInfo == $test) {
275 return TRUE;
276 }
277 }
278 break;
279 case 'useragent':
280 $test = trim($value);
281 if (strlen($test)) {
282 return $this->searchStringWildcard($browserInfo['useragent'], $test);
283 }
284 break;
285 case 'language':
286 $values = t3lib_div::trimExplode(',', $value, TRUE);
287 foreach ($values as $test) {
288 if (preg_match('/^\*.+\*$/', $test)) {
289 $allLanguages = preg_split('/[,;]/', t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE'));
290 if (in_array(substr($test, 1, -1), $allLanguages)) {
291 return TRUE;
292 }
293 } elseif (t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE') == $test) {
294 return TRUE;
295 }
296 }
297 break;
298 case 'IP':
299 if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
300 return TRUE;
301 }
302 break;
303 case 'hostname':
304 if (t3lib_div::cmpFQDN(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
305 return TRUE;
306 }
307 break;
308 // hour, minute, dayofweek, dayofmonth, month, year, julianday
309 case 'hour':
310 case 'minute':
311 case 'month':
312 case 'year':
313 case 'dayofweek':
314 case 'dayofmonth':
315 case 'dayofyear':
316 // In order to simulate time properly in templates.
317 $theEvalTime = $GLOBALS['SIM_EXEC_TIME'];
318 switch ($key) {
319 case 'hour':
320 $theTestValue = date('H', $theEvalTime);
321 break;
322 case 'minute':
323 $theTestValue = date('i', $theEvalTime);
324 break;
325 case 'month':
326 $theTestValue = date('m', $theEvalTime);
327 break;
328 case 'year':
329 $theTestValue = date('Y', $theEvalTime);
330 break;
331 case 'dayofweek':
332 $theTestValue = date('w', $theEvalTime);
333 break;
334 case 'dayofmonth':
335 $theTestValue = date('d', $theEvalTime);
336 break;
337 case 'dayofyear':
338 $theTestValue = date('z', $theEvalTime);
339 break;
340 }
341 $theTestValue = intval($theTestValue);
342 // comp
343 $values = t3lib_div::trimExplode(',', $value, TRUE);
344 foreach ($values as $test) {
345 if (t3lib_utility_Math::canBeInterpretedAsInteger($test)) {
346 $test = '=' . $test;
347 }
348 if ($this->compareNumber($test, $theTestValue)) {
349 return TRUE;
350 }
351 }
352 break;
353 case 'compatVersion':
354 return t3lib_div::compat_version($value);
355 break;
356 case 'loginUser':
357 if ($this->isUserLoggedIn()) {
358 $values = t3lib_div::trimExplode(',', $value, TRUE);
359 foreach ($values as $test) {
360 if ($test == '*' || !strcmp($this->getUserId(), $test)) {
361 return TRUE;
362 }
363 }
364 } elseif ($value === '') {
365 return TRUE;
366 }
367 break;
368 case 'page':
369 if ($keyParts[1]) {
370 $page = $this->getPage();
371 $property = $keyParts[1];
372 if (!empty($page) && isset($page[$property])) {
373 if (strcmp($page[$property], $value) === 0) {
374 return TRUE;
375 }
376 }
377 }
378 break;
379 case 'globalVar':
380 $values = t3lib_div::trimExplode(',', $value, TRUE);
381 foreach ($values as $test) {
382 $point = strcspn($test, '!=<>');
383 $theVarName = substr($test, 0, $point);
384 $nv = $this->getVariable(trim($theVarName));
385 $testValue = substr($test, $point);
386
387 if ($this->compareNumber($testValue, $nv)) {
388 return TRUE;
389 }
390 }
391 break;
392 case 'globalString':
393 $values = t3lib_div::trimExplode(',', $value, TRUE);
394 foreach ($values as $test) {
395 $point = strcspn($test, '=');
396 $theVarName = substr($test, 0, $point);
397 $nv = $this->getVariable(trim($theVarName));
398 $testValue = substr($test, $point + 1);
399
400 if ($this->searchStringWildcard($nv, trim($testValue))) {
401 return TRUE;
402 }
403 }
404 break;
405 case 'userFunc':
406 $values = preg_split('/\(|\)/', $value);
407 $funcName = trim($values[0]);
408 $funcValue = t3lib_div::trimExplode(',', $values[1]);
409 if (function_exists($funcName) && call_user_func($funcName, $funcValue[0])) {
410 return TRUE;
411 }
412 break;
413 }
414
415 return NULL;
416 }
417
418 /**
419 * Get variable common
420 *
421 * @param array $vars
422 * @return mixed Whatever value. If none, then NULL.
423 */
424 protected function getVariableCommon(array $vars) {
425 $value = NULL;
426
427 if (count($vars) == 1) {
428 $value = $this->getGlobal($vars[0]);
429 } else {
430 $splitAgain = explode('|', $vars[1], 2);
431 $k = trim($splitAgain[0]);
432
433 if ($k) {
434 switch ((string) trim($vars[0])) {
435 case 'GP':
436 $value = t3lib_div::_GP($k);
437 break;
438 case 'ENV':
439 $value = getenv($k);
440 break;
441 case 'IENV':
442 $value = t3lib_div::getIndpEnv($k);
443 break;
444 // return literal value:
445 case 'LIT':
446 return trim($vars[1]);
447 break;
448 default:
449 return NULL;
450 }
451 // If array:
452 if (count($splitAgain) > 1) {
453 if (is_array($value) && trim($splitAgain[1])) {
454 $value = $this->getGlobal($splitAgain[1], $value);
455 } else {
456 $value = '';
457 }
458 }
459 }
460 }
461
462 return $value;
463 }
464
465 /**
466 * Evaluates a $leftValue based on an operator: "<", ">", "<=", ">=", "!=" or "="
467 *
468 * @param string $test The value to compare with on the form [operator][number]. Eg. "< 123"
469 * @param integer $leftValue The value on the left side
470 * @return boolean If $value is "50" and $test is "< 123" then it will return TRUE.
471 */
472 protected function compareNumber($test, $leftValue) {
473 if (preg_match('/^(!?=+|<=?|>=?)\s*([^\s]*)\s*$/', $test, $matches)) {
474 $operator = $matches[1];
475 $rightValue = $matches[2];
476
477 switch ($operator) {
478 case '>=':
479 return ($leftValue >= doubleval($rightValue));
480 break;
481 case '<=':
482 return ($leftValue <= doubleval($rightValue));
483 break;
484 case '!=':
485 // multiple values may be split with '|'
486 // see if none matches ("not in list")
487 $found = FALSE;
488
489 $rightValueParts = t3lib_div::trimExplode('|', $rightValue);
490 foreach ($rightValueParts as $rightValueSingle) {
491 if ($leftValue === doubleval($rightValueSingle)) {
492 $found = TRUE;
493 break;
494 }
495 }
496
497 return ($found === FALSE);
498 break;
499 case '<':
500 return ($leftValue < doubleval($rightValue));
501 break;
502 case '>':
503 return ($leftValue > doubleval($rightValue));
504 break;
505 default:
506 // nothing valid found except '=', use '='
507
508 // multiple values may be split with '|'
509 // see if one matches ("in list")
510 $found = FALSE;
511
512 $rightValueParts = t3lib_div::trimExplode('|', $rightValue);
513 foreach ($rightValueParts as $rightValueSingle) {
514 if ($leftValue == $rightValueSingle) {
515 $found = TRUE;
516 break;
517 }
518 }
519
520 return $found;
521 break;
522 }
523 }
524
525 return FALSE;
526 }
527
528 /**
529 * Matching two strings against each other, supporting a "*" wildcard or (if wrapped in "/") PCRE regular expressions
530 *
531 * @param string $haystack The string in which to find $needle.
532 * @param string $needle The string to find in $haystack
533 * @return boolean Returns TRUE if $needle matches or is found in (according to wildcards) in $haystack. Eg. if $haystack is "Netscape 6.5" and $needle is "Net*" or "Net*ape" then it returns TRUE.
534 */
535 protected function searchStringWildcard($haystack, $needle) {
536 $result = FALSE;
537
538 if ($needle) {
539 if (preg_match('/^\/.+\/$/', $needle)) {
540 // Regular expression, only "//" is allowed as delimiter
541 $regex = $needle;
542 } else {
543 $needle = str_replace(array('*', '?'), array('###MANY###', '###ONE###'), $needle);
544 $regex = '/^' . preg_quote($needle, '/') . '$/';
545 // Replace the marker with .* to match anything (wildcard)
546 $regex = str_replace(array('###MANY###', '###ONE###'), array('.*', '.'), $regex);
547 }
548
549 $result = (boolean) preg_match($regex, (string) $haystack);
550 }
551
552 return $result;
553 }
554
555 /**
556 * Generates an array with abstracted browser information
557 *
558 * @param string $userAgent The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
559 * @return array Contains keys "browser", "version", "system"
560 */
561 protected function getBrowserInfo($userAgent) {
562 return t3lib_utility_Client::getBrowserInfo($userAgent);
563 }
564
565 /**
566 * Gets a code for a browsing device based on the input useragent string.
567 *
568 * @param string $userAgent The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
569 * @return string Code for the specific device type
570 */
571 protected function getDeviceType($userAgent) {
572 return t3lib_utility_Client::getDeviceType($userAgent);
573 }
574
575 /**
576 * Return global variable where the input string $var defines array keys separated by "|"
577 * Example: $var = "HTTP_SERVER_VARS | something" will return the value $GLOBALS['HTTP_SERVER_VARS']['something'] value
578 *
579 * @param string $var Global var key, eg. "HTTP_GET_VAR" or "HTTP_GET_VARS|id" to get the GET parameter "id" back.
580 * @param array $source Alternative array than $GLOBAL to get variables from.
581 * @return mixed Whatever value. If none, then blank string.
582 */
583 protected function getGlobal($var, $source = NULL) {
584 $vars = explode('|', $var);
585 $c = count($vars);
586 $k = trim($vars[0]);
587 $theVar = isset($source) ? $source[$k] : $GLOBALS[$k];
588
589 for ($a = 1; $a < $c; $a++) {
590 if (!isset($theVar)) {
591 break;
592 }
593
594 $key = trim($vars[$a]);
595 if (is_object($theVar)) {
596 $theVar = $theVar->$key;
597 } elseif (is_array($theVar)) {
598 $theVar = $theVar[$key];
599 } else {
600 return '';
601 }
602 }
603
604 if (!is_array($theVar) && !is_object($theVar)) {
605 return $theVar;
606 } else {
607 return '';
608 }
609 }
610
611 /**
612 * Evaluates a TypoScript condition given as input, eg. "[browser=net][...(other conditions)...]"
613 *
614 * @param string $string The condition to match against its criterias.
615 * @return boolean Whether the condition matched
616 * @see t3lib_tsparser::parse()
617 */
618 abstract protected function evaluateCondition($string);
619
620 /**
621 * Gets the value of a variable.
622 *
623 * Examples of names:
624 * + TSFE:id
625 * + GP:firstLevel|secondLevel
626 * + _GET|firstLevel|secondLevel
627 * + LIT:someLiteralValue
628 *
629 * @param string $name The name of the variable to fetch the value from
630 * @return mixed The value of the given variable (string) or NULL if variable did not exist
631 */
632 abstract protected function getVariable($name);
633
634 /**
635 * Gets the usergroup list of the current user.
636 *
637 * @return string The usergroup list of the current user
638 */
639 abstract protected function getGroupList();
640
641 /**
642 * Determines the current page Id.
643 *
644 * @return integer The current page Id
645 */
646 abstract protected function determinePageId();
647
648 /**
649 * Gets the properties for the current page.
650 *
651 * @return array The properties for the current page.
652 */
653 abstract protected function getPage();
654
655 /**
656 * Determines the rootline for the current page.
657 *
658 * @return array The rootline for the current page.
659 */
660 abstract protected function determineRootline();
661
662 /**
663 * Gets the id of the current user.
664 *
665 * @return integer The id of the current user
666 */
667 abstract protected function getUserId();
668
669 /**
670 * Determines if a user is logged in.
671 *
672 * @return boolean Determines if a user is logged in
673 */
674 abstract protected function isUserLoggedIn();
675
676 /**
677 * Sets a log message.
678 *
679 * @param string $message The log message to set/write
680 * @return void
681 */
682 abstract protected function log($message);
683 }
684
685 ?>