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