+ */
+ public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
+ $lookupFile = explode('?', $file);
+ $path = self::resolveBackPath(self::dirname(PATH_thisScript) . '/' . $lookupFile[0]);
+ if (TYPO3_MODE == 'FE') {
+ $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
+ if ($mode === 'embed') {
+ $mode = TRUE;
+ } else {
+ if ($mode === 'querystring') {
+ $mode = FALSE;
+ } else {
+ $doNothing = TRUE;
+ }
+ }
+ } else {
+ $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
+ }
+ if (!file_exists($path) || $doNothing) {
+ // File not found, return filename unaltered
+ $fullName = $file;
+ } else {
+ if (!$mode || $forceQueryString) {
+ // If use of .htaccess rule is not configured,
+ // we use the default query-string method
+ if ($lookupFile[1]) {
+ $separator = '&';
+ } else {
+ $separator = '?';
+ }
+ $fullName = $file . $separator . filemtime($path);
+ } else {
+ // Change the filename
+ $name = explode('.', $lookupFile[0]);
+ $extension = array_pop($name);
+ array_push($name, filemtime($path), $extension);
+ $fullName = implode('.', $name);
+ // append potential query string
+ $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
+ }
+ }
-
-
+ return $fullName;
+ }
/*************************
@@ -3315,6 +3733,9 @@ final class t3lib_div {
*
*************************/
+ /* Deprecated since 4.5, use t3lib_utility_Debug */
+
+
/**
* Returns a string with a list of ascii-values for the first $characters characters in $string
* Usage: 0
@@ -3322,13 +3743,11 @@ final class t3lib_div {
* @param string String to show ASCII value for
* @param integer Number of characters to show
* @return string The string with ASCII values in separated by a space char.
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::ordinalValue instead
*/
- public static function debug_ordvalue($string,$characters=100) {
- if(strlen($string) < $characters) $characters = strlen($string);
- for ($i=0; $i<$characters; $i++) {
- $valuestring.=' '.ord(substr($string,$i,1));
- }
- return trim($valuestring);
+ public static function debug_ordvalue($string, $characters = 100) {
+ self::logDeprecatedFunction();
+ return t3lib_utility_Debug::ordinalValue($string, $characters);
}
/**
@@ -3339,47 +3758,11 @@ final class t3lib_div {
*
* @param mixed Array to view
* @return string HTML output
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::viewArray instead
*/
- public static function view_array($array_in) {
- if (is_array($array_in)) {
- $result='
- ';
- if (count($array_in) == 0) {
- $result.= 'EMPTY! |
';
- } else {
- foreach ($array_in as $key => $val) {
- $result.= '
- '.htmlspecialchars((string)$key).' |
- ';
- if (is_array($val)) {
- $result.=t3lib_div::view_array($val);
- } elseif (is_object($val)) {
- $string = get_class($val);
- if (method_exists($val, '__toString')) {
- $string .= ': '.(string)$val;
- }
- $result .= ''.nl2br(htmlspecialchars($string)).' ';
- } else {
- if (gettype($val) == 'object') {
- $string = 'Unknown object';
- } else {
- $string = (string)$val;
- }
- $result.= ''.nl2br(htmlspecialchars($string)).' ';
- }
- $result.= ' |
-
';
- }
- }
- $result.= '
';
- } else {
- $result = '
-
- '.nl2br(htmlspecialchars((string)$array_in)).'
|
-
-
'; // Output it as a string.
- }
- return $result;
+ public static function view_array($array_in) {
+ self::logDeprecatedFunction();
+ return t3lib_utility_Debug::viewArray($array_in);
}
/**
@@ -3389,9 +3772,11 @@ final class t3lib_div {
* @param mixed Array to print visually (in a table).
* @return void
* @see view_array()
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::printArray instead
*/
- public static function print_array($array_in) {
- echo t3lib_div::view_array($array_in);
+ public static function print_array($array_in) {
+ self::logDeprecatedFunction();
+ t3lib_utility_Debug::printArray($array_in);
}
/**
@@ -3402,56 +3787,25 @@ final class t3lib_div {
* Usage: 8
*
* @param mixed Variable to print
- * @param mixed If the parameter is a string it will be used as header. Otherwise number of break tags to apply after (positive integer) or before (negative integer) the output.
+ * @param string The header.
+ * @param string Group for the debug console
* @return void
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debug instead
*/
- public static function debug($var='',$brOrHeader=0) {
- // buffer the output of debug if no buffering started before
- if (ob_get_level()==0) {
- ob_start();
- }
-
- if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
- echo ''.htmlspecialchars((string)$brOrHeader).' |
';
- } elseif ($brOrHeader<0) {
- for($a=0;$a';}
- }
-
- if (is_array($var)) {
- t3lib_div::print_array($var);
- } elseif (is_object($var)) {
- echo '|Object:';
- print_r($var);
- echo ' |';
- } elseif ((string)$var!='') {
- echo '|'.htmlspecialchars((string)$var).'|';
- } else {
- echo '| debug |';
- }
-
- if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
- echo ' |
';
- } elseif ($brOrHeader>0) {
- for($a=0;$a';}
- }
+ public static function debug($var = '', $header = '', $group = 'Debug') {
+ self::logDeprecatedFunction();
+ t3lib_utility_Debug::debug($var, $header, $group);
}
/**
* Displays the "path" of the function call stack in a string, using debug_backtrace
*
* @return string
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugTrail instead
*/
- public static function debug_trail() {
- $trail = debug_backtrace();
- $trail = array_reverse($trail);
- array_pop($trail);
-
- $path = array();
- foreach($trail as $dat) {
- $path[] = $dat['class'].$dat['type'].$dat['function'].'#'.$dat['line'];
- }
-
- return implode(' // ',$path);
+ public static function debug_trail() {
+ self::logDeprecatedFunction();
+ return t3lib_utility_Debug::debugTrail();
}
/**
@@ -3461,75 +3815,14 @@ final class t3lib_div {
* @param string Table header
* @param boolean If TRUE, will return content instead of echo'ing out.
* @return void Outputs to browser.
+ * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugRows instead
*/
- public static function debugRows($rows,$header='',$returnHTML=FALSE) {
- if (is_array($rows)) {
- reset($rows);
- $firstEl = current($rows);
- if (is_array($firstEl)) {
- $headerColumns = array_keys($firstEl);
- $tRows = array();
-
- // Header:
- $tRows[] = ''.htmlspecialchars($header).' |
';
- $tCells = array();
- foreach($headerColumns as $key) {
- $tCells[] = '
- '.htmlspecialchars($key).' | ';
- }
- $tRows[] = '
- '.implode('',$tCells).'
-
';
-
- // Rows:
- foreach($rows as $singleRow) {
- $tCells = array();
- foreach($headerColumns as $key) {
- $tCells[] = '
- '.(is_array($singleRow[$key]) ? t3lib_div::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).' | ';
- }
- $tRows[] = '
- '.implode('',$tCells).'
-
';
- }
-
- $table = '
- ';
- if ($returnHTML) return $table; else echo $table;
- } else debug('Empty array of rows',$header);
- } else {
- debug('No array of rows',$header);
- }
+ public static function debugRows($rows, $header = '', $returnHTML = FALSE) {
+ self::logDeprecatedFunction();
+ return t3lib_utility_Debug::debugRows($rows, $header, $returnHTML);
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*************************
*
* SYSTEM INFORMATION
@@ -3542,10 +3835,10 @@ final class t3lib_div {
*
* @return string
*/
- public static function getThisUrl() {
- $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
- $dir=t3lib_div::dirname($p['path']).'/'; // Strip file
- $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
+ public static function getThisUrl() {
+ $p = parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
+ $dir = self::dirname($p['path']) . '/'; // Strip file
+ $url = str_replace('//', '/', $p['host'] . ($p['port'] ? ':' . $p['port'] : '') . $dir);
return $url;
}
@@ -3559,8 +3852,8 @@ final class t3lib_div {
* @return string
*/
public static function linkThisScript(array $getParams = array()) {
- $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
- $params = t3lib_div::_GET();
+ $parts = self::getIndpEnv('SCRIPT_NAME');
+ $params = self::_GET();
foreach ($getParams as $key => $value) {
if ($value !== '') {
@@ -3570,7 +3863,7 @@ final class t3lib_div {
}
}
- $pString = t3lib_div::implodeArrayForUrl('', $params);
+ $pString = self::implodeArrayForUrl('', $params);
return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
}
@@ -3584,17 +3877,17 @@ final class t3lib_div {
* @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
* @return string Output URL with added getParams.
*/
- public static function linkThisUrl($url,array $getParams=array()) {
+ public static function linkThisUrl($url, array $getParams = array()) {
$parts = parse_url($url);
$getP = array();
- if ($parts['query']) {
- parse_str($parts['query'],$getP);
+ if ($parts['query']) {
+ parse_str($parts['query'], $getP);
}
- $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
- $uP = explode('?',$url);
+ $getP = self::array_merge_recursive_overrule($getP, $getParams);
+ $uP = explode('?', $url);
- $params = t3lib_div::implodeArrayForUrl('',$getP);
- $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
+ $params = self::implodeArrayForUrl('', $getP);
+ $outurl = $uP[0] . ($params ? '?' . substr($params, 1) : '');
return $outurl;
}
@@ -3607,7 +3900,7 @@ final class t3lib_div {
* @param string Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
* @return string Value based on the input key, independent of server/os environment.
*/
- public static function getIndpEnv($getEnvName) {
+ public static function getIndpEnv($getEnvName) {
/*
Conventions:
output from parse_url():
@@ -3671,105 +3964,113 @@ final class t3lib_div {
*/
-# if ($getEnvName=='HTTP_REFERER') return '';
+ # if ($getEnvName=='HTTP_REFERER') return '';
$retVal = '';
- switch ((string)$getEnvName) {
+ switch ((string) $getEnvName) {
case 'SCRIPT_NAME':
- $retVal = (PHP_SAPI=='cgi'||PHP_SAPI=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
+ $retVal = (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'cgi-fcgi') &&
+ ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) ?
+ ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) :
+ ($_SERVER['ORIG_SCRIPT_NAME'] ? $_SERVER['ORIG_SCRIPT_NAME'] : $_SERVER['SCRIPT_NAME']);
// add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
- if (t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
- if (t3lib_div::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
- $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
+ if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
+ if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
+ $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
} elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
- $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
+ $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
}
}
- break;
+ break;
case 'SCRIPT_FILENAME':
- $retVal = str_replace('//','/', str_replace('\\','/', (PHP_SAPI=='cgi'||PHP_SAPI=='isapi' ||PHP_SAPI=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])? ($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
- break;
+ $retVal = str_replace('//', '/', str_replace('\\', '/',
+ (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
+ ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
+ ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
+ ($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
+
+ break;
case 'REQUEST_URI':
// Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
- if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) { // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
- list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
+ if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) { // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
+ list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
$retVal = $GLOBALS[$v][$n];
- } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
- $retVal = '/'.ltrim(t3lib_div::getIndpEnv('SCRIPT_NAME'), '/').
- ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
+ } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
+ $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') .
+ ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
} else {
$retVal = $_SERVER['REQUEST_URI'];
}
// add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
- if (t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
- if (t3lib_div::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
- $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
+ if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
+ if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
+ $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
} elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
- $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
+ $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
}
}
- break;
+ break;
case 'PATH_INFO':
// $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
// Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
// IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'PHP_SAPI=='cgi'' might be a better check. Right now strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) will always return false for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO because of PHP_SAPI=='cgi' (see above)
-// if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
- if (PHP_SAPI!='cgi' && PHP_SAPI!='cgi-fcgi') {
+ // if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
+ if (PHP_SAPI != 'cgi' && PHP_SAPI != 'cgi-fcgi' && PHP_SAPI != 'fpm-fcgi') {
$retVal = $_SERVER['PATH_INFO'];
}
- break;
+ break;
case 'TYPO3_REV_PROXY':
- $retVal = t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
- break;
+ $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
+ break;
case 'REMOTE_ADDR':
$retVal = $_SERVER['REMOTE_ADDR'];
- if (t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
- $ip = t3lib_div::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
+ if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
+ $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
// choose which IP in list to use
if (count($ip)) {
switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
case 'last':
$ip = array_pop($ip);
- break;
+ break;
case 'first':
$ip = array_shift($ip);
- break;
+ break;
case 'none':
default:
$ip = '';
- break;
+ break;
}
}
- if (t3lib_div::validIP($ip)) {
+ if (self::validIP($ip)) {
$retVal = $ip;
}
}
- break;
+ break;
case 'HTTP_HOST':
$retVal = $_SERVER['HTTP_HOST'];
- if (t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
- $host = t3lib_div::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
+ if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
+ $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
// choose which host in list to use
if (count($host)) {
switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
case 'last':
$host = array_pop($host);
- break;
+ break;
case 'first':
$host = array_shift($host);
- break;
+ break;
case 'none':
default:
$host = '';
- break;
+ break;
}
}
- if ($host) {
+ if ($host) {
$retVal = $host;
}
}
- break;
+ break;
// These are let through without modification
case 'HTTP_REFERER':
case 'HTTP_USER_AGENT':
@@ -3778,74 +4079,84 @@ final class t3lib_div {
case 'REMOTE_HOST':
case 'QUERY_STRING':
$retVal = $_SERVER[$getEnvName];
- break;
+ break;
case 'TYPO3_DOCUMENT_ROOT':
- // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
- // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
- $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
- $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
- $SFN_A = explode('/',strrev($SFN));
+ // Get the web root (it is not the root of the TYPO3 installation)
+ // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
+ // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
+ // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
+ $SFN = self::getIndpEnv('SCRIPT_FILENAME');
+ $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
+ $SFN_A = explode('/', strrev($SFN));
$acc = array();
foreach ($SN_A as $kk => $vv) {
- if (!strcmp($SFN_A[$kk],$vv)) {
+ if (!strcmp($SFN_A[$kk], $vv)) {
$acc[] = $vv;
- } else break;
+ } else {
+ break;
+ }
+ }
+ $commonEnd = strrev(implode('/', $acc));
+ if (strcmp($commonEnd, '')) {
+ $DR = substr($SFN, 0, -(strlen($commonEnd) + 1));
}
- $commonEnd=strrev(implode('/',$acc));
- if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
$retVal = $DR;
- break;
+ break;
case 'TYPO3_HOST_ONLY':
- $p = explode(':',t3lib_div::getIndpEnv('HTTP_HOST'));
- $retVal = $p[0];
- break;
+ $httpHost = self::getIndpEnv('HTTP_HOST');
+ $httpHostBracketPosition = strpos($httpHost, ']');
+ $retVal = ($httpHostBracketPosition !== FALSE) ? substr($httpHost, 0, ($httpHostBracketPosition + 1)) : array_shift(explode(':', $httpHost));
+ break;
case 'TYPO3_PORT':
- $p = explode(':',t3lib_div::getIndpEnv('HTTP_HOST'));
- $retVal = $p[1];
- break;
+ $httpHost = self::getIndpEnv('HTTP_HOST');
+ $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
+ $retVal = (strlen($httpHost) > strlen($httpHostOnly)) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
+ break;
case 'TYPO3_REQUEST_HOST':
- $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
- t3lib_div::getIndpEnv('HTTP_HOST');
- break;
+ $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') .
+ self::getIndpEnv('HTTP_HOST');
+ break;
case 'TYPO3_REQUEST_URL':
- $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
- break;
+ $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
+ break;
case 'TYPO3_REQUEST_SCRIPT':
- $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
- break;
+ $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
+ break;
case 'TYPO3_REQUEST_DIR':
- $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
- break;
+ $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
+ break;
case 'TYPO3_SITE_URL':
- if (defined('PATH_thisScript') && defined('PATH_site')) {
- $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
- $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
- $siteUrl = substr($url,0,-strlen($lPath));
- if (substr($siteUrl,-1)!='/') $siteUrl.='/';
+ if (defined('PATH_thisScript') && defined('PATH_site')) {
+ $lPath = substr(dirname(PATH_thisScript), strlen(PATH_site)) . '/';
+ $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
+ $siteUrl = substr($url, 0, -strlen($lPath));
+ if (substr($siteUrl, -1) != '/') {
+ $siteUrl .= '/';
+ }
$retVal = $siteUrl;
}
- break;
+ break;
case 'TYPO3_SITE_PATH':
- $retVal = substr(t3lib_div::getIndpEnv('TYPO3_SITE_URL'), strlen(t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST')));
- break;
+ $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
+ break;
case 'TYPO3_SITE_SCRIPT':
- $retVal = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
- break;
+ $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
+ break;
case 'TYPO3_SSL':
$proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
if ($proxySSL == '*') {
$proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
}
- if (t3lib_div::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
- $retVal = true;
+ if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
+ $retVal = TRUE;
} else {
- $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? true : false; // see http://bugs.typo3.org/view.php?id=3909
+ $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? TRUE : FALSE; // see http://bugs.typo3.org/view.php?id=3909
}
- break;
+ break;
case '_ARRAY':
$out = array();
// Here, list ALL possible keys to this function for debug display.
- $envTestVars = t3lib_div::trimExplode(',','
+ $envTestVars = self::trimExplode(',', '
HTTP_HOST,
TYPO3_HOST_ONLY,
TYPO3_PORT,
@@ -3867,13 +4178,13 @@ final class t3lib_div {
REMOTE_ADDR,
REMOTE_HOST,
HTTP_USER_AGENT,
- HTTP_ACCEPT_LANGUAGE',1);
+ HTTP_ACCEPT_LANGUAGE', 1);
foreach ($envTestVars as $v) {
- $out[$v]=t3lib_div::getIndpEnv($v);
+ $out[$v] = self::getIndpEnv($v);
}
reset($out);
$retVal = $out;
- break;
+ break;
}
return $retVal;
}
@@ -3884,7 +4195,7 @@ final class t3lib_div {
* @return integer The unixtime as milliseconds
*/
public static function milliseconds() {
- return round(microtime(true) * 1000);
+ return round(microtime(TRUE) * 1000);
}
/**
@@ -3894,55 +4205,63 @@ final class t3lib_div {
* @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
* @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
*/
- public static function clientInfo($useragent='') {
- if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
+ public static function clientInfo($useragent = '') {
+ if (!$useragent) {
+ $useragent = self::getIndpEnv('HTTP_USER_AGENT');
+ }
- $bInfo=array();
+ $bInfo = array();
// Which browser?
- if (strpos($useragent,'Konqueror') !== false) {
- $bInfo['BROWSER']= 'konqu';
- } elseif (strpos($useragent,'Opera') !== false) {
- $bInfo['BROWSER']= 'opera';
- } elseif (strpos($useragent, 'MSIE') !== false) {
- $bInfo['BROWSER']= 'msie';
- } elseif (strpos($useragent, 'Mozilla') !== false) {
- $bInfo['BROWSER']='net';
- } elseif (strpos($useragent, 'Flash') !== false) {
+ if (strpos($useragent, 'Konqueror') !== FALSE) {
+ $bInfo['BROWSER'] = 'konqu';
+ } elseif (strpos($useragent, 'Opera') !== FALSE) {
+ $bInfo['BROWSER'] = 'opera';
+ } elseif (strpos($useragent, 'MSIE') !== FALSE) {
+ $bInfo['BROWSER'] = 'msie';
+ } elseif (strpos($useragent, 'Mozilla') !== FALSE) {
+ $bInfo['BROWSER'] = 'net';
+ } elseif (strpos($useragent, 'Flash') !== FALSE) {
$bInfo['BROWSER'] = 'flash';
}
- if ($bInfo['BROWSER']) {
+ if ($bInfo['BROWSER']) {
// Browser version
- switch($bInfo['BROWSER']) {
+ switch ($bInfo['BROWSER']) {
case 'net':
- $bInfo['VERSION']= doubleval(substr($useragent,8));
- if (strpos($useragent,'Netscape6/') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10)); } // Will we ever know if this was a typo or intention...?! :-(
- if (strpos($useragent,'Netscape/6') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10)); }
- if (strpos($useragent,'Netscape/7') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/7'),9)); }
- break;
+ $bInfo['VERSION'] = doubleval(substr($useragent, 8));
+ if (strpos($useragent, 'Netscape6/') !== FALSE) {
+ $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape6/'), 10));
+ } // Will we ever know if this was a typo or intention...?! :-(
+ if (strpos($useragent, 'Netscape/6') !== FALSE) {
+ $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/6'), 10));
+ }
+ if (strpos($useragent, 'Netscape/7') !== FALSE) {
+ $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/7'), 9));
+ }
+ break;
case 'msie':
- $tmp = strstr($useragent,'MSIE');
- $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,4)));
- break;
+ $tmp = strstr($useragent, 'MSIE');
+ $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 4)));
+ break;
case 'opera':
- $tmp = strstr($useragent,'Opera');
- $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,5)));
- break;
+ $tmp = strstr($useragent, 'Opera');
+ $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 5)));
+ break;
case 'konqu':
- $tmp = strstr($useragent,'Konqueror/');
- $bInfo['VERSION'] = doubleval(substr($tmp,10));
- break;
+ $tmp = strstr($useragent, 'Konqueror/');
+ $bInfo['VERSION'] = doubleval(substr($tmp, 10));
+ break;
}
- // Client system
- if (strpos($useragent,'Win') !== false) {
+ // Client system
+ if (strpos($useragent, 'Win') !== FALSE) {
$bInfo['SYSTEM'] = 'win';
- } elseif (strpos($useragent,'Mac') !== false) {
+ } elseif (strpos($useragent, 'Mac') !== FALSE) {
$bInfo['SYSTEM'] = 'mac';
- } elseif (strpos($useragent,'Linux') !== false || strpos($useragent,'X11') !== false || strpos($useragent,'SGI') !== false || strpos($useragent,' SunOS ') !== false || strpos($useragent,' HP-UX ') !== false) {
+ } elseif (strpos($useragent, 'Linux') !== FALSE || strpos($useragent, 'X11') !== FALSE || strpos($useragent, 'SGI') !== FALSE || strpos($useragent, ' SunOS ') !== FALSE || strpos($useragent, ' HP-UX ') !== FALSE) {
$bInfo['SYSTEM'] = 'unix';
}
}
- // Is true if the browser supports css to format forms, especially the width
- $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net' && $bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
+ // Is true if the browser supports css to format forms, especially the width
+ $bInfo['FORMSTYLE'] = ($bInfo['BROWSER'] == 'msie' || ($bInfo['BROWSER'] == 'net' && $bInfo['VERSION'] >= 5) || $bInfo['BROWSER'] == 'opera' || $bInfo['BROWSER'] == 'konqu');
return $bInfo;
}
@@ -3954,51 +4273,39 @@ final class t3lib_div {
* @param boolean Use request host (when not in CLI mode).
* @return string The fully-qualified host name.
*/
- public static function getHostname($requestHost=TRUE) {
+ public static function getHostname($requestHost = TRUE) {
$host = '';
- if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
- $host = t3lib_div::getIndpEnv('HTTP_HOST');
+ // If not called from the command-line, resolve on getIndpEnv()
+ // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
+ if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
+ $host = self::getIndpEnv('HTTP_HOST');
}
- if (!$host) {
+ if (!$host) {
// will fail for PHP 4.1 and 4.2
$host = @php_uname('n');
// 'n' is ignored in broken installations
- if (strpos($host, ' ')) $host = '';
- }
- // we have not found a FQDN yet
- if ($host && strpos($host, '.') === false) {
- $ip = gethostbyname($host);
- // we got an IP address
- if ($ip != $host) {
- $fqdn = gethostbyaddr($ip);
- if ($ip != $fqdn) $host = $fqdn;
+ if (strpos($host, ' ')) {
+ $host = '';
}
}
- if (!$host) $host = 'localhost.localdomain';
+ // we have not found a FQDN yet
+ if ($host && strpos($host, '.') === FALSE) {
+ $ip = gethostbyname($host);
+ // we got an IP address
+ if ($ip != $host) {
+ $fqdn = gethostbyaddr($ip);
+ if ($ip != $fqdn) {
+ $host = $fqdn;
+ }
+ }
+ }
+ if (!$host) {
+ $host = 'localhost.localdomain';
+ }
return $host;
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*************************
*
@@ -4015,45 +4322,51 @@ final class t3lib_div {
* @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
* @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
*/
- public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE) {
- if (!strcmp($filename,'')) return '';
+ public static function getFileAbsFileName($filename, $onlyRelative = TRUE, $relToTYPO3_mainDir = FALSE) {
+ if (!strcmp($filename, '')) {
+ return '';
+ }
- if ($relToTYPO3_mainDir) {
- if (!defined('PATH_typo3')) return '';
+ if ($relToTYPO3_mainDir) {
+ if (!defined('PATH_typo3')) {
+ return '';
+ }
$relPathPrefix = PATH_typo3;
} else {
$relPathPrefix = PATH_site;
}
- if (substr($filename,0,4)=='EXT:') { // extension
- list($extKey,$local) = explode('/',substr($filename,4),2);
- $filename='';
- if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
- $filename = t3lib_extMgm::extPath($extKey).$local;
+ if (substr($filename, 0, 4) == 'EXT:') { // extension
+ list($extKey, $local) = explode('/', substr($filename, 4), 2);
+ $filename = '';
+ if (strcmp($extKey, '') && t3lib_extMgm::isLoaded($extKey) && strcmp($local, '')) {
+ $filename = t3lib_extMgm::extPath($extKey) . $local;
}
- } elseif (!t3lib_div::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
- $filename=$relPathPrefix.$filename;
- } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
- $filename='';
+ } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
+ $filename = $relPathPrefix . $filename;
+ } elseif ($onlyRelative && !self::isFirstPartOfStr($filename, $relPathPrefix)) { // absolute, but set to blank if not allowed
+ $filename = '';
}
- if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) { // checks backpath.
+ if (strcmp($filename, '') && self::validPathStr($filename)) { // checks backpath.
return $filename;
}
}
/**
* Checks for malicious file paths.
- * Returns true if no '//', '..' or '\' is in the $theFile
+ *
+ * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
* This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
* So it's compatible with the UNIX style path strings valid for TYPO3 internally.
* Usage: 14
*
* @param string Filepath to evaluate
- * @return boolean True, if no '//', '\', '/../' is in the $theFile and $theFile doesn't begin with '../'
+ * @return boolean TRUE, $theFile is allowed path string
+ * @see http://php.net/manual/en/security.filesystem.nullbytes.php
* @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
*/
- public static function validPathStr($theFile) {
- if (strpos($theFile, '//')===false && strpos($theFile, '\\')===false && !preg_match('#(?:^\.\.|/\.\./)#', $theFile)) {
- return true;
+ public static function validPathStr($theFile) {
+ if (strpos($theFile, '//') === FALSE && strpos($theFile, '\\') === FALSE && !preg_match('#(?:^\.\.|/\.\./|[[:cntrl:]])#', $theFile)) {
+ return TRUE;
}
}
@@ -4064,8 +4377,14 @@ final class t3lib_div {
* @param string Filepath to evaluate
* @return boolean
*/
- public static function isAbsPath($path) {
- return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
+ public static function isAbsPath($path) {
+ // on Windows also a path starting with a drive letter is absolute: X:/
+ if (TYPO3_OS === 'WIN' && substr($path, 1, 2) === ':/') {
+ return TRUE;
+ }
+
+ // path starting with a / is always absolute, on every system
+ return (substr($path, 0, 1) === '/');
}
/**
@@ -4075,14 +4394,16 @@ final class t3lib_div {
* @param string Filepath to evaluate
* @return boolean
*/
- public static function isAllowedAbsPath($path) {
- if (t3lib_div::isAbsPath($path) &&
- t3lib_div::validPathStr($path) &&
- ( t3lib_div::isFirstPartOfStr($path,PATH_site)
- ||
- ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
+ public static function isAllowedAbsPath($path) {
+ if (self::isAbsPath($path) &&
+ self::validPathStr($path) &&
+ (self::isFirstPartOfStr($path, PATH_site)
+ ||
+ ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
)
- ) return true;
+ ) {
+ return TRUE;
+ }
}
/**
@@ -4092,12 +4413,19 @@ final class t3lib_div {
* @param string Filepath to evaluate
* @return boolean
*/
- public static function verifyFilenameAgainstDenyPattern($filename) {
- if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
- $result = preg_match('/'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'].'/i',$filename);
- if ($result) return false; // so if a matching filename is found, return false;
+ public static function verifyFilenameAgainstDenyPattern($filename) {
+ // Filenames are not allowed to contain control characters
+ if (preg_match('/[[:cntrl:]]/', $filename)) {
+ return FALSE;
}
- return true;
+
+ if (strcmp($filename, '') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], '')) {
+ $result = preg_match('/' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . '/i', $filename);
+ if ($result) {
+ return FALSE;
+ } // so if a matching filename is found, return FALSE;
+ }
+ return TRUE;
}
/**
@@ -4107,7 +4435,7 @@ final class t3lib_div {
* @param string $url potential URL to check
*
* @return string either $url if $url is considered to be harmless, or an
- * empty string otherwise
+ * empty string otherwise
*/
public static function sanitizeLocalUrl($url = '') {
$sanitizedUrl = '';
@@ -4116,7 +4444,7 @@ final class t3lib_div {
if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
$testAbsoluteUrl = self::resolveBackPath($decodedUrl);
$testRelativeUrl = self::resolveBackPath(
- t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
+ self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
);
// Pass if URL is on the current host:
@@ -4153,17 +4481,17 @@ final class t3lib_div {
* @coauthor Dennis Petersen
* @see upload_to_tempfile()
*/
- public static function upload_copy_move($source,$destination) {
- if (is_uploaded_file($source)) {
+ public static function upload_copy_move($source, $destination) {
+ if (is_uploaded_file($source)) {
$uploaded = TRUE;
- // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
+ // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
$uploadedResult = move_uploaded_file($source, $destination);
} else {
$uploaded = FALSE;
- @copy($source,$destination);
+ @copy($source, $destination);
}
- t3lib_div::fixPermissions($destination); // Change the permissions of the file
+ self::fixPermissions($destination); // Change the permissions of the file
// If here the file is copied and the temporary $source is still around, so when returning false the user can try unlink to delete the $source
return $uploaded ? $uploadedResult : FALSE;
@@ -4179,9 +4507,9 @@ final class t3lib_div {
* @return string If a new file was successfully created, return its filename, otherwise blank string.
* @see unlink_tempfile(), upload_copy_move()
*/
- public static function upload_to_tempfile($uploadedFileName) {
- if (is_uploaded_file($uploadedFileName)) {
- $tempFile = t3lib_div::tempnam('upload_temp_');
+ public static function upload_to_tempfile($uploadedFileName) {
+ if (is_uploaded_file($uploadedFileName)) {
+ $tempFile = self::tempnam('upload_temp_');
move_uploaded_file($uploadedFileName, $tempFile);
return @is_file($tempFile) ? $tempFile : '';
}
@@ -4197,9 +4525,11 @@ final class t3lib_div {
* @return boolean Returns true if the file was unlink()'ed
* @see upload_to_tempfile(), tempnam()
*/
- public static function unlink_tempfile($uploadedTempFileName) {
- if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
- if (unlink($uploadedTempFileName)) return TRUE;
+ public static function unlink_tempfile($uploadedTempFileName) {
+ if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName, PATH_site . 'typo3temp/') && @is_file($uploadedTempFileName)) {
+ if (unlink($uploadedTempFileName)) {
+ return TRUE;
+ }
}
}
@@ -4213,8 +4543,8 @@ final class t3lib_div {
* @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
* @see unlink_tempfile(), upload_to_tempfile()
*/
- public static function tempnam($filePrefix) {
- return tempnam(PATH_site.'typo3temp/',$filePrefix);
+ public static function tempnam($filePrefix) {
+ return tempnam(PATH_site . 'typo3temp/', $filePrefix);
}
/**
@@ -4226,25 +4556,25 @@ final class t3lib_div {
* @param integer Length of returned authentication code.
* @return string MD5 hash of 8 chars.
*/
- public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8) {
+ public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) {
- if (is_array($uid_or_record)) {
- $recCopy_temp=array();
- if ($fields) {
- $fieldArr = t3lib_div::trimExplode(',',$fields,1);
+ if (is_array($uid_or_record)) {
+ $recCopy_temp = array();
+ if ($fields) {
+ $fieldArr = self::trimExplode(',', $fields, 1);
foreach ($fieldArr as $k => $v) {
- $recCopy_temp[$k]=$uid_or_record[$v];
+ $recCopy_temp[$k] = $uid_or_record[$v];
}
} else {
- $recCopy_temp=$uid_or_record;
+ $recCopy_temp = $uid_or_record;
}
- $preKey = implode('|',$recCopy_temp);
+ $preKey = implode('|', $recCopy_temp);
} else {
$preKey = $uid_or_record;
}
- $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
- $authCode = substr(md5($authCode),0,$codeLength);
+ $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
+ $authCode = substr(md5($authCode), 0, $codeLength);
return $authCode;
}
@@ -4257,18 +4587,18 @@ final class t3lib_div {
* @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
*/
public static function cHashParams($addQueryParams) {
- $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
+ $params = explode('&', substr($addQueryParams, 1)); // Splitting parameters up
// Make array:
$pA = array();
- foreach($params as $theP) {
- $pKV = explode('=', $theP); // Splitting single param by '=' sign
- if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0])) {
- $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
+ foreach ($params as $theP) {
+ $pKV = explode('=', $theP); // Splitting single param by '=' sign
+ if (!self::inList('id,type,no_cache,cHash,MP,ftu', $pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/', $pKV[0])) {
+ $pA[rawurldecode($pKV[0])] = (string) rawurldecode($pKV[1]);
}
}
// Hook: Allows to manipulate the parameters which are taken to build the chash:
- if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
+ if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
$cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
if (is_array($cHashParamsHook)) {
$hookParameters = array(
@@ -4276,9 +4606,9 @@ final class t3lib_div {
'params' => &$params,
'pA' => &$pA,
);
- $hookReference = null;
- foreach ($cHashParamsHook as $hookFunction) {
- t3lib_div::callUserFunction($hookFunction, $hookParameters, $hookReference);
+ $hookReference = NULL;
+ foreach ($cHashParamsHook as $hookFunction) {
+ self::callUserFunction($hookFunction, $hookParameters, $hookReference);
}
}
}
@@ -4297,8 +4627,8 @@ final class t3lib_div {
* @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
*/
public static function generateCHash($addQueryParams) {
- $cHashParams = t3lib_div::cHashParams($addQueryParams);
- $cHash = t3lib_div::calculateCHash($cHashParams);
+ $cHashParams = self::cHashParams($addQueryParams);
+ $cHash = self::calculateCHash($cHashParams);
return $cHash;
}
@@ -4319,11 +4649,11 @@ final class t3lib_div {
* @param integer Value from "l18n_cfg" field of a page record
* @return boolean True if the page should be hidden
*/
- public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
- if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
- return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
+ public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
+ if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
+ return $l18n_cfg_fieldValue & 2 ? FALSE : TRUE;
} else {
- return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
+ return $l18n_cfg_fieldValue & 2 ? TRUE : FALSE;
}
}
@@ -4333,47 +4663,60 @@ final class t3lib_div {
* @param string Input is a file-reference (see t3lib_div::getFileAbsFileName). That file is expected to be a 'locallang.php' file containing a $LOCAL_LANG array (will be included!) or a 'locallang.xml' file conataining a valid XML TYPO3 language structure.
* @param string Language key
* @param string Character set (option); if not set, determined by the language key
- * @param integer Error mode (when file could not be found): 0 - call debug(), 1 - do nothing, 2 - throw an exception
+ * @param integer Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
* @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
- * Otherwise an empty array and it is FALSE in error case.
+ * Otherwise an empty array and it is FALSE in error case.
*/
- public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
+ public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
$result = FALSE;
- $file = t3lib_div::getFileAbsFileName($fileRef);
- if ($file) {
+ $file = self::getFileAbsFileName($fileRef);
+ if ($file) {
$baseFile = preg_replace('/\.(php|xml)$/', '', $file);
- if (@is_file($baseFile.'.xml')) {
- $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey, $charset);
- } elseif (@is_file($baseFile.'.php')) {
- if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] || $charset) {
- $LOCAL_LANG = t3lib_div::readLLPHPfile($baseFile.'.php', $langKey, $charset);
+ if (@is_file($baseFile . '.xml')) {
+ $LOCAL_LANG = self::readLLXMLfile($baseFile . '.xml', $langKey, $charset);
+ } elseif (@is_file($baseFile . '.php')) {
+ if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] || $charset) {
+ $LOCAL_LANG = self::readLLPHPfile($baseFile . '.php', $langKey, $charset);
} else {
- include($baseFile.'.php');
- if (is_array($LOCAL_LANG)) {
- $LOCAL_LANG = array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]); }
+ include($baseFile . '.php');
+ if (is_array($LOCAL_LANG)) {
+ $LOCAL_LANG = array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]);
+ }
}
} else {
- $errorMsg = 'File "' . $fileRef. '" not found!';
+ $errorMsg = 'File "' . $fileRef . '" not found!';
if ($errorMode == 2) {
throw new t3lib_exception($errorMsg);
- } elseif(!$errorMode) {
- debug($errorMsg, 1);
+ } elseif (!$errorMode) {
+ self::sysLog($errorMsg, 'Core', self::SYSLOG_SEVERITY_ERROR);
}
$fileNotFound = TRUE;
}
- if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef])) {
- foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef] as $overrideFile) {
- $languageOverrideFileName = t3lib_div::getFileAbsFileName($overrideFile);
+
+
+ $overrides = array();
+ $fileRefWithoutExtension = preg_replace('/\.(php|xml)$/', '', $fileRef);
+
+ if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRefWithoutExtension . '.php'])) {
+ $overrides = array_merge($overrides, $GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRefWithoutExtension . '.php']);
+ }
+ if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRefWithoutExtension . '.xml'])) {
+ $overrides = array_merge($overrides, $GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRefWithoutExtension . '.xml']);
+ }
+
+ if (count($overrides) > 0) {
+ foreach ($overrides as $overrideFile) {
+ $languageOverrideFileName = self::getFileAbsFileName($overrideFile);
if (@is_file($languageOverrideFileName)) {
- $languageOverrideArray = t3lib_div::readLLXMLfile($languageOverrideFileName, $langKey, $charset);
- $LOCAL_LANG = t3lib_div::array_merge_recursive_overrule($LOCAL_LANG, $languageOverrideArray);
+ $languageOverrideArray = self::readLLXMLfile($languageOverrideFileName, $langKey, $charset);
+ $LOCAL_LANG = self::array_merge_recursive_overrule($LOCAL_LANG, $languageOverrideArray);
}
}
}
}
- if ($fileNotFound !== TRUE) {
+ if ($fileNotFound !== TRUE) {
$result = is_array($LOCAL_LANG) ? $LOCAL_LANG : array();
}
return $result;
@@ -4388,23 +4731,23 @@ final class t3lib_div {
* @param string Character set (optional)
* @return array LOCAL_LANG array in return.
*/
- public static function readLLPHPfile($fileRef, $langKey, $charset='') {
+ public static function readLLPHPfile($fileRef, $langKey, $charset = '') {
- if (is_object($GLOBALS['LANG'])) {
+ if (is_object($GLOBALS['LANG'])) {
$csConvObj = $GLOBALS['LANG']->csConvObj;
- } elseif (is_object($GLOBALS['TSFE'])) {
+ } elseif (is_object($GLOBALS['TSFE'])) {
$csConvObj = $GLOBALS['TSFE']->csConvObj;
} else {
- $csConvObj = t3lib_div::makeInstance('t3lib_cs');
+ $csConvObj = self::makeInstance('t3lib_cs');
}
- if (@is_file($fileRef) && $langKey) {
+ if (@is_file($fileRef) && $langKey) {
// Set charsets:
$sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
- if ($charset) {
+ if ($charset) {
$targetCharset = $csConvObj->parse_charset($charset);
- } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
+ } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
// when forceCharset is set, we store ALL labels in this charset!!!
$targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
} else {
@@ -4412,41 +4755,49 @@ final class t3lib_div {
}
// Cache file name:
- $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
- $cacheFileName = PATH_site.'typo3temp/llxml/'.
- substr(basename($fileRef),10,15).
- '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
+ $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
+ $cacheFileName = PATH_site . 'typo3temp/llxml/' .
+ substr(basename($fileRef), 10, 15) .
+ '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
// Check if cache file exists...
- if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
-
+ if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
+ $LOCAL_LANG = NULL;
// Get PHP data
include($fileRef);
- if (!is_array($LOCAL_LANG)) {
+ if (!is_array($LOCAL_LANG)) {
$fileName = substr($fileRef, strlen(PATH_site));
- die('\'' . $fileName . '\' is no TYPO3 language file)!');
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
+ 1270853900
+ );
}
// converting the default language (English)
// this needs to be done for a few accented loan words and extension names
if (is_array($LOCAL_LANG['default']) && $targetCharset != 'iso-8859-1') {
- foreach ($LOCAL_LANG['default'] as &$labelValue) {
+ foreach ($LOCAL_LANG['default'] as &$labelValue) {
$labelValue = $csConvObj->conv($labelValue, 'iso-8859-1', $targetCharset);
}
}
- if ($langKey!='default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset!=$targetCharset) {
- foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
+ if ($langKey != 'default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset != $targetCharset) {
+ foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
$labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
}
}
// Cache the content now:
- $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
- $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
- if ($res) die('ERROR: '.$res);
+ $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
+ $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
+ if ($res) {
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: "' . $res,
+ 1270853901
+ );
+ }
} else {
// Get content from cache:
- $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
+ $serContent = unserialize(self::getUrl($cacheFileName));
$LOCAL_LANG = $serContent['LOCAL_LANG'];
}
@@ -4463,23 +4814,23 @@ final class t3lib_div {
* @param string Character set (optional)
* @return array LOCAL_LANG array in return.
*/
- public static function readLLXMLfile($fileRef, $langKey, $charset='') {
+ public static function readLLXMLfile($fileRef, $langKey, $charset = '') {
- if (is_object($GLOBALS['LANG'])) {
+ if (is_object($GLOBALS['LANG'])) {
$csConvObj = $GLOBALS['LANG']->csConvObj;
- } elseif (is_object($GLOBALS['TSFE'])) {
+ } elseif (is_object($GLOBALS['TSFE'])) {
$csConvObj = $GLOBALS['TSFE']->csConvObj;
} else {
- $csConvObj = t3lib_div::makeInstance('t3lib_cs');
+ $csConvObj = self::makeInstance('t3lib_cs');
}
$LOCAL_LANG = NULL;
- if (@is_file($fileRef) && $langKey) {
+ if (@is_file($fileRef) && $langKey) {
// Set charset:
- if ($charset) {
+ if ($charset) {
$targetCharset = $csConvObj->parse_charset($charset);
- } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
+ } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
// when forceCharset is set, we store ALL labels in this charset!!!
$targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
} else {
@@ -4487,20 +4838,23 @@ final class t3lib_div {
}
// Cache file name:
- $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
- $cacheFileName = PATH_site.'typo3temp/llxml/'.
- substr(basename($fileRef),10,15).
- '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
+ $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
+ $cacheFileName = PATH_site . 'typo3temp/llxml/' .
+ substr(basename($fileRef), 10, 15) .
+ '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
// Check if cache file exists...
- if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
+ if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
// Read XML, parse it.
- $xmlString = t3lib_div::getUrl($fileRef);
- $xmlContent = t3lib_div::xml2array($xmlString);
+ $xmlString = self::getUrl($fileRef);
+ $xmlContent = self::xml2array($xmlString);
if (!is_array($xmlContent)) {
$fileName = substr($fileRef, strlen(PATH_site));
- die('The file "' . $fileName . '" is no TYPO3 language file!');
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
+ 1270853902
+ );
}
// Set default LOCAL_LANG array content:
@@ -4511,7 +4865,7 @@ final class t3lib_div {
// this needs to be done for a few accented loan words and extension names
// NOTE: no conversion is done when in UTF-8 mode!
if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
- foreach ($LOCAL_LANG['default'] as &$labelValue) {
+ foreach ($LOCAL_LANG['default'] as &$labelValue) {
$labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
}
unset($labelValue);
@@ -4519,74 +4873,85 @@ final class t3lib_div {
// converting other languages to their "native" charsets
// NOTE: no conversion is done when in UTF-8 mode!
- if ($langKey!='default') {
+ if ($langKey != 'default') {
// If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
- $LOCAL_LANG[$langKey] = t3lib_div::llXmlAutoFileName($fileRef, $langKey);
- $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
- if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
+ $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
+ $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
+ if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
$LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
}
// Checking if charset should be converted.
- if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
- foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
- $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
+ if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
+ foreach ($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
+ $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue, $targetCharset);
}
}
}
// Cache the content now:
- $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
- $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
- if ($res) die('ERROR: '.$res);
+ $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
+ $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
+ if ($res) {
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: ' . $res,
+ 1270853903
+ );
+ }
} else {
// Get content from cache:
- $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
+ $serContent = unserialize(self::getUrl($cacheFileName));
$LOCAL_LANG = $serContent['LOCAL_LANG'];
}
// Checking for EXTERNAL file for non-default language:
- if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
+ if ($langKey != 'default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
// Look for localized file:
- $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
- if ($localized_file && @is_file($localized_file)) {
+ $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
+ if ($localized_file && @is_file($localized_file)) {
// Cache file name:
- $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file)).'|version=2.3';
- $cacheFileName = PATH_site.'typo3temp/llxml/EXT_'.
- substr(basename($localized_file),10,15).
- '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
+ $hashSource = substr($localized_file, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($localized_file)) . '|version=2.3';
+ $cacheFileName = PATH_site . 'typo3temp/llxml/EXT_' .
+ substr(basename($localized_file), 10, 15) .
+ '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
// Check if cache file exists...
- if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
+ if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
// Read and parse XML content:
- $local_xmlString = t3lib_div::getUrl($localized_file);
- $local_xmlContent = t3lib_div::xml2array($local_xmlString);
+ $local_xmlString = self::getUrl($localized_file);
+ $local_xmlContent = self::xml2array($local_xmlString);
if (!is_array($local_xmlContent)) {
$fileName = substr($localized_file, strlen(PATH_site));
- die('The file "' . $fileName . '" is no TYPO3 language file!');
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
+ 1270853904
+ );
}
$LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
// Checking if charset should be converted.
- if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
- foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
- $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
+ if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
+ foreach ($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
+ $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue, $targetCharset);
}
}
// Cache the content now:
- $serContent = array('extlang'=>$langKey, 'origFile'=>$hashSource, 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
- $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
+ $serContent = array('extlang' => $langKey, 'origFile' => $hashSource, 'EXT_DATA' => $LOCAL_LANG[$langKey]);
+ $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
if ($res) {
- die('ERROR: '.$res);
+ throw new RuntimeException(
+ 'TYPO3 Fatal Error: ' . $res,
+ 1270853905
+ );
}
} else {
// Get content from cache:
- $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
+ $serContent = unserialize(self::getUrl($cacheFileName));
$LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
}
} else {
@@ -4605,33 +4970,35 @@ final class t3lib_div {
* @param string Language key
* @return string Returns the filename reference for the language unless error occured (or local mode is used) in which case it will be NULL
*/
- public static function llXmlAutoFileName($fileRef,$language) {
+ public static function llXmlAutoFileName($fileRef, $language) {
// Analyse file reference:
- $location = 'typo3conf/l10n/'.$language.'/'; // Default location of translations
- if (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) { // Is system:
- $validatedPrefix = PATH_typo3.'sysext/';
+ $location = 'typo3conf/l10n/' . $language . '/'; // Default location of translations
+ if (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'sysext/')) { // Is system:
+ $validatedPrefix = PATH_typo3 . 'sysext/';
#$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
- } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'ext/')) { // Is global:
- $validatedPrefix = PATH_typo3.'ext/';
- } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/')) { // Is local:
- $validatedPrefix = PATH_typo3conf.'ext/';
+ } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'ext/')) { // Is global:
+ $validatedPrefix = PATH_typo3 . 'ext/';
+ } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3conf . 'ext/')) { // Is local:
+ $validatedPrefix = PATH_typo3conf . 'ext/';
} else {
$validatedPrefix = '';
}
- if ($validatedPrefix) {
+ if ($validatedPrefix) {
// Divide file reference into extension key, directory (if any) and base name:
- list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
- $temp = t3lib_div::revExplode('/',$file_extPath,2);
- if (count($temp)==1) array_unshift($temp,''); // Add empty first-entry if not there.
- list($file_extPath,$file_fileName) = $temp;
+ list($file_extKey, $file_extPath) = explode('/', substr($fileRef, strlen($validatedPrefix)), 2);
+ $temp = self::revExplode('/', $file_extPath, 2);
+ if (count($temp) == 1) {
+ array_unshift($temp, '');
+ } // Add empty first-entry if not there.
+ list($file_extPath, $file_fileName) = $temp;
// The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
- return $location.
- $file_extKey.'/'.
- ($file_extPath?$file_extPath.'/':'').
- $language.'.'.$file_fileName;
+ return $location .
+ $file_extKey . '/' .
+ ($file_extPath ? $file_extPath . '/' : '') .
+ $language . '.' . $file_fileName;
} else {
return NULL;
}
@@ -4654,7 +5021,7 @@ final class t3lib_div {
* @param string Table name for which to load the full TCA array part into the global $TCA
* @return void
*/
- public static function loadTCA($table) {
+ public static function loadTCA($table) {
global $TCA;
if (isset($TCA[$table])) {
@@ -4662,11 +5029,13 @@ final class t3lib_div {
if (!$tca['columns']) {
$dcf = $tca['ctrl']['dynamicConfigFile'];
if ($dcf) {
- if (!strcmp(substr($dcf,0,6),'T3LIB:')) {
- include(PATH_t3lib.'stddb/'.substr($dcf,6));
- } elseif (t3lib_div::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
+ if (!strcmp(substr($dcf, 0, 6), 'T3LIB:')) {
+ include(PATH_t3lib . 'stddb/' . substr($dcf, 6));
+ } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
include($dcf);
- } else include(PATH_typo3conf.$dcf);
+ } else {
+ include(PATH_typo3conf . $dcf);
+ }
}
}
}
@@ -4681,30 +5050,34 @@ final class t3lib_div {
* @param string The sheet to return, preferably.
* @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error happend in which case an error string is returned (string). key1: The used sheet key value!
*/
- public static function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
- if (!is_array ($dataStructArray)) return 'Data structure must be an array';
+ public static function resolveSheetDefInDS($dataStructArray, $sheet = 'sDEF') {
+ if (!is_array($dataStructArray)) {
+ return 'Data structure must be an array';
+ }
- if (is_array($dataStructArray['sheets'])) {
+ if (is_array($dataStructArray['sheets'])) {
$singleSheet = FALSE;
- if (!isset($dataStructArray['sheets'][$sheet])) {
- $sheet='sDEF';
+ if (!isset($dataStructArray['sheets'][$sheet])) {
+ $sheet = 'sDEF';
}
- $dataStruct = $dataStructArray['sheets'][$sheet];
+ $dataStruct = $dataStructArray['sheets'][$sheet];
// If not an array, but still set, then regard it as a relative reference to a file:
- if ($dataStruct && !is_array($dataStruct)) {
- $file = t3lib_div::getFileAbsFileName($dataStruct);
- if ($file && @is_file($file)) {
- $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
+ if ($dataStruct && !is_array($dataStruct)) {
+ $file = self::getFileAbsFileName($dataStruct);
+ if ($file && @is_file($file)) {
+ $dataStruct = self::xml2array(self::getUrl($file));
}
}
} else {
$singleSheet = TRUE;
$dataStruct = $dataStructArray;
- if (isset($dataStruct['meta'])) unset($dataStruct['meta']); // Meta data should not appear there.
- $sheet = 'sDEF'; // Default sheet
+ if (isset($dataStruct['meta'])) {
+ unset($dataStruct['meta']);
+ } // Meta data should not appear there.
+ $sheet = 'sDEF'; // Default sheet
}
- return array($dataStruct,$sheet,$singleSheet);
+ return array($dataStruct, $sheet, $singleSheet);
}
/**
@@ -4714,17 +5087,17 @@ final class t3lib_div {
* @param array Input data structure, possibly with a sheet-definition and references to external data source files.
* @return array Output data structure with all sheets resolved as arrays.
*/
- public static function resolveAllSheetsInDS(array $dataStructArray) {
- if (is_array($dataStructArray['sheets'])) {
- $out=array('sheets'=>array());
- foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
- list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
- if ($sheetId==$aS) {
- $out['sheets'][$aS]=$ds;
+ public static function resolveAllSheetsInDS(array $dataStructArray) {
+ if (is_array($dataStructArray['sheets'])) {
+ $out = array('sheets' => array());
+ foreach ($dataStructArray['sheets'] as $sheetId => $sDat) {
+ list($ds, $aS) = self::resolveSheetDefInDS($dataStructArray, $sheetId);
+ if ($sheetId == $aS) {
+ $out['sheets'][$aS] = $ds;
}
}
} else {
- list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
+ list($ds) = self::resolveSheetDefInDS($dataStructArray);
$out = array('sheets' => array('sDEF' => $ds));
}
return $out;
@@ -4743,72 +5116,71 @@ final class t3lib_div {
* @return mixed Content from method/function call or false if the class/method/function was not found
* @see getUserObj()
*/
- public static function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$errorMode=0) {
+ public static function callUserFunction($funcName, &$params, &$ref, $checkPrefix = 'user_', $errorMode = 0) {
global $TYPO3_CONF_VARS;
- $content = false;
+ $content = FALSE;
// Check persistent object and if found, call directly and exit.
- if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
+ if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
return call_user_func_array(
- array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
- $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
- array(&$params, &$ref)
- );
+ array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
+ $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
+ array(&$params, &$ref)
+ );
}
// Check file-reference prefix; if found, require_once() the file (should be library of code)
- if (strpos($funcName,':') !== false) {
- list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
- $requireFile = t3lib_div::getFileAbsFileName($file);
- if ($requireFile) t3lib_div::requireOnce($requireFile);
+ if (strpos($funcName, ':') !== FALSE) {
+ list($file, $funcRef) = self::revExplode(':', $funcName, 2);
+ $requireFile = self::getFileAbsFileName($file);
+ if ($requireFile) {
+ self::requireOnce($requireFile);
+ }
} else {
$funcRef = $funcName;
}
// Check for persistent object token, "&"
- if (substr($funcRef,0,1)=='&') {
- $funcRef = substr($funcRef,1);
- $storePersistentObject = true;
+ if (substr($funcRef, 0, 1) == '&') {
+ $funcRef = substr($funcRef, 1);
+ $storePersistentObject = TRUE;
} else {
- $storePersistentObject = false;
+ $storePersistentObject = FALSE;
}
// Check prefix is valid:
- if ($checkPrefix &&
- !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
- !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
- ) {
+ if ($checkPrefix && !self::hasValidClassPrefix($funcRef, array($checkPrefix))) {
$errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
if ($errorMode == 2) {
throw new Exception($errorMsg);
- } elseif(!$errorMode) {
- debug($errorMsg, 1);
+ } elseif (!$errorMode) {
+ debug($errorMsg, 't3lib_div::callUserFunction');
}
- return false;
+ return FALSE;
}
// Call function or method:
- $parts = explode('->',$funcRef);
- if (count($parts)==2) { // Class
+ $parts = explode('->', $funcRef);
+ if (count($parts) == 2) { // Class
// Check if class/method exists:
- if (class_exists($parts[0])) {
+ if (class_exists($parts[0])) {
// Get/Create object of class:
- if ($storePersistentObject) { // Get reference to current instance of class:
- if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
- $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = t3lib_div::makeInstance($parts[0]);
+ if ($storePersistentObject) { // Get reference to current instance of class:
+ if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
+ $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self::makeInstance($parts[0]);
}
$classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
- } else { // Create new object:
- $classObj = t3lib_div::makeInstance($parts[0]);
+ } else { // Create new object:
+ $classObj = self::makeInstance($parts[0]);
}
- if (method_exists($classObj, $parts[1])) {
+ if (method_exists($classObj, $parts[1])) {
// If persistent object should be created, set reference:
- if ($storePersistentObject) {
- $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
+ if ($storePersistentObject) {
+ $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array(
'method' => $parts[1],
'obj' => &$classObj
);
@@ -4819,30 +5191,30 @@ final class t3lib_div {
array(&$params, &$ref)
);
} else {
- $errorMsg = "ERROR: No method name '".$parts[1]."' in class ".$parts[0];
+ $errorMsg = "ERROR: No method name '" . $parts[1] . "' in class " . $parts[0];
if ($errorMode == 2) {
throw new Exception($errorMsg);
- } elseif(!$errorMode) {
- debug($errorMsg, 1);
+ } elseif (!$errorMode) {
+ debug($errorMsg, 't3lib_div::callUserFunction');
}
}
} else {
- $errorMsg = "ERROR: No class named: ".$parts[0];
+ $errorMsg = "ERROR: No class named: " . $parts[0];
if ($errorMode == 2) {
throw new Exception($errorMsg);
- } elseif(!$errorMode) {
- debug($errorMsg, 1);
+ } elseif (!$errorMode) {
+ debug($errorMsg, 't3lib_div::callUserFunction');
}
}
- } else { // Function
- if (function_exists($funcRef)) {
+ } else { // Function
+ if (function_exists($funcRef)) {
$content = call_user_func_array($funcRef, array(&$params, &$ref));
} else {
- $errorMsg = "ERROR: No function named: ".$funcRef;
+ $errorMsg = "ERROR: No function named: " . $funcRef;
if ($errorMode == 2) {
throw new Exception($errorMsg);
- } elseif(!$errorMode) {
- debug($errorMsg, 1);
+ } elseif (!$errorMode) {
+ debug($errorMsg, 't3lib_div::callUserFunction');
}
}
}
@@ -4855,97 +5227,140 @@ final class t3lib_div {
* Usage: 5
*
* @param string Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
- * @param string Required prefix of class name. By default "tx_" is allowed.
+ * @param string Required prefix of class name. By default "tx_" and "Tx_" are allowed.
* @param boolean If set, no debug() error message is shown if class/function is not present.
* @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
* @see callUserFunction()
*/
- public static function getUserObj($classRef, $checkPrefix='user_', $silent=false) {
+ public static function getUserObj($classRef, $checkPrefix = 'user_', $silent = FALSE) {
global $TYPO3_CONF_VARS;
// Check persistent object and if found, call directly and exit.
- if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
+ if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
} else {
// Check file-reference prefix; if found, require_once() the file (should be library of code)
- if (strpos($classRef,':') !== false) {
- list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
- $requireFile = t3lib_div::getFileAbsFileName($file);
- if ($requireFile) t3lib_div::requireOnce($requireFile);
+ if (strpos($classRef, ':') !== FALSE) {
+ list($file, $class) = self::revExplode(':', $classRef, 2);
+ $requireFile = self::getFileAbsFileName($file);
+ if ($requireFile) {
+ self::requireOnce($requireFile);
+ }
} else {
$class = $classRef;
}
// Check for persistent object token, "&"
- if (substr($class,0,1)=='&') {
- $class = substr($class,1);
+ if (substr($class, 0, 1) == '&') {
+ $class = substr($class, 1);
$storePersistentObject = TRUE;
} else {
$storePersistentObject = FALSE;
}
// Check prefix is valid:
- if ($checkPrefix &&
- !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
- !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
- ) {
- if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
+ if ($checkPrefix && !self::hasValidClassPrefix($class, array($checkPrefix))) {
+ if (!$silent) {
+ debug("Class '" . $class . "' was not prepended with '" . $checkPrefix . "'", 't3lib_div::getUserObj');
+ }
return FALSE;
}
// Check if class exists:
- if (class_exists($class)) {
- $classObj = t3lib_div::makeInstance($class);
+ if (class_exists($class)) {
+ $classObj = self::makeInstance($class);
// If persistent object should be created, set reference:
- if ($storePersistentObject) {
+ if ($storePersistentObject) {
$GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
}
return $classObj;
} else {
- if (!$silent) debug("ERROR: No class named: ".$class,1);
+ if (!$silent) {
+ debug("ERROR: No class named: " . $class, 't3lib_div::getUserObj');
+ }
}
}
}
+ /**
+ * Checks if a class or function has a valid prefix: tx_, Tx_ or custom, e.g. user_
+ *
+ * @param string $classRef The class or function to check
+ * @param array $additionalPrefixes Additional allowed prefixes, mostly this will be user_
+ * @return bool TRUE if name is allowed
+ */
+ public static function hasValidClassPrefix($classRef, array $additionalPrefixes = array()) {
+ $hasValidPrefix = FALSE;
+ $validPrefixes = array('tx_', 'Tx_', $GLOBALS['TYPO3_CONF_VARS']['FE']['userFuncClassPrefix']);
+ $classRef = trim($classRef);
+
+ if (count($additionalPrefixes)) {
+ $validPrefixes = array_merge($validPrefixes, $additionalPrefixes);
+ }
+
+ foreach ($validPrefixes as $prefixToCheck) {
+ if (self::isFirstPartOfStr($classRef, $prefixToCheck)) {
+ $hasValidPrefix = TRUE;
+ break;
+ }
+ }
+
+ return $hasValidPrefix;
+ }
+
/**
* Creates an instance of a class taking into account the class-extensions
* API of TYPO3. USE THIS method instead of the PHP "new" keyword.
* Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
- * You can also pass arguments for a constructor:
- * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
*
- * @param string Class name to instantiate
- * @return object A reference to the object
+ * You can also pass arguments for a constructor:
+ * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
+ *
+ * @throws InvalidArgumentException if classname is an empty string
+ * @param string $className
+ * name of the class to instantiate, must not be empty
+ * @return object the created instance
*/
public static function makeInstance($className) {
- // holds references of singletons
- static $instances = array();
+ if ($className === '') {
+ throw new InvalidArgumentException('$classname must not be empty.', 1288965219);
+ }
- // Get final classname
- $className = self::getClassName($className);
+ // Determine final class name which must be instantiated, this takes XCLASS handling
+ // into account. Cache in a local array to save some cycles for consecutive calls.
+ if (!isset(self::$finalClassNameRegister[$className])) {
+ self::$finalClassNameRegister[$className] = self::getClassName($className);
+ }
+ $finalClassName = self::$finalClassNameRegister[$className];
- if (isset($instances[$className])) {
- // it's a singleton, get the existing instance
- $instance = $instances[$className];
+ // Return singleton instance if it is already registered
+ if (isset(self::$singletonInstances[$finalClassName])) {
+ return self::$singletonInstances[$finalClassName];
+ }
+
+ // Return instance if it has been injected by addInstance()
+ if (isset(self::$nonSingletonInstances[$finalClassName])
+ && !empty(self::$nonSingletonInstances[$finalClassName])
+ ) {
+ return array_shift(self::$nonSingletonInstances[$finalClassName]);
+ }
+
+ // Create new instance and call constructor with parameters
+ if (func_num_args() > 1) {
+ $constructorArguments = func_get_args();
+ array_shift($constructorArguments);
+
+ $reflectedClass = new ReflectionClass($finalClassName);
+ $instance = $reflectedClass->newInstanceArgs($constructorArguments);
} else {
- if (func_num_args() > 1) {
- // getting the constructor arguments by removing this
- // method's first argument (the class name)
- $constructorArguments = func_get_args();
- array_shift($constructorArguments);
+ $instance = new $finalClassName;
+ }
- $reflectedClass = new ReflectionClass($className);
- $instance = $reflectedClass->newInstanceArgs($constructorArguments);
- } else {
- $instance = new $className;
- }
-
- if ($instance instanceof t3lib_Singleton) {
- // it's a singleton, save the instance for later reuse
- $instances[$className] = $instance;
- }
+ // Register new singleton instance
+ if ($instance instanceof t3lib_Singleton) {
+ self::$singletonInstances[$finalClassName] = $instance;
}
return $instance;
@@ -4958,12 +5373,12 @@ final class t3lib_div {
*
* @param string Base Class name to evaluate
* @return string Final class name to instantiate with "new [classname]"
- * @deprecated since TYPO3 4.3 - Use t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
+ * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.6 - Use t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
*/
- public static function makeInstanceClassName($className) {
+ public static function makeInstanceClassName($className) {
self::logDeprecatedFunction();
- return (class_exists($className) && class_exists('ux_'.$className, false) ? t3lib_div::makeInstanceClassName('ux_' . $className) : $className);
+ return (class_exists($className) && class_exists('ux_' . $className, FALSE) ? self::makeInstanceClassName('ux_' . $className) : $className);
}
/**
@@ -4974,7 +5389,104 @@ final class t3lib_div {
* @return string Final class name to instantiate with "new [classname]"
*/
protected function getClassName($className) {
- return (class_exists($className) && class_exists('ux_' . $className, false) ? self::getClassName('ux_' . $className) : $className);
+ if (class_exists($className)) {
+ while (class_exists('ux_' . $className, FALSE)) {
+ $className = 'ux_' . $className;
+ }
+ }
+
+ return $className;
+ }
+
+ /**
+ * Sets the instance of a singleton class to be returned by makeInstance.
+ *
+ * If this function is called multiple times for the same $className,
+ * makeInstance will return the last set instance.
+ *
+ * Warning: This is a helper method for unit tests. Do not call this directly in production code!
+ *
+ * @see makeInstance
+ * @param string $className
+ * the name of the class to set, must not be empty
+ * @param t3lib_Singleton $instance
+ * the instance to set, must be an instance of $className
+ * @return void
+ */
+ public static function setSingletonInstance($className, t3lib_Singleton $instance) {
+ self::checkInstanceClassName($className, $instance);
+ self::$singletonInstances[$className] = $instance;
+ }
+
+ /**
+ * Sets the instance of a non-singleton class to be returned by makeInstance.
+ *
+ * If this function is called multiple times for the same $className,
+ * makeInstance will return the instances in the order in which they have
+ * been added (FIFO).
+ *
+ * Warning: This is a helper method for unit tests. Do not call this directly in production code!
+ *
+ * @see makeInstance
+ * @throws InvalidArgumentException if class extends t3lib_Singleton
+ * @param string $className
+ * the name of the class to set, must not be empty
+ * @param object $instance
+ * the instance to set, must be an instance of $className
+ * @return void
+ */
+ public static function addInstance($className, $instance) {
+ self::checkInstanceClassName($className, $instance);
+
+ if ($instance instanceof t3lib_Singleton) {
+ throw new InvalidArgumentException(
+ '$instance must not be an instance of t3lib_Singleton. ' .
+ 'For setting singletons, please use setSingletonInstance.',
+ 1288969325
+ );
+ }
+
+ if (!isset(self::$nonSingletonInstances[$className])) {
+ self::$nonSingletonInstances[$className] = array();
+ }
+ self::$nonSingletonInstances[$className][] = $instance;
+ }
+
+ /**
+ * Checks that $className is non-empty and that $instance is an instance of
+ * $className.
+ *
+ * @throws InvalidArgumentException if $className is empty or if $instance is no instance of $className
+ * @param string $className a class name
+ * @param object $instance an object
+ * @return void
+ */
+ protected static function checkInstanceClassName($className, $instance) {
+ if ($className === '') {
+ throw new InvalidArgumentException('$className must not be empty.', 1288967479);
+ }
+ if (!($instance instanceof $className)) {
+ throw new InvalidArgumentException(
+ '$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.',
+ 1288967686
+ );
+ }
+ }
+
+ /**
+ * Purge all instances returned by makeInstance.
+ *
+ * This function is most useful when called from tearDown in a testcase
+ * to drop any instances that have been created by the tests.
+ *
+ * Warning: This is a helper method for unit tests. Do not call this directly in production code!
+ *
+ * @see makeInstance
+ * @return void
+ */
+ public static function purgeInstances() {
+ self::$singletonInstances = array();
+ self::$nonSingletonInstances = array();
}
/**
@@ -4985,34 +5497,34 @@ final class t3lib_div {
* @param string Sub type like file extensions or similar. Defined by the service.
* @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
* @return object The service object or an array with error info's.
- * @author Ren� Fritz
+ * @author René Fritz
*/
- public static function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) {
+ public static function makeInstanceService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
$error = FALSE;
- if (!is_array($excludeServiceKeys) ) {
- $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
+ if (!is_array($excludeServiceKeys)) {
+ $excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, 1);
}
- while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
+ while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
// Check persistent object and if found, call directly and exit.
- if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
+ if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
// reset service and return object
$T3_VAR['makeInstanceService'][$info['className']]->reset();
return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
// include file and create object
} else {
- $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
+ $requireFile = self::getFileAbsFileName($info['classFile']);
if (@is_file($requireFile)) {
- t3lib_div::requireOnce ($requireFile);
- $obj = t3lib_div::makeInstance($info['className']);
+ self::requireOnce($requireFile);
+ $obj = self::makeInstance($info['className']);
if (is_object($obj)) {
- if(!@is_callable(array($obj,'init'))) {
+ if (!@is_callable(array($obj, 'init'))) {
// use silent logging??? I don't think so.
- die ('Broken service:'.t3lib_div::view_array($info));
+ die ('Broken service:' . t3lib_utility_Debug::viewArray($info));
}
$obj->info = $info;
if ($obj->init()) { // service available?
@@ -5031,7 +5543,7 @@ final class t3lib_div {
}
}
// deactivate the service
- t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
+ t3lib_extMgm::deactivateService($info['serviceType'], $info['serviceKey']);
}
return $error;
}
@@ -5040,7 +5552,7 @@ final class t3lib_div {
* Require a class for TYPO3
* Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
*/
- public static function requireOnce($requireFile) {
+ public static function requireOnce($requireFile) {
global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
require_once ($requireFile);
@@ -5068,76 +5580,73 @@ final class t3lib_div {
* @param string Email address to send to. (see PHP function mail())
* @param string Subject line, non-encoded. (see PHP function mail())
* @param string Message content, non-encoded. (see PHP function mail())
- * @param string Headers, separated by chr(10)
+ * @param string Headers, separated by LF
* @param string Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
* @param string Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
* @param boolean If set, the header content will not be encoded.
* @return boolean True if mail was accepted for delivery, false otherwise
*/
- public static function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false) {
- if (!$charset) {
+ public static function plainMailEncoded($email, $subject, $message, $headers = '', $encoding = 'quoted-printable', $charset = '', $dontEncodeHeader = FALSE) {
+ if (!$charset) {
$charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
}
$email = self::normalizeMailAddress($email);
- if (!$dontEncodeHeader) {
+ if (!$dontEncodeHeader) {
// Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
- $newHeaders=array();
- foreach (explode(chr(10),$headers) as $line) { // Split the header in lines and convert each line separately
- $parts = explode(': ',$line,2); // Field tags must not be encoded
- if (count($parts)==2) {
+ $newHeaders = array();
+ foreach (explode(LF, $headers) as $line) { // Split the header in lines and convert each line separately
+ $parts = explode(': ', $line, 2); // Field tags must not be encoded
+ if (count($parts) == 2) {
if (0 == strcasecmp($parts[0], 'from')) {
$parts[1] = self::normalizeMailAddress($parts[1]);
}
- $parts[1] = t3lib_div::encodeHeader($parts[1],$encoding,$charset);
- $newHeaders[] = implode(': ',$parts);
+ $parts[1] = self::encodeHeader($parts[1], $encoding, $charset);
+ $newHeaders[] = implode(': ', $parts);
} else {
- $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
+ $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
}
}
- $headers = implode(chr(10),$newHeaders);
+ $headers = implode(LF, $newHeaders);
unset($newHeaders);
- $email = t3lib_div::encodeHeader($email,$encoding,$charset); // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Sk�rh�j ")
- $subject = t3lib_div::encodeHeader($subject,$encoding,$charset);
+ $email = self::encodeHeader($email, $encoding, $charset); // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Skårhøj ")
+ $subject = self::encodeHeader($subject, $encoding, $charset);
}
- switch ((string)$encoding) {
+ switch ((string) $encoding) {
case 'base64':
- $headers=trim($headers).chr(10).
- 'Mime-Version: 1.0'.chr(10).
- 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
- 'Content-Transfer-Encoding: base64';
+ $headers = trim($headers) . LF .
+ 'Mime-Version: 1.0' . LF .
+ 'Content-Type: text/plain; charset="' . $charset . '"' . LF .
+ 'Content-Transfer-Encoding: base64';
- $message=trim(chunk_split(base64_encode($message.chr(10)))).chr(10); // Adding chr(10) because I think MS outlook 2002 wants it... may be removed later again.
- break;
+ $message = trim(chunk_split(base64_encode($message . LF))) . LF; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
+ break;
case '8bit':
- $headers=trim($headers).chr(10).
- 'Mime-Version: 1.0'.chr(10).
- 'Content-Type: text/plain; charset='.$charset.chr(10).
- 'Content-Transfer-Encoding: 8bit';
- break;
+ $headers = trim($headers) . LF .
+ 'Mime-Version: 1.0' . LF .
+ 'Content-Type: text/plain; charset=' . $charset . LF .
+ 'Content-Transfer-Encoding: 8bit';
+ break;
case 'quoted-printable':
default:
- $headers=trim($headers).chr(10).
- 'Mime-Version: 1.0'.chr(10).
- 'Content-Type: text/plain; charset='.$charset.chr(10).
- 'Content-Transfer-Encoding: quoted-printable';
+ $headers = trim($headers) . LF .
+ 'Mime-Version: 1.0' . LF .
+ 'Content-Type: text/plain; charset=' . $charset . LF .
+ 'Content-Transfer-Encoding: quoted-printable';
- $message=t3lib_div::quoted_printable($message);
- break;
+ $message = self::quoted_printable($message);
+ break;
}
- // Headers must be separated by CRLF according to RFC 2822, not just LF.
- // But many servers (Gmail, for example) behave incorectly and want only LF.
- // So we stick to LF in all cases.
- $headers = trim(implode(chr(10), t3lib_div::trimExplode(chr(10), $headers, true))); // Make sure no empty lines are there.
+ // Headers must be separated by CRLF according to RFC 2822, not just LF.
+ // But many servers (Gmail, for example) behave incorectly and want only LF.
+ // So we stick to LF in all cases.
+ $headers = trim(implode(LF, self::trimExplode(LF, $headers, TRUE))); // Make sure no empty lines are there.
- $ret = @mail($email, $subject, $message, $headers);
- if (!$ret) {
- t3lib_div::sysLog('Mail to "'.$email.'" could not be sent (Subject: "'.$subject.'").', 'Core', 3);
- }
- return $ret;
+
+ return t3lib_utility_Mail::mail($email, $subject, $message, $headers);
}
/**
@@ -5150,42 +5659,42 @@ final class t3lib_div {
* @param integer Length of the lines, default is 76
* @return string The QP encoded string
*/
- public static function quoted_printable($string,$maxlen=76) {
+ public static function quoted_printable($string, $maxlen = 76) {
// Make sure the string contains only Unix linebreaks
- $string = str_replace(chr(13).chr(10), chr(10), $string); // Replace Windows breaks (\r\n)
- $string = str_replace(chr(13), chr(10), $string); // Replace Mac breaks (\r)
+ $string = str_replace(CRLF, LF, $string); // Replace Windows breaks (\r\n)
+ $string = str_replace(CR, LF, $string); // Replace Mac breaks (\r)
- $linebreak = chr(10); // Default line break for Unix systems.
- if (TYPO3_OS=='WIN') {
- $linebreak = chr(13).chr(10); // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
+ $linebreak = LF; // Default line break for Unix systems.
+ if (TYPO3_OS == 'WIN') {
+ $linebreak = CRLF; // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
}
$newString = '';
- $theLines = explode(chr(10),$string); // Split lines
- foreach ($theLines as $val) {
+ $theLines = explode(LF, $string); // Split lines
+ foreach ($theLines as $val) {
$newVal = '';
$theValLen = strlen($val);
$len = 0;
- for ($index=0; $index < $theValLen; $index++) { // Walk through each character of this line
- $char = substr($val,$index,1);
+ for ($index = 0; $index < $theValLen; $index++) { // Walk through each character of this line
+ $char = substr($val, $index, 1);
$ordVal = ord($char);
- if ($len>($maxlen-4) || ($len>($maxlen-14) && $ordVal==32)) {
- $newVal.='='.$linebreak; // Add a line break
- $len=0; // Reset the length counter
+ if ($len > ($maxlen - 4) || ($len > ($maxlen - 14) && $ordVal == 32)) {
+ $newVal .= '=' . $linebreak; // Add a line break
+ $len = 0; // Reset the length counter
}
- if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
- $newVal.=$char; // This character is ok, add it to the message
+ if (($ordVal >= 33 && $ordVal <= 60) || ($ordVal >= 62 && $ordVal <= 126) || $ordVal == 9 || $ordVal == 32) {
+ $newVal .= $char; // This character is ok, add it to the message
$len++;
} else {
- $newVal.=sprintf('=%02X',$ordVal); // Special character, needs to be encoded
- $len+=3;
+ $newVal .= sprintf('=%02X', $ordVal); // Special character, needs to be encoded
+ $len += 3;
}
}
- $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal); // Replaces a possible SPACE-character at the end of a line
- $newVal = preg_replace('/'.chr(9).'$/','=09',$newVal); // Replaces a possible TAB-character at the end of a line
- $newString.=$newVal.$linebreak;
+ $newVal = preg_replace('/' . chr(32) . '$/', '=20', $newVal); // Replaces a possible SPACE-character at the end of a line
+ $newVal = preg_replace('/' . TAB . '$/', '=09', $newVal); // Replaces a possible TAB-character at the end of a line
+ $newString .= $newVal . $linebreak;
}
- return preg_replace('/'.$linebreak.'$/','',$newString); // Remove last newline
+ return preg_replace('/' . $linebreak . '$/', '', $newString); // Remove last newline
}
/**
@@ -5197,42 +5706,42 @@ final class t3lib_div {
* @param string Charset used for encoding
* @return string The encoded string
*/
- public static function encodeHeader($line,$enc='quoted-printable',$charset='iso-8859-1') {
+ public static function encodeHeader($line, $enc = 'quoted-printable', $charset = 'iso-8859-1') {
// Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
- if (strpos($line,'###') !== false) {
+ if (strpos($line, '###') !== FALSE) {
return $line;
}
// Check if any non-ASCII characters are found - otherwise encoding is not needed
- if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) {
+ if (!preg_match('/[^' . chr(32) . '-' . chr(127) . ']/', $line)) {
return $line;
}
// Wrap email addresses in a special marker
$line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
$matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
- foreach ($matches as $part) {
+ foreach ($matches as $part) {
$oldPart = $part;
- switch ((string)$enc) {
+ switch ((string) $enc) {
case 'base64':
- $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
- break;
+ $part = '=?' . $charset . '?B?' . base64_encode($part) . '?=';
+ break;
case 'quoted-printable':
default:
- $qpValue = t3lib_div::quoted_printable($part,1000);
- if ($part!=$qpValue) {
- // Encoded words in the header should not contain non-encoded:
- // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
- // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
+ $qpValue = self::quoted_printable($part, 1000);
+ if ($part != $qpValue) {
+ // Encoded words in the header should not contain non-encoded:
+ // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
+ // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
$search = array(' ', '?');
$replace = array('_', '=3F');
$qpValue = str_replace($search, $replace, $qpValue);
- $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
+ $part = '=?' . $charset . '?Q?' . $qpValue . '?=';
}
- break;
+ break;
}
$line = str_replace($oldPart, $part, $line);
}
- $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
+ $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
return $line;
}
@@ -5248,27 +5757,27 @@ final class t3lib_div {
* @return string Processed message content
* @see makeRedirectUrl()
*/
- public static function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
+ public static function substUrlsInPlainText($message, $urlmode = '76', $index_script_url = '') {
// Substitute URLs with shorter links:
- foreach (array('http','https') as $protocol) {
- $urlSplit = explode($protocol.'://',$message);
+ foreach (array('http', 'https') as $protocol) {
+ $urlSplit = explode($protocol . '://', $message);
foreach ($urlSplit as $c => &$v) {
- if ($c) {
+ if ($c) {
$newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
- $newURL = $protocol.'://'.$newParts[0];
+ $newURL = $protocol . '://' . $newParts[0];
- switch ((string)$urlmode) {
+ switch ((string) $urlmode) {
case 'all':
- $newURL = t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
- break;
+ $newURL = self::makeRedirectUrl($newURL, 0, $index_script_url);
+ break;
case '76':
- $newURL = t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
- break;
+ $newURL = self::makeRedirectUrl($newURL, 76, $index_script_url);
+ break;
}
- $v = $newURL . substr($v,strlen($newParts[0]));
+ $v = $newURL . substr($v, strlen($newParts[0]));
}
}
- $message = implode('',$urlSplit);
+ $message = implode('', $urlSplit);
}
return $message;
@@ -5283,13 +5792,13 @@ final class t3lib_div {
* @param string URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php'
* @return string Processed URL
*/
- public static function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
- if (strlen($inUrl)>$l) {
- $md5 = substr(md5($inUrl),0,20);
+ public static function makeRedirectUrl($inUrl, $l = 0, $index_script_url = '') {
+ if (strlen($inUrl) > $l) {
+ $md5 = substr(md5($inUrl), 0, 20);
$count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
'*',
'cache_md5params',
- 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
+ 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
);
if (!$count) {
$insertFields = array(
@@ -5301,8 +5810,8 @@ final class t3lib_div {
$GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
}
- $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
- '?RDCT='.$md5;
+ $inUrl = ($index_script_url ? $index_script_url : self::getIndpEnv('TYPO3_REQUEST_DIR') . 'index.php') .
+ '?RDCT=' . $md5;
}
return $inUrl;
@@ -5315,9 +5824,11 @@ final class t3lib_div {
* @param integer Fontsize for freetype function call
* @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
*/
- public static function freetypeDpiComp($font_size) {
+ public static function freetypeDpiComp($font_size) {
$dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
- if ($dpi!=72) $font_size = $font_size/$dpi*72;
+ if ($dpi != 72) {
+ $font_size = $font_size / $dpi * 72;
+ }
return $font_size;
}
@@ -5327,43 +5838,43 @@ final class t3lib_div {
* @return void
* @see sysLog()
*/
- public static function initSysLog() {
+ public static function initSysLog() {
global $TYPO3_CONF_VARS;
// for CLI logging name is :
- if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
- $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getHostname($requestHost=FALSE).':'.PATH_site;
+ // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
+ if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
+ $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getHostname($requestHost = FALSE) . ':' . PATH_site;
}
// for Web logging name is :///
else {
- $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getIndpEnv('TYPO3_SITE_URL');
+ $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getIndpEnv('TYPO3_SITE_URL');
}
// init custom logging
- if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
- $params = array('initLog'=>TRUE);
+ if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
+ $params = array('initLog' => TRUE);
$fakeThis = FALSE;
- foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
- t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
+ foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
+ self::callUserFunction($hookMethod, $params, $fakeThis);
}
}
// init TYPO3 logging
- foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
- list($type,$destination) = explode(',',$log,3);
+ foreach (explode(';', $TYPO3_CONF_VARS['SYS']['systemLog'], 2) as $log) {
+ list($type, $destination) = explode(',', $log, 3);
- if ($type == 'syslog') {
- define_syslog_variables();
- if (TYPO3_OS == 'WIN') {
+ if ($type == 'syslog') {
+ if (TYPO3_OS == 'WIN') {
$facility = LOG_USER;
} else {
- $facility = constant('LOG_'.strtoupper($destination));
+ $facility = constant('LOG_' . strtoupper($destination));
}
openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
}
}
- $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = t3lib_div::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
+ $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = self::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'], 0, 4);
$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
}
@@ -5371,79 +5882,94 @@ final class t3lib_div {
* Logs message to the system log.
* This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
* If you want to implement the sysLog in your applications, simply add lines like:
- * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
+ * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
*
* @param string Message (in English).
* @param string Extension key (from which extension you are calling the log) or "Core"
* @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
* @return void
*/
- public static function sysLog($msg, $extKey, $severity=0) {
+ public static function sysLog($msg, $extKey, $severity = 0) {
global $TYPO3_CONF_VARS;
- $severity = t3lib_div::intInRange($severity,0,4);
+ $severity = self::intInRange($severity, 0, 4);
// is message worth logging?
- if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity) return;
+ if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity) {
+ return;
+ }
// initialize logging
- if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
- t3lib_div::initSysLog();
+ if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
+ self::initSysLog();
}
// do custom logging
- if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
- $params = array('msg'=>$msg, 'extKey'=>$extKey, 'backTrace'=>debug_backtrace(), 'severity'=>$severity);
+ if (isset($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
+ is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
+ $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
$fakeThis = FALSE;
- foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
- t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
+ foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
+ self::callUserFunction($hookMethod, $params, $fakeThis);
}
}
// TYPO3 logging enabled?
- if (!$TYPO3_CONF_VARS['SYS']['systemLog']) return;
+ if (!$TYPO3_CONF_VARS['SYS']['systemLog']) {
+ return;
+ }
$dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
$timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
// use all configured logging options
- foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
- list($type,$destination,$level) = explode(',',$log,4);
+ foreach (explode(';', $TYPO3_CONF_VARS['SYS']['systemLog'], 2) as $log) {
+ list($type, $destination, $level) = explode(',', $log, 4);
// is message worth logging for this log type?
- if (intval($level) > $severity) continue;
+ if (intval($level) > $severity) {
+ continue;
+ }
- $msgLine = ' - '.$extKey.': '.$msg;
+ $msgLine = ' - ' . $extKey . ': ' . $msg;
// write message to a file
- if ($type == 'file') {
+ if ($type == 'file') {
$file = fopen($destination, 'a');
- if ($file) {
- flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
- fwrite($file, date($dateFormat.' '.$timeFormat).$msgLine.chr(10));
- flock($file, LOCK_UN); // release the lock
+ if ($file) {
+ flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
+ fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF);
+ flock($file, LOCK_UN); // release the lock
fclose($file);
+ self::fixPermissions($destination);
}
}
// send message per mail
- elseif ($type == 'mail') {
- list($to,$from) = explode('/',$destination);
- mail($to, 'Warning - error in TYPO3 installation',
- 'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost']."\n".
- 'Extension: '.$extKey."\n".
- 'Severity: '.$severity."\n".
- "\n".$msg,
- ($from ? 'From: '.$from : '')
+ elseif ($type == 'mail') {
+ list($to, $from) = explode('/', $destination);
+ if (!t3lib_div::validEmail($from)) {
+ $from = t3lib_utility_Mail::getSystemFrom();
+ }
+ /** @var $mail t3lib_mail_Message */
+ $mail = t3lib_div::makeInstance('t3lib_mail_Message');
+ $mail->setTo($to)
+ ->setFrom($from)
+ ->setSubject('Warning - error in TYPO3 installation')
+ ->setBody('Host: ' . $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF .
+ 'Extension: ' . $extKey . LF .
+ 'Severity: ' . $severity . LF .
+ LF . $msg
);
+ $mail->send();
}
// use the PHP error log
- elseif ($type == 'error_log') {
- error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
+ elseif ($type == 'error_log') {
+ error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
}
// use the system log
- elseif ($type == 'syslog') {
- $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
- syslog($priority[(int)$severity], $msgLine);
+ elseif ($type == 'syslog') {
+ $priority = array(LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT);
+ syslog($priority[(int) $severity], $msgLine);
}
}
}
@@ -5454,22 +5980,22 @@ final class t3lib_div {
* The result is meant to make sense to developers during development or debugging of a site.
* The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
* If you want to implement the devLog in your applications, simply add lines like:
- * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
+ * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
*
* @param string Message (in english).
* @param string Extension key (from which extension you are calling the log)
* @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
- * @param array Additional data you want to pass to the logger.
+ * @param mixed Additional data you want to pass to the logger.
* @return void
*/
- public static function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
+ public static function devLog($msg, $extKey, $severity = 0, $dataVar = FALSE) {
global $TYPO3_CONF_VARS;
- if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
- $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
+ if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
+ $params = array('msg' => $msg, 'extKey' => $extKey, 'severity' => $severity, 'dataVar' => $dataVar);
$fakeThis = FALSE;
- foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
- t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
+ foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
+ self::callUserFunction($hookMethod, $params, $fakeThis);
}
}
}
@@ -5485,24 +6011,55 @@ final class t3lib_div {
return;
}
- // write a longer message to the deprecation log
- $destination = PATH_typo3conf . '/deprecation_' . t3lib_div::shortMD5(PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) . '.log';
- $file = @fopen($destination, 'a');
- if ($file) {
- $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
- flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
- @fwrite($file, $date.$msg.chr(10));
- flock($file, LOCK_UN); // release the lock
- @fclose($file);
+ $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
+ $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
+
+ // legacy values (no strict comparison, $log can be boolean, string or int)
+ if ($log === TRUE || $log == '1') {
+ $log = 'file';
}
- // copy message also to the developer log
- self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
+ if (stripos($log, 'file') !== FALSE) {
+ // write a longer message to the deprecation log
+ $destination = self::getDeprecationLogFileName();
+ $file = @fopen($destination, 'a');
+ if ($file) {
+ flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
+ @fwrite($file, $date . $msg . LF);
+ flock($file, LOCK_UN); // release the lock
+ @fclose($file);
+ self::fixPermissions($destination);
+ }
+ }
+
+ if (stripos($log, 'devlog') !== FALSE) {
+ // copy message also to the developer log
+ self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
+ }
+
+ // do not use console in login screen
+ if (stripos($log, 'console') !== FALSE && isset($GLOBALS['BE_USER']->user['uid'])) {
+ t3lib_utility_Debug::debug($msg, $date, 'Deprecation Log');
+ }
+ }
+
+ /**
+ * Gets the absolute path to the deprecation log file.
+ *
+ * @return string absolute path to the deprecation log file
+ */
+ public static function getDeprecationLogFileName() {
+ return PATH_typo3conf .
+ 'deprecation_' .
+ self::shortMD5(
+ PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
+ ) .
+ '.log';
}
/**
* Logs a call to a deprecated function.
- * The log message will b etaken from the annotation.
+ * The log message will be taken from the annotation.
* @return void
*/
public static function logDeprecatedFunction() {
@@ -5517,31 +6074,22 @@ final class t3lib_div {
} else {
$function = new ReflectionFunction($trail[1]['function']);
}
- if (!$msg) {
- if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
- $msg = $match[1];
- }
+
+ $msg = '';
+ if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
+ $msg = $match[1];
}
- // trigger PHP error with a short message: is deprecated (called from , defined in )
+ // trigger PHP error with a short message: is deprecated (called from , defined in )
$errorMsg = 'Function ' . $trail[1]['function'];
if ($trail[1]['class']) {
$errorMsg .= ' of class ' . $trail[1]['class'];
}
- $errorMsg .= ' is deprecated (called from '.$trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
+ $errorMsg .= ' is deprecated (called from ' . $trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
-// michael@typo3.org: Temporary disabled until error handling is implemented (follows later this week...)
-/*
- if (defined('E_USER_DEPRECATED')) {
- trigger_error($errorMsg, E_USER_DEPRECATED); // PHP 5.3
- } else {
- trigger_error($errorMsg, E_USER_NOTICE); // PHP 5.2
- }
-*/
-
- // write a longer message to the deprecation log: - ()
+ // write a longer message to the deprecation log: - ()
$logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
- $logMsg .= '() - ' . $msg.' - ' . self::debug_trail();
+ $logMsg .= '() - ' . $msg.' - ' . t3lib_utility_Debug::debugTrail();
$logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site)) . '#' . $function->getStartLine() . ')';
self::deprecationLog($logMsg);
}
@@ -5555,15 +6103,15 @@ final class t3lib_div {
* @param integer Long string values are shortened to this length. Default: 20
* @return string Output string with key names and their value as string
*/
- public static function arrayToLogString(array $arr, $valueList=array(), $valueLength=20) {
+ public static function arrayToLogString(array $arr, $valueList = array(), $valueLength = 20) {
$str = '';
- if (!is_array($valueList)) {
- $valueList = t3lib_div::trimExplode(',', $valueList, 1);
+ if (!is_array($valueList)) {
+ $valueList = self::trimExplode(',', $valueList, 1);
}
$valListCnt = count($valueList);
- foreach ($arr as $key => $value) {
- if (!$valListCnt || in_array($key, $valueList)) {
- $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd_cs(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
+ foreach ($arr as $key => $value) {
+ if (!$valListCnt || in_array($key, $valueList)) {
+ $str .= (string) $key . trim(': ' . self::fixed_lgd_cs(str_replace(LF, '|', (string) $value), $valueLength)) . '; ';
}
}
return $str;
@@ -5574,59 +6122,11 @@ final class t3lib_div {
*
* @param string Command to be run: identify, convert or combine/composite
* @param string The parameters string
- * @param string Override the default path
+ * @param string Override the default path (e.g. used by the install tool)
* @return string Compiled command that deals with IM6 & GraphicsMagick
*/
- public static function imageMagickCommand($command, $parameters, $path='') {
- $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
- $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
- $switchCompositeParameters=false;
-
- if(!$path) { $path = $gfxConf['im_path']; }
-
- $im_version = strtolower($gfxConf['im_version_5']);
- $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
-
- if($command==='combine') { // This is only used internally, has no effect outside
- $command = 'composite';
- }
-
- // Compile the path & command
- if($im_version==='gm') {
- $switchCompositeParameters=true;
- $path .= 'gm'.$isExt.' '.$command;
- } else {
- if($im_version==='im6') { $switchCompositeParameters=true; }
- $path .= (($command=='composite') ? $combineScript : $command).$isExt;
- }
-
- // strip profile information for thumbnails and reduce their size
- if ($parameters && $command != 'identify' && $gfxConf['im_useStripProfileByDefault'] && $gfxConf['im_stripProfileCommand'] != '') {
- if (strpos($parameters, $gfxConf['im_stripProfileCommand']) === false) {
- // Determine whether the strip profile action has be disabled by TypoScript:
- if ($parameters !== '-version' && strpos($parameters, '###SkipStripProfile###') === false) {
- $parameters = $gfxConf['im_stripProfileCommand'] . ' ' . $parameters;
- } else {
- $parameters = str_replace('###SkipStripProfile###', '', $parameters);
- }
- }
- }
-
- $cmdLine = $path.' '.$parameters;
-
- if($command=='composite' && $switchCompositeParameters) { // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
- $paramsArr = t3lib_div::unQuoteFilenames($parameters);
-
- if(count($paramsArr)>5) { // The mask image has been specified => swap the parameters
- $tmp = $paramsArr[count($paramsArr)-3];
- $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
- $paramsArr[count($paramsArr)-4] = $tmp;
- }
-
- $cmdLine = $path.' '.implode(' ', $paramsArr);
- }
-
- return $cmdLine;
+ public static function imageMagickCommand($command, $parameters, $path = '') {
+ return t3lib_utility_Command::imageMagickCommand($command, $parameters, $path);
}
/**
@@ -5636,30 +6136,33 @@ final class t3lib_div {
* @param boolean If set, the elements of the resulting array are unquoted.
* @return array Exploded parameters
*/
- public static function unQuoteFilenames($parameters,$unQuote=FALSE) {
+ public static function unQuoteFilenames($parameters, $unQuote = FALSE) {
$paramsArr = explode(' ', trim($parameters));
- $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
+ $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
foreach ($paramsArr as $k => $v) {
- if($quoteActive > -1) {
- $paramsArr[$quoteActive] .= ' '.$v;
+ if ($quoteActive > -1) {
+ $paramsArr[$quoteActive] .= ' ' . $v;
unset($paramsArr[$k]);
- if(preg_match('/"$/', $v)) { $quoteActive = -1; }
+ if (substr($v, -1) === $paramsArr[$quoteActive][0]) {
+ $quoteActive = -1;
+ }
+ } elseif (!trim($v)) {
+ unset($paramsArr[$k]); // Remove empty elements
- } elseif(!trim($v)) {
- unset($paramsArr[$k]); // Remove empty elements
-
- } elseif(preg_match('/^"/', $v)) {
+ } elseif (preg_match('/^(["\'])/', $v) && substr($v, -1) !== $v[0]) {
$quoteActive = $k;
}
}
- if($unQuote) {
+ if ($unQuote) {
foreach ($paramsArr as $key => &$val) {
- $val = preg_replace('/(^"|"$)/','',$val);
+ $val = preg_replace('/(^"|"$)/', '', $val);
+ $val = preg_replace('/(^\'|\'$)/', '', $val);
+
}
}
- // return reindexed array
+ // return reindexed array
return array_values($paramsArr);
}
@@ -5671,15 +6174,15 @@ final class t3lib_div {
*
* @param string $value the string to encode, may be empty
* @param boolean $withinCData
- * whether the escaped data is expected to be used as CDATA and thus
- * does not need to be htmlspecialchared
+ * whether the escaped data is expected to be used as CDATA and thus
+ * does not need to be htmlspecialchared
*
* @return string the encoded value already quoted (with single quotes),
- * will not be empty
+ * will not be empty
*/
- static public function quoteJSvalue($value, $withinCData = false) {
+ static public function quoteJSvalue($value, $withinCData = FALSE) {
$escapedValue = addcslashes(
- $value, '\'' . '"' . '\\' . chr(9) . chr(10) . chr(13)
+ $value, '\'' . '"' . '\\' . TAB . LF . CR
);
if (!$withinCData) {
$escapedValue = htmlspecialchars($escapedValue);
@@ -5694,8 +6197,8 @@ final class t3lib_div {
* @return void
*/
public static function cleanOutputBuffers() {
- while (ob_get_level()) {
- ob_end_clean();
+ while (ob_end_clean()) {
+ ;
}
header('Content-Encoding: None', TRUE);
}
@@ -5707,9 +6210,26 @@ final class t3lib_div {
* @return void
*/
public static function flushOutputBuffers() {
- while (ob_get_level()) {
- ob_end_flush();
+ $obContent = '';
+
+ while ($obContent .= ob_get_clean()) {
+ ;
}
+
+ // if previously a "Content-Encoding: whatever" has been set, we have to unset it
+ if (!headers_sent()) {
+ $headersList = headers_list();
+ foreach ($headersList as $header) {
+ // split it up at the :
+ list($key, $value) = self::trimExplode(':', $header, TRUE);
+ // check if we have a Content-Encoding other than 'None'
+ if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
+ header('Content-Encoding: None');
+ break;
+ }
+ }
+ }
+ echo $obContent;
}
}
diff --git a/lib/typo3/readme_moodle.txt b/lib/typo3/readme_moodle.txt
index 085e9d452df..12cb54bdb82 100644
--- a/lib/typo3/readme_moodle.txt
+++ b/lib/typo3/readme_moodle.txt
@@ -1,8 +1,12 @@
-Description of Typo3 libraries (v 4.3.0RC1) import into Moodle
+Description of Typo3 libraries (v 4.5.0) import into Moodle
skodak, stronk7
-25 June 2010 - Martin D
+25 June 2010 - Martin D (4.3.0RC1)
I renamed getURL to getUrl since it was being called that way everywhere.
I added a check to avoid notices on lib/typo3/class.t3lib_cs.php line 976
+
+22 October 2011 - Petr Skoda (4.5.0)
+ reapplied getURL --> getUrl in class.t3lib_div.php line 2992
+ reintroduced check to avoid notices on class.t3lib_cs.php line 1031