Added feature #5613: Enable/integrate conditions in Page TSconfig
[Packages/TYPO3.CMS.git] / t3lib / matchcondition / class.t3lib_matchcondition_abstract.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 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
214 switch ($key) {
215 case 'browser':
216 $values = t3lib_div::trimExplode(',', $value, true);
217 foreach ($values as $test) {
218 if (strpos($browserInfo['browser'] . $browserInfo['version'], $test) !== false) {
219 return true;
220 }
221 }
222 break;
223 case 'version':
224 $values = t3lib_div::trimExplode(',', $value, true);
225 foreach ($values as $test) {
226 if (strcspn($test, '=<>') == 0) {
227 switch (substr($test, 0, 1)) {
228 case '=':
229 if (doubleval(substr($test, 1)) == $browserInfo['version']) {
230 return true;
231 }
232 break;
233 case '<':
234 if (doubleval(substr($test, 1)) > $browserInfo['version']) {
235 return true;
236 }
237 break;
238 case '>':
239 if (doubleval(substr($test, 1)) < $browserInfo['version']) {
240 return true;
241 }
242 break;
243 }
244 } else {
245 if (strpos(' ' . $browserInfo['version'], $test) == 1) {
246 return true;
247 }
248 }
249 }
250 break;
251 case 'system':
252 $values = t3lib_div::trimExplode(',', $value, true);
253 foreach ($values as $test) {
254 if (strpos(' ' . $browserInfo['system'], $test) == 1) {
255 return true;
256 }
257 }
258 break;
259 case 'device':
260 if (!isset($this->deviceInfo)) {
261 $this->deviceInfo = $this->getDeviceType(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
262 }
263 $values = t3lib_div::trimExplode(',', $value, true);
264 foreach ($values as $test) {
265 if ($this->deviceInfo == $test) {
266 return true;
267 }
268 }
269 break;
270 case 'useragent':
271 $test = trim($value);
272 if (strlen($test)) {
273 return $this->searchStringWildcard($browserInfo['useragent'], $test);
274 }
275 break;
276 case 'language':
277 $values = t3lib_div::trimExplode(',', $value, true);
278 foreach ($values as $test) {
279 if (preg_match('/^\*.+\*$/', $test)) {
280 $allLanguages = preg_split('/[,;]/', t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE'));
281 if (in_array(substr($test, 1, -1), $allLanguages)) {
282 return true;
283 }
284 } else if (t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE') == $test) {
285 return true;
286 }
287 }
288 break;
289 case 'IP':
290 if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
291 return true;
292 }
293 break;
294 case 'hostname':
295 if (t3lib_div::cmpFQDN(t3lib_div::getIndpEnv('REMOTE_ADDR'), $value)) {
296 return true;
297 }
298 break;
299 // hour, minute, dayofweek, dayofmonth, month, year, julianday
300 case 'hour':
301 case 'minute':
302 case 'month':
303 case 'year':
304 case 'dayofweek':
305 case 'dayofmonth':
306 case 'dayofyear':
307 $theEvalTime = $GLOBALS['SIM_EXEC_TIME']; // In order to simulate time properly in templates.
308 switch($key) {
309 case 'hour': $theTestValue = date('H', $theEvalTime); break;
310 case 'minute': $theTestValue = date('i', $theEvalTime); break;
311 case 'month': $theTestValue = date('m', $theEvalTime); break;
312 case 'year': $theTestValue = date('Y', $theEvalTime); break;
313 case 'dayofweek': $theTestValue = date('w', $theEvalTime); break;
314 case 'dayofmonth': $theTestValue = date('d', $theEvalTime); break;
315 case 'dayofyear': $theTestValue = date('z', $theEvalTime); break;
316 }
317 $theTestValue = intval($theTestValue);
318 // comp
319 $values = t3lib_div::trimExplode(',', $value, true);
320 foreach ($values as $test) {
321 if (t3lib_div::testInt($test)) {
322 $test = '=' . $test;
323 }
324 if ($this->compareNumber($test, $theTestValue)) {
325 return true;
326 }
327 }
328 break;
329 case 'compatVersion':
330 return t3lib_div::compat_version($value);
331 break;
332 case 'loginUser':
333 if ($this->isUserLoggedIn()) {
334 $values = t3lib_div::trimExplode(',', $value, true);
335 foreach ($values as $test) {
336 if ($test == '*' || !strcmp($this->getUserId(), $test)) {
337 return true;
338 }
339 }
340 }
341 break;
342 case 'globalVar':
343 $values = t3lib_div::trimExplode(',', $value, true);
344 foreach ($values as $test) {
345 $point = strcspn($test, '!=<>');
346 $theVarName = substr($test, 0, $point);
347 $nv = $this->getVariable(trim($theVarName));
348 $testValue = substr($test, $point);
349
350 if ($this->compareNumber($testValue, $nv)) {
351 return true;
352 }
353 }
354 break;
355 case 'globalString':
356 $values = t3lib_div::trimExplode(',', $value, true);
357 foreach ($values as $test) {
358 $point = strcspn($test, '=');
359 $theVarName = substr($test, 0, $point);
360 $nv = $this->getVariable(trim($theVarName));
361 $testValue = substr($test, $point+1);
362
363 if ($this->searchStringWildcard($nv, trim($testValue))) {
364 return true;
365 }
366 }
367 break;
368 case 'userFunc':
369 $values = preg_split('/\(|\)/', $value);
370 $funcName = trim($values[0]);
371 $funcValue = t3lib_div::trimExplode(',', $values[1]);
372 $prefix = $this->getUserFuncClassPrefix();
373 if ($prefix &&
374 !t3lib_div::isFirstPartOfStr(trim($funcName), $prefix) &&
375 !t3lib_div::isFirstPartOfStr(trim($funcName),'tx_')
376 ) {
377 $this->log('Match condition: Function "' . $funcName . '" was not prepended with "' . $prefix.'"');
378 return false;
379 }
380 if (function_exists($funcName) && call_user_func($funcName, $funcValue[0])) {
381 return true;
382 }
383 break;
384 }
385
386 return NULL;
387 }
388
389 protected function getVariableCommon(array $vars) {
390 $value = NULL;
391
392 if (count($vars) == 1) {
393 $value = $this->getGlobal($vars[0]);
394 } else {
395 $splitAgain = explode('|',$vars[1], 2);
396 $k = trim($splitAgain[0]);
397
398 if ($k) {
399 switch((string)trim($vars[0])) {
400 case 'GP':
401 $value = t3lib_div::_GP($k);
402 break;
403 case 'ENV':
404 $value = getenv($k);
405 break;
406 case 'IENV':
407 $value = t3lib_div::getIndpEnv($k);
408 break;
409 // return litteral value:
410 case 'LIT':
411 return trim($vars[1]);
412 break;
413 default:
414 return NULL;
415 }
416 // If array:
417 if (count($splitAgain) > 1) {
418 if (is_array($value) && trim($splitAgain[1])) {
419 $value = $this->getGlobal($splitAgain[1], $value);
420 } else {
421 $value = '';
422 }
423 }
424 }
425 }
426
427 return $value;
428 }
429
430 /**
431 * Evaluates a $leftValue based on an operator: "<", ">", "<=", ">=", "!=" or "="
432 *
433 * @param string $test: The value to compare with on the form [operator][number]. Eg. "< 123"
434 * @param integer $leftValue: The value on the left side
435 * @return boolean If $value is "50" and $test is "< 123" then it will return true.
436 */
437 protected function compareNumber($test, $leftValue) {
438 if (preg_match('/^(!?=+|<=?|>=?)\s*([^\s]*)\s*$/', $test, $matches)) {
439 $operator = $matches[1];
440 $rightValue = $matches[2];
441
442 switch ($operator) {
443 case '>=':
444 return ($leftValue >= doubleval($rightValue));
445 break;
446 case '<=':
447 return ($leftValue <= doubleval($rightValue));
448 break;
449 case '!=':
450 return ($leftValue != doubleval($rightValue));
451 break;
452 case '<':
453 return ($leftValue < doubleval($rightValue));
454 break;
455 case '>':
456 return ($leftValue > doubleval($rightValue));
457 break;
458 default:
459 // nothing valid found except '=', use '='
460 return ($leftValue == trim($rightValue));
461 break;
462 }
463 }
464
465 return false;
466 }
467
468 /**
469 * Matching two strings against each other, supporting a "*" wildcard or (if wrapped in "/") PCRE regular expressions
470 *
471 * @param string The string in which to find $needle.
472 * @param string The string to find in $haystack
473 * @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.
474 */
475 protected function searchStringWildcard($haystack, $needle) {
476 $result = false;
477
478 if ($needle) {
479 if (preg_match('/^\/.+\/$/', $needle)) {
480 // Regular expression, only "//" is allowed as delimiter
481 $regex = $needle;
482 } else {
483 $needle = str_replace(array('*', '?'), array('###MANY###', '###ONE###'), $needle);
484 $regex = '/^' . preg_quote($needle, '/') . '$/';
485 // Replace the marker with .* to match anything (wildcard)
486 $regex = str_replace(array('###MANY###', '###ONE###'), array('.*' , '.'), $regex);
487 }
488
489 $result = (boolean)preg_match($regex, (string)$haystack);
490 }
491
492 return $result;
493 }
494
495 /**
496 * Generates an array with abstracted browser information
497 *
498 * @param string $userAgent: The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
499 * @return array Contains keys "browser", "version", "system"
500 */
501 protected function getBrowserInfo($userAgent) {
502 return t3lib_utility_Client::getBrowserInfo($userAgent);
503 }
504
505 /**
506 * Gets a code for a browsing device based on the input useragent string.
507 *
508 * @param string $userAgent: The useragent string, t3lib_div::getIndpEnv('HTTP_USER_AGENT')
509 * @return string Code for the specific device type
510 */
511 protected function getDeviceType($userAgent) {
512 return t3lib_utility_Client::getDeviceType($userAgent);
513 }
514
515 /**
516 * Return global variable where the input string $var defines array keys separated by "|"
517 * Example: $var = "HTTP_SERVER_VARS | something" will return the value $GLOBALS['HTTP_SERVER_VARS']['something'] value
518 *
519 * @param string Global var key, eg. "HTTP_GET_VAR" or "HTTP_GET_VARS|id" to get the GET parameter "id" back.
520 * @param array Alternative array than $GLOBAL to get variables from.
521 * @return mixed Whatever value. If none, then blank string.
522 */
523 protected function getGlobal($var, $source=NULL) {
524 $vars = explode('|', $var);
525 $c = count($vars);
526 $k = trim($vars[0]);
527 $theVar = isset($source) ? $source[$k] : $GLOBALS[$k];
528
529 for ($a=1;$a<$c;$a++) {
530 if (!isset($theVar)) { break; }
531
532 $key = trim($vars[$a]);
533 if (is_object($theVar)) {
534 $theVar = $theVar->$key;
535 } elseif (is_array($theVar)) {
536 $theVar = $theVar[$key];
537 } else {
538 return '';
539 }
540 }
541
542 if (!is_array($theVar) && !is_object($theVar)) {
543 return $theVar;
544 } else {
545 return '';
546 }
547 }
548
549
550 /**
551 * Evaluates a TypoScript condition given as input, eg. "[browser=net][...(other conditions)...]"
552 *
553 * @param string $string: The condition to match against its criterias.
554 * @return boolean Whether the condition matched
555 * @see t3lib_tsparser::parse()
556 */
557 abstract protected function evaluateCondition($string);
558
559 /**
560 * Gets the value of a variable.
561 *
562 * Examples of names:
563 * + TSFE:id
564 * + GP:firstLevel|secondLevel
565 * + _GET|firstLevel|secondLevel
566 * + LIT:someLiteralValue
567 *
568 * @param string $name: The name of the variable to fetch the value from
569 * @return mixed The value of the given variable (string) or NULL if variable did not exist
570 */
571 abstract protected function getVariable($name);
572
573 /**
574 * Gets the usergroup list of the current user.
575 *
576 * @return string The usergroup list of the current user
577 */
578 abstract protected function getGroupList();
579
580 /**
581 * Determines the current page Id.
582 *
583 * @return integer The current page Id
584 */
585 abstract protected function determinePageId();
586
587 /**
588 * Determines the rootline for the current page.
589 *
590 * @return array The rootline for the current page.
591 */
592 abstract protected function determineRootline();
593
594 /**
595 * Gets prefix for user functions (normally 'user_').
596 *
597 * @return string The prefix for user functions (normally 'user_').
598 */
599 abstract protected function getUserFuncClassPrefix();
600
601 /**
602 * Gets the id of the current user.
603 *
604 * @return integer The id of the current user
605 */
606 abstract protected function getUserId();
607
608 /**
609 * Determines if a user is logged in.
610 *
611 * @return boolean Determines if a user is logged in
612 */
613 abstract protected function isUserLoggedIn();
614
615 /**
616 * Sets a log message.
617 *
618 * @param string $message: The log message to set/write
619 * @return void
620 */
621 abstract protected function log($message);
622 }
623
624 ?>