Follow-up to issue #16878: Keep t3lib_utility_Client::getBrowserInfo backwards compat...
[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 * $Id$
31 *
32 * Used with the TypoScript parser.
33 * Matches browserinfo, IPnumbers for use with templates
34 *
35 * @author Oliver Hader <oliver@typo3.org>
36 * @package TYPO3
37 * @subpackage t3lib
38 */
39 abstract class t3lib_matchCondition_abstract {
40 /**
41 * Id of the current page.
42 * @var integer
43 */
44 protected $pageId;
45 /**
46 * The rootline for the current page.
47 * @var array
48 */
49 protected $rootline;
50
51 /**
52 * Whether to simulate the behaviour and match all conditions
53 * (used in TypoScript object browser).
54 * @var boolean
55 */
56 protected $simulateMatchResult = FALSE;
57 /**
58 * Whether to simulat the behaviour and match specific conditions
59 * (used in TypoScript object browser).
60 * @var array
61 */
62 protected $simulateMatchConditions = array();
63
64 /**
65 * Sets the id of the page to evaluate conditions for.
66 *
67 * @param integer $pageId: Id of the page (must be positive)
68 * @return void
69 */
70 public function setPageId($pageId) {
71 if (is_integer($pageId) && $pageId > 0) {
72 $this->pageId = $pageId;
73 }
74 }
75
76 /**
77 * Gets the id of the page to evaluate conditions for.
78 *
79 * @return integer Id of the page
80 */
81 public function getPageId() {
82 return $this->pageId;
83 }
84
85 /**
86 * Sets the rootline.
87 *
88 * @param array $rootline: The rootline to be used for matching (must have elements)
89 * @return void
90 */
91 public function setRootline(array $rootline) {
92 if (count($rootline)) {
93 $this->rootline = $rootline;
94 }
95 }
96
97 /**
98 * Gets the rootline.
99 *
100 * @return array The rootline to be used for matching
101 */
102 public function getRootline() {
103 return $this->rootline;
104 }
105
106 /**
107 * Sets whether to simulate the behaviour and match all conditions.
108 *
109 * @param boolean $simulateMatchResult: Whether to simulate positive matches
110 * @return void
111 */
112 public function setSimulateMatchResult($simulateMatchResult) {
113 if (is_bool($simulateMatchResult)) {
114 $this->simulateMatchResult = $simulateMatchResult;
115 }
116 }
117
118 /**
119 * Sets whether to simulate the behaviour and match specific conditions.
120 *
121 * @param array $simulateMatchConditions: Conditions to simulate a match for
122 * @return void
123 */
124 public function setSimulateMatchConditions(array $simulateMatchConditions) {
125 $this->simulateMatchConditions = $simulateMatchConditions;
126 }
127
128 /**
129 * Normalizes an expression and removes the first and last square bracket.
130 * + OR normalization: "...]OR[...", "...]||[...", "...][..." --> "...]||[..."
131 * + AND normalization: "...]AND[...", "...]&&[..." --> "...]&&[..."
132 *
133 * @param string $expression: The expression to be normalized (e.g. "[A] && [B] OR [C]")
134 * @return string The normalized expression (e.g. "[A]&&[B]||[C]")
135 */
136 protected function normalizeExpression($expression) {
137 $normalizedExpression = preg_replace(
138 array(
139 '/\]\s*(OR|\|\|)?\s*\[/i',
140 '/\]\s*(AND|&&)\s*\[/i',
141 ),
142 array(
143 ']||[',
144 ']&&[',
145 ),
146 trim($expression)
147 );
148
149 return $normalizedExpression;
150 }
151
152 /**
153 * Matches a TypoScript condition expression.
154 *
155 * @param string $expression: The expression to match
156 * @return boolean Whether the expression matched
157 */
158 public function match($expression) {
159 // Return directly if result should be simulated:
160 if ($this->simulateMatchResult) {
161 return $this->simulateMatchResult;
162 }
163 // Return directly if matching for specific condition is simulated only:
164 if (count($this->simulateMatchConditions)) {
165 return in_array($expression, $this->simulateMatchConditions);
166 }
167 // Sets the current pageId if not defined yet:
168 if (!isset($this->pageId)) {
169 $this->pageId = $this->determinePageId();
170 }
171 // Sets the rootline if not defined yet:
172 if (!isset($this->rootline)) {
173 $this->rootline = $this->determineRootline();
174 }
175
176 $result = FALSE;
177 $normalizedExpression = $this->normalizeExpression($expression);
178
179 // First and last character must be square brackets (e.g. "[A]&&[B]":
180 if (substr($normalizedExpression, 0, 1) === '[' && substr($normalizedExpression, -1) === ']') {
181 $innerExpression = substr($normalizedExpression, 1, -1);
182
183 $orParts = explode(']||[', $innerExpression);
184 foreach ($orParts as $orPart) {
185 $andParts = explode(']&&[', $orPart);
186 foreach ($andParts as $andPart) {
187 $result = $this->evaluateCondition($andPart);
188 // If condition in AND context fails, the whole block is false:
189 if ($result === FALSE) {
190 break;
191 }
192 }
193 // If condition in OR context succeeds, the whole expression is true:
194 if ($result === TRUE) {
195 break;
196 }
197 }
198 }
199
200 return $result;
201 }
202
203 /**
204 * Evaluates a TypoScript condition given as input, eg. "[browser=net][...(other conditions)...]"
205 *
206 * @param string The condition to match against its criterias.
207 * @return mixed Returns true or false based on the evaluation
208 */
209 protected function evaluateConditionCommon($key, $value) {
210 if (t3lib_div::inList('browser,version,system,useragent', strtolower($key))) {
211 $browserInfo = $this->getBrowserInfo(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
212 }
213 $keyParts = t3lib_div::trimExplode('|', $key);
214
215 switch ($keyParts[0]) {
216 case 'browser':
217 $values = t3lib_div::trimExplode(',', $value, TRUE);
218 // take all identified browsers into account, eg chrome deliver
219 // webkit=>532.5, chrome=>4.1, safari=>532.5
220 // so comparing string will be
221 // "webkit532.5 chrome4.1 safari532.5"
222 $all = '';
223 foreach ($browserInfo['all'] as $key => $value) {
224 $all .= $key . $value . ' ';
225 }
226 foreach ($values as $test) {
227 if (stripos($all, $test) !== FALSE) {
228 return TRUE;
229 }
230 }
231 break;
232 case 'version':
233 $values = t3lib_div::trimExplode(',', $value, TRUE);
234 foreach ($values as $test) {
235 if (strcspn($test, '=<>') == 0) {
236 switch (substr($test, 0, 1)) {
237 case '=':
238 if (doubleval(substr($test, 1)) == $browserInfo['version']) {
239 return TRUE;
240 }
241 break;
242 case '<':
243 if (doubleval(substr($test, 1)) > $browserInfo['version']) {
244 return TRUE;
245 }
246 break;
247 case '>':
248 if (doubleval(substr($test, 1)) < $browserInfo['version']) {
249 return TRUE;
250 }
251 break;
252 }
253 } elseif (strpos(' ' . $browserInfo['version'], $test) == 1) {
254 return TRUE;
255 }
256 }
257 break;
258 case 'system':
259 $values = t3lib_div::trimExplode(',', $value, TRUE);
260 // Take all identified systems into account, e.g. mac for iOS, Linux
261 // for android and Windows NT for Windows XP
262 $allSystems .= ' ' . implode(' ', $browserInfo['all_systems']);
263 foreach ($values as $test) {
264 if (stripos($allSystems, $test) !== FALSE) {
265 return TRUE;
266 }
267 }
268 break;
269 case 'device':
270 if (!isset($this->deviceInfo)) {
271 $this->deviceInfo = $this->getDeviceType(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
272 }
273 $values = t3lib_div::trimExplode(',', $value, TRUE);
274 foreach ($values as $test) {
275 if ($this->deviceInfo == $test) {
276 return TRUE;
277 }
278 }
279 break;
280 case 'useragent':
281 $test = trim($value);
282 if (strlen($test)) {
283 return $this->searchStringWildcard($browserInfo['useragent'], $test);
284 }
285 break;
286 case 'language':
287 $values = t3lib_div::trimExplode(',', $value, TRUE);
288 foreach ($values as $test) {
289 if (preg_match('/^\*.+\*$/', $test)) {
290 $allLanguages = preg_split('/[,;]/', t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE'));
291 if (in_array(substr($test, 1, -1), $allLanguages)) {
292 return TRUE;
293 }
294 } elseif (t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE') == $test) {
295 return TRUE;
296 }
297 }
298 break;
299 case 'IP':
300 if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
301 return TRUE;
302 }
303 break;
304 case 'hostname':
305 if (t3lib_div::cmpFQDN(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
306 return TRUE;
307 }
308 break;
309 // hour, minute, dayofweek, dayofmonth, month, year, julianday
310 case 'hour':
311 case 'minute':
312 case 'month':
313 case 'year':
314 case 'dayofweek':
315 case 'dayofmonth':
316 case 'dayofyear':
317 $theEvalTime = $GLOBALS['SIM_EXEC_TIME']; // In order to simulate time properly in templates.
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_div::testInt($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 $prefix = $this->getUserFuncClassPrefix();
410 if ($prefix &&
411 !t3lib_div::isFirstPartOfStr(trim($funcName), $prefix) &&
412 !t3lib_div::isFirstPartOfStr(trim($funcName), 'tx_')
413 ) {
414 $this->log('Match condition: Function "' . $funcName . '" was not prepended with "' . $prefix . '"');
415 return FALSE;
416 }
417 if (function_exists($funcName) && call_user_func($funcName, $funcValue[0])) {
418 return TRUE;
419 }
420 break;
421 }
422
423 return NULL;
424 }
425
426 protected function getVariableCommon(array $vars) {
427 $value = NULL;
428
429 if (count($vars) == 1) {
430 $value = $this->getGlobal($vars[0]);
431 } else {
432 $splitAgain = explode('|', $vars[1], 2);
433 $k = trim($splitAgain[0]);
434
435 if ($k) {
436 switch ((string) trim($vars[0])) {
437 case 'GP':
438 $value = t3lib_div::_GP($k);
439 break;
440 case 'ENV':
441 $value = getenv($k);
442 break;
443 case 'IENV':
444 $value = t3lib_div::getIndpEnv($k);
445 break;
446 // return litteral value:
447 case 'LIT':
448 return trim($vars[1]);
449 break;
450 default:
451 return NULL;
452 }
453 // If array:
454 if (count($splitAgain) > 1) {
455 if (is_array($value) && trim($splitAgain[1])) {
456 $value = $this->getGlobal($splitAgain[1], $value);
457 } else {
458 $value = '';
459 }
460 }
461 }
462 }
463
464 return $value;
465 }
466
467 /**
468 * Evaluates a $leftValue based on an operator: "<", ">", "<=", ">=", "!=" or "="
469 *
470 * @param string $test: The value to compare with on the form [operator][number]. Eg. "< 123"
471 * @param integer $leftValue: The value on the left side
472 * @return boolean If $value is "50" and $test is "< 123" then it will return true.
473 */
474 protected function compareNumber($test, $leftValue) {
475 if (preg_match('/^(!?=+|<=?|>=?)\s*([^\s]*)\s*$/', $test, $matches)) {
476 $operator = $matches[1];
477 $rightValue = $matches[2];
478
479 switch ($operator) {
480 case '>=':
481 return ($leftValue >= doubleval($rightValue));
482 break;
483 case '<=':
484 return ($leftValue <= doubleval($rightValue));
485 break;
486 case '!=':
487 return ($leftValue != doubleval($rightValue));
488 break;
489 case '<':
490 return ($leftValue < doubleval($rightValue));
491 break;
492 case '>':
493 return ($leftValue > doubleval($rightValue));
494 break;
495 default:
496 // nothing valid found except '=', use '='
497 return ($leftValue == trim($rightValue));
498 break;
499 }
500 }
501
502 return FALSE;
503 }
504
505 /**
506 * Matching two strings against each other, supporting a "*" wildcard or (if wrapped in "/") PCRE regular expressions
507 *
508 * @param string The string in which to find $needle.
509 * @param string The string to find in $haystack
510 * @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.
511 */
512 protected function searchStringWildcard($haystack, $needle) {
513 $result = FALSE;
514
515 if ($needle) {
516 if (preg_match('/^\/.+\/$/', $needle)) {
517 // Regular expression, only "//" is allowed as delimiter
518 $regex = $needle;
519 } else {
520 $needle = str_replace(array('*', '?'), array('###MANY###', '###ONE###'), $needle);
521 $regex = '/^' . preg_quote($needle, '/') . '$/';
522 // Replace the marker with .* to match anything (wildcard)
523 $regex = str_replace(array('###MANY###', '###ONE###'), array('.*', '.'), $regex);
524 }
525
526 $result = (boolean) preg_match($regex, (string) $haystack);
527 }
528
529 return $result;
530 }
531
532 /**
533 * Generates an array with abstracted browser information
534 *
535 * @param string $userAgent: The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
536 * @return array Contains keys "browser", "version", "system"
537 */
538 protected function getBrowserInfo($userAgent) {
539 return t3lib_utility_Client::getBrowserInfo($userAgent);
540 }
541
542 /**
543 * Gets a code for a browsing device based on the input useragent string.
544 *
545 * @param string $userAgent: The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
546 * @return string Code for the specific device type
547 */
548 protected function getDeviceType($userAgent) {
549 return t3lib_utility_Client::getDeviceType($userAgent);
550 }
551
552 /**
553 * Return global variable where the input string $var defines array keys separated by "|"
554 * Example: $var = "HTTP_SERVER_VARS | something" will return the value $GLOBALS['HTTP_SERVER_VARS']['something'] value
555 *
556 * @param string Global var key, eg. "HTTP_GET_VAR" or "HTTP_GET_VARS|id" to get the GET parameter "id" back.
557 * @param array Alternative array than $GLOBAL to get variables from.
558 * @return mixed Whatever value. If none, then blank string.
559 */
560 protected function getGlobal($var, $source = NULL) {
561 $vars = explode('|', $var);
562 $c = count($vars);
563 $k = trim($vars[0]);
564 $theVar = isset($source) ? $source[$k] : $GLOBALS[$k];
565
566 for ($a = 1; $a < $c; $a++) {
567 if (!isset($theVar)) {
568 break;
569 }
570
571 $key = trim($vars[$a]);
572 if (is_object($theVar)) {
573 $theVar = $theVar->$key;
574 } elseif (is_array($theVar)) {
575 $theVar = $theVar[$key];
576 } else {
577 return '';
578 }
579 }
580
581 if (!is_array($theVar) && !is_object($theVar)) {
582 return $theVar;
583 } else {
584 return '';
585 }
586 }
587
588
589 /**
590 * Evaluates a TypoScript condition given as input, eg. "[browser=net][...(other conditions)...]"
591 *
592 * @param string $string: The condition to match against its criterias.
593 * @return boolean Whether the condition matched
594 * @see t3lib_tsparser::parse()
595 */
596 abstract protected function evaluateCondition($string);
597
598 /**
599 * Gets the value of a variable.
600 *
601 * Examples of names:
602 * + TSFE:id
603 * + GP:firstLevel|secondLevel
604 * + _GET|firstLevel|secondLevel
605 * + LIT:someLiteralValue
606 *
607 * @param string $name: The name of the variable to fetch the value from
608 * @return mixed The value of the given variable (string) or NULL if variable did not exist
609 */
610 abstract protected function getVariable($name);
611
612 /**
613 * Gets the usergroup list of the current user.
614 *
615 * @return string The usergroup list of the current user
616 */
617 abstract protected function getGroupList();
618
619 /**
620 * Determines the current page Id.
621 *
622 * @return integer The current page Id
623 */
624 abstract protected function determinePageId();
625
626 /**
627 * Gets the properties for the current page.
628 *
629 * @return array The properties for the current page.
630 */
631 abstract protected function getPage();
632
633 /**
634 * Determines the rootline for the current page.
635 *
636 * @return array The rootline for the current page.
637 */
638 abstract protected function determineRootline();
639
640 /**
641 * Gets prefix for user functions (normally 'user_').
642 *
643 * @return string The prefix for user functions (normally 'user_').
644 */
645 abstract protected function getUserFuncClassPrefix();
646
647 /**
648 * Gets the id of the current user.
649 *
650 * @return integer The id of the current user
651 */
652 abstract protected function getUserId();
653
654 /**
655 * Determines if a user is logged in.
656 *
657 * @return boolean Determines if a user is logged in
658 */
659 abstract protected function isUserLoggedIn();
660
661 /**
662 * Sets a log message.
663 *
664 * @param string $message: The log message to set/write
665 * @return void
666 */
667 abstract protected function log($message);
668 }
669
670 ?>