示例#1
0
 /**
  * Gets the relative path from a source directory to a target directory.
  * The allowed TYPO3 path is checked as well, thus it's not possible to go to upper levels.
  *
  * @param string $sourcePath Absolute source path
  * @param string $targetPath Absolute target path
  * @return NULL|string
  */
 public static function getRelativePath($sourcePath, $targetPath)
 {
     $relativePath = NULL;
     $sourcePath = rtrim(GeneralUtility::fixWindowsFilePath($sourcePath), '/');
     $targetPath = rtrim(GeneralUtility::fixWindowsFilePath($targetPath), '/');
     if ($sourcePath !== $targetPath) {
         $commonPrefix = self::getCommonPrefix(array($sourcePath, $targetPath));
         if ($commonPrefix !== NULL && \TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($commonPrefix)) {
             $commonPrefixLength = strlen($commonPrefix);
             $resolvedSourcePath = '';
             $resolvedTargetPath = '';
             $sourcePathSteps = 0;
             if (strlen($sourcePath) > $commonPrefixLength) {
                 $resolvedSourcePath = (string) substr($sourcePath, $commonPrefixLength);
             }
             if (strlen($targetPath) > $commonPrefixLength) {
                 $resolvedTargetPath = (string) substr($targetPath, $commonPrefixLength);
             }
             if ($resolvedSourcePath !== '') {
                 $sourcePathSteps = count(explode('/', $resolvedSourcePath));
             }
             $relativePath = self::sanitizeTrailingSeparator(str_repeat('../', $sourcePathSteps) . $resolvedTargetPath);
         }
     }
     return $relativePath;
 }
示例#2
0
 /**
  * return true if the button is clicked
  * @return bool
  */
 public function isClicked()
 {
     if ($this->form->isSubmitted()) {
         $post = GeneralUtility::_POST($this->form->getIdentifier());
         return isset($post[$this->getName()]) && $post[$this->getName()] == $this->getLabel();
     }
     return false;
 }
示例#3
0
 public static function handleRequest($namespace, $singleJsonRequest)
 {
     $methodRaw = $singleJsonRequest['method'];
     list($namespace, $method) = self::getNamespaceAndMethod($namespace, $methodRaw);
     $singleJsonRequest['method'] = $method;
     $server = new JsonServerService($namespace, (bool) GeneralUtility::_GP('smd'));
     $request = new Request();
     $request->setOptions($singleJsonRequest);
     $server->handle($request);
 }
示例#4
0
 /**
  * Checks peak memory usage and stores data in cache for use in the report module
  *
  * @return void
  */
 public static function peakMemoryUsage()
 {
     $peakUsage = memory_get_peak_usage(true);
     $memoryLimit = GeneralUtility::getBytesFromSizeMeasurement(ini_get('memory_limit'));
     if (is_double($memoryLimit) && $memoryLimit != 0) {
         if ($peakUsage / $memoryLimit >= 0.9) {
             /** @var $registry \TYPO3\CMS\Core\Registry */
             $registry = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Registry::class);
             $data = array('used' => $peakUsage, 'tstamp' => $GLOBALS['EXEC_TIME'], 'url' => GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
             $registry->set('core', 'reports-peakMemoryUsage', $data);
         }
     }
 }
示例#5
0
 /**
  * Returns TRUE if $haystack ends with $needle.
  * The input string is not trimmed before and search
  * is done case sensitive.
  *
  * @param string $haystack Full string to check
  * @param string $needle Reference string which must be found as the "last part" of the full string
  * @throws \InvalidArgumentException
  * @return boolean TRUE if $needle was found to be equal to the last part of $str
  * @deprecated since 6.3 - will be removed two versions later, use beginsWith() instead
  */
 public static function isLastPartOfString($haystack, $needle)
 {
     GeneralUtility::logDeprecatedFunction();
     // Sanitize $haystack and $needle
     if (is_object($haystack) || (string) $haystack != $haystack || strlen($haystack) < 1) {
         throw new \InvalidArgumentException('$haystack can not be interpreted as string or has no length', 1347135544);
     }
     if (is_object($needle) || (string) $needle != $needle || strlen($needle) < 1) {
         throw new \InvalidArgumentException('$needle can not be interpreted as string or has no length', 1347135545);
     }
     $stringLength = strlen($haystack);
     $needleLength = strlen($needle);
     return strrpos((string) $haystack, (string) $needle, 0) === $stringLength - $needleLength;
 }
 /**
  * Get Frontend User Group
  *
  * @return array
  */
 protected function getFrontendUserGroupIds()
 {
     if (!$this->objectManager) {
         $this->objectManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
     }
     $feGroupIds = [];
     $feUserId = (int) $GLOBALS['TSFE']->fe_user->user['uid'];
     if ($feUserId) {
         $frontendUserRepository = $this->objectManager->get(\TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository::class);
         $feUser = $frontendUserRepository->findByUid($feUserId);
         $feGroups = $feUser->getUsergroup();
         if ($feGroups) {
             foreach ($feGroups as $feGroup) {
                 $feGroupIds[] = $feGroup->getUid();
             }
         }
     }
     return $feGroupIds;
 }
 /**
  * Makes a table categorizable by adding value into the category registry.
  * FOR USE IN ext_localconf.php FILES or files in Configuration/TCA/Overrides/*.php Use the latter to benefit from TCA caching!
  *
  * @param string $extensionKey Extension key to be used
  * @param string $tableName Name of the table to be categorized
  * @param string $fieldName Name of the field to be used to store categories
  * @param array $options Additional configuration options
  * @see addTCAcolumns
  * @see addToAllTCAtypes
  */
 public static function makeCategorizable($extensionKey, $tableName, $fieldName = 'categories', array $options = array())
 {
     // Update the category registry
     $result = \TYPO3\CMS\Core\Category\CategoryRegistry::getInstance()->add($extensionKey, $tableName, $fieldName, $options);
     if ($result === FALSE) {
         $message = '\\TYPO3\\CMS\\Core\\Category\\CategoryRegistry: no category registered for table "%s". Key was already registered.';
         /** @var $logger \TYPO3\CMS\Core\Log\Logger */
         $logger = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Log\\LogManager')->getLogger(__CLASS__);
         $logger->warning(sprintf($message, $tableName));
     }
 }
示例#8
0
}
$file = 'people';
$file = 'contacts';
$file = 'cars';
$file = 'yvi';
if ($argc > 1) {
    $file = $argv[1];
}
$file = __DIR__ . '/var/Data/' . $file . '.json';
$fileContents = '';
$csvPath = __DIR__ . '/memory_samples.csv';
$fileHandle = fopen($csvPath, 'a');
$standardMemoryUsage = memory_get_usage(TRUE);
printf('Memory: %s Peak: %s' . PHP_EOL, GeneralUtility::formatBytes(memory_get_usage(TRUE) - $standardMemoryUsage), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE) - $standardMemoryUsage));
printf('File size: %s' . PHP_EOL, GeneralUtility::formatBytes(filesize($file)));
printf('Memory: %s Peak: %s' . PHP_EOL, GeneralUtility::formatBytes(memory_get_usage(TRUE) - $standardMemoryUsage), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE) - $standardMemoryUsage));
file_get_contents($file);
printf('Memory: %s Peak: %s' . PHP_EOL, GeneralUtility::formatBytes(memory_get_usage(TRUE) - $standardMemoryUsage), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE) - $standardMemoryUsage));
$fileContents = file_get_contents($file);
printf('Memory: %s Peak: %s' . PHP_EOL, GeneralUtility::formatBytes(memory_get_usage(TRUE) - $standardMemoryUsage), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE) - $standardMemoryUsage));
printf('Memory ratio: memory/filesize = %s' . PHP_EOL, (memory_get_usage(TRUE) - $standardMemoryUsage) / filesize($file));
$json = json_decode(file_get_contents($file), TRUE);
printf('Memory: %s Peak: %s' . PHP_EOL, GeneralUtility::formatBytes(memory_get_usage(TRUE) - $standardMemoryUsage), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE) - $standardMemoryUsage));
printf('Memory ratio: memory/filesize = %s' . PHP_EOL, (memory_get_usage(TRUE) - $standardMemoryUsage) / filesize($file));
printf('Memory ratio: memory/strlen = %s' . PHP_EOL, (memory_get_usage(TRUE) - $standardMemoryUsage) / strlen($fileContents));
printf('Memory ratio: memory/braces = %s' . PHP_EOL, (memory_get_usage(TRUE) - $standardMemoryUsage) / substr_count($fileContents, '{'));
printf('Memory ratio: memory/comma = %s' . PHP_EOL, (memory_get_usage(TRUE) - $standardMemoryUsage) / substr_count($fileContents, ','));
printf('Memory ratio: log(memory)/log(comma) = %s' . PHP_EOL, log(memory_get_usage(TRUE) - $standardMemoryUsage) / log(filesize($file)));
$toMb = 1024 * 1024;
//fputcsv($fileHandle, array(filesize($file) / $toMb, (float)(memory_get_usage(TRUE) - $standardMemoryUsage) / $toMb, (float)(memory_get_peak_usage(TRUE) - $standardMemoryUsage) / $toMb));
fputcsv($fileHandle, array(filesize($file), (double) (memory_get_usage(TRUE) - $standardMemoryUsage), (double) (memory_get_peak_usage(TRUE) - $standardMemoryUsage)));
示例#9
0
 /**
  * Returns the title for the input record. If blank, a "no title" label (localized) will be returned.
  * Do NOT htmlspecialchar the string from this function - has already been done.
  *
  * @param array $row The input row array (where the key "title" is used for the title)
  * @param int $titleLen Title length (30)
  * @return string The title.
  */
 public function getTitleStr($row, $titleLen = 30)
 {
     if ($this->ext_showNavTitle && trim($row['nav_title']) !== '') {
         $title = '<span title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tca.xlf:title', TRUE) . ' ' . htmlspecialchars(trim($row['title'])) . '">' . htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['nav_title'], $titleLen)) . '</span>';
     } else {
         $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $titleLen));
         if (trim($row['nav_title']) !== '') {
             $title = '<span title="' . $GLOBALS['LANG']->sL('LLL:EXT:cms/locallang_tca.xlf:pages.nav_title', TRUE) . ' ' . htmlspecialchars(trim($row['nav_title'])) . '">' . $title . '</span>';
         }
         $title = trim($row['title']) === '' ? '<em>[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']</em>' : $title;
     }
     return $title;
 }
示例#10
0
 /**
  * @return \TYPO3\CMS\Core\Encoder\JavaScriptEncoder
  */
 protected static function getJavaScriptEncoder()
 {
     if (empty(self::$javaScriptEncoder)) {
         self::$javaScriptEncoder = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Encoder\\JavaScriptEncoder');
     }
     return self::$javaScriptEncoder;
 }
示例#11
0
 /**
  * Filters an array to reduce its elements to match the condition.
  * The values in $keepItems can be optionally evaluated by a custom callback function.
  *
  * Example (arguments used to call this function):
  * $array = array(
  * array('aa' => array('first', 'second'),
  * array('bb' => array('third', 'fourth'),
  * array('cc' => array('fifth', 'sixth'),
  * );
  * $keepItems = array('third');
  * $getValueFunc = function($value) { return $value[0]; }
  *
  * Returns:
  * array(
  * array('bb' => array('third', 'fourth'),
  * )
  *
  * @param array $array The initial array to be filtered/reduced
  * @param mixed $keepItems The items which are allowed/kept in the array - accepts array or csv string
  * @param string $getValueFunc (optional) Callback function used to get the value to keep
  * @return array The filtered/reduced array with the kept items
  */
 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = null)
 {
     if ($array) {
         // Convert strings to arrays:
         if (is_string($keepItems)) {
             $keepItems = GeneralUtility::trimExplode(',', $keepItems);
         }
         // Check if valueFunc can be executed:
         if (!is_callable($getValueFunc)) {
             $getValueFunc = null;
         }
         // Do the filtering:
         if (is_array($keepItems) && !empty($keepItems)) {
             foreach ($array as $key => $value) {
                 // Get the value to compare by using the callback function:
                 $keepValue = isset($getValueFunc) ? call_user_func($getValueFunc, $value) : $value;
                 if (!in_array($keepValue, $keepItems)) {
                     unset($array[$key]);
                 }
             }
         }
     }
     return $array;
 }
 /**
  * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
  * This function is about preserving long links in messages.
  *
  * @param string $message Message content
  * @param string $urlmode URL mode; "76" or "all
  * @param string $index_script_url URL of index script (see makeRedirectUrl())
  * @return string Processed message content
  * @see makeRedirectUrl()
  */
 public static function substUrlsInPlainText($message, $urlmode = '76', $index_script_url = '')
 {
     switch ((string) $urlmode) {
         case '':
             $lengthLimit = FALSE;
             break;
         case 'all':
             $lengthLimit = 0;
             break;
         case '76':
         default:
             $lengthLimit = (int) $urlmode;
     }
     if ($lengthLimit === FALSE) {
         // No processing
         $messageSubstituted = $message;
     } else {
         $messageSubstituted = preg_replace_callback('/(http|https):\\/\\/.+(?=[\\]\\.\\?]*([\\! \'"()<>]+|$))/iU', function (array $matches) use($lengthLimit, $index_script_url) {
             return GeneralUtility::makeRedirectUrl($matches[0], $lengthLimit, $index_script_url);
         }, $message);
     }
     return $messageSubstituted;
 }
 /**
  * Method to raise a version number
  *
  * @param string $raise one of "main", "sub", "dev" - the version part to raise by one
  * @param string $version (like 4.1.20)
  * @return string
  * @throws \TYPO3\CMS\Core\Exception
  */
 public static function raiseVersionNumber($raise, $version)
 {
     if (!in_array($raise, array('main', 'sub', 'dev'))) {
         throw new \TYPO3\CMS\Core\Exception('RaiseVersionNumber expects one of "main", "sub" or "dev".', 1342639555);
     }
     $parts = GeneralUtility::intExplode('.', $version . '..');
     $parts[0] = MathUtility::forceIntegerInRange($parts[0], 0, 999);
     $parts[1] = MathUtility::forceIntegerInRange($parts[1], 0, 999);
     $parts[2] = MathUtility::forceIntegerInRange($parts[2], 0, 999);
     switch ((string) $raise) {
         case 'main':
             $parts[0]++;
             $parts[1] = 0;
             $parts[2] = 0;
             break;
         case 'sub':
             $parts[1]++;
             $parts[2] = 0;
             break;
         case 'dev':
             $parts[2]++;
             break;
     }
     return $parts[0] . '.' . $parts[1] . '.' . $parts[2];
 }
示例#14
0
 /**
  * Parses mailbox headers and turns them into an array.
  *
  * Mailbox headers are a comma separated list of 'name <*****@*****.**>' combinations
  * or plain email addresses (or a mix of these).
  * The resulting array has key-value pairs where the key is either a number
  * (no display name in the mailbox header) and the value is the email address,
  * or the key is the email address and the value is the display name.
  *
  * @param string $rawAddresses Comma separated list of email addresses (optionally with display name)
  * @return array Parsed list of addresses.
  */
 public static function parseAddresses($rawAddresses)
 {
     /** @var $addressParser \TYPO3\CMS\Core\Mail\Rfc822AddressesParser */
     $addressParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\Rfc822AddressesParser::class, $rawAddresses);
     $addresses = $addressParser->parseAddressList();
     $addressList = array();
     foreach ($addresses as $address) {
         if ($address->mailbox === '') {
             continue;
         }
         if ($address->personal) {
             // item with name found ( name <*****@*****.**> )
             $addressList[$address->mailbox . '@' . $address->host] = $address->personal;
         } else {
             // item without name found ( email@example.org )
             $addressList[] = $address->mailbox . '@' . $address->host;
         }
     }
     return $addressList;
 }
 /**
  * Fixes the SQL mode by unsetting NO_BACKSLASH_ESCAPES if found.
  *
  * @return void
  */
 private function setSqlMode()
 {
     $resource = $this->sql_query('SELECT @@SESSION.sql_mode;');
     if ($resource) {
         $result = $resource->fetch_row();
         if (isset($result[0]) && $result[0] && strpos($result[0], 'NO_BACKSLASH_ESCAPES') !== FALSE) {
             $modes = array_diff(GeneralUtility::trimExplode(',', $result[0]), array('NO_BACKSLASH_ESCAPES'));
             $query = 'SET sql_mode=\'' . $this->db->real_escape_string(implode(',', $modes)) . '\';';
             $this->sql_query($query);
             GeneralUtility::sysLog('NO_BACKSLASH_ESCAPES could not be removed from SQL mode: ' . $this->sql_error(), 'rn_base', GeneralUtility::SYSLOG_SEVERITY_ERROR);
         }
     }
 }
示例#16
0
 /**
  * Sets the class
  *
  * @param string $class
  * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
  */
 public function setClass($class)
 {
     GeneralUtility::logDeprecatedFunction();
     $this->class = $class;
 }
示例#17
0
 /**
  * Prints the memory usage
  */
 public static function printMemorySample()
 {
     static::$backtraceOffset += 1;
     static::debug(sprintf('Memory: %s (max: %s)', GeneralUtility::formatBytes(memory_get_usage(TRUE)), GeneralUtility::formatBytes(memory_get_peak_usage(TRUE))));
     static::$backtraceOffset -= 1;
 }
示例#18
0
    /**
     * Opens a debug message inside a popup window
     *
     * @param mixed $debugVariable
     * @param string $header
     * @param string $group
     */
    public static function debugInPopUpWindow($debugVariable, $header = 'Debug', $group = 'Debug')
    {
        $debugString = self::convertVariableToString($debugVariable);
        $script = '
			(function debug() {
				var debugMessage = ' . GeneralUtility::quoteJSvalue($debugString) . ',
					header = ' . GeneralUtility::quoteJSvalue($header) . ',
					group = ' . GeneralUtility::quoteJSvalue($group) . ',

					browserWindow = function(debug, header, group) {
						var newWindow = window.open("", "TYPO3DebugWindow_" + group,
							"width=600,height=400,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1"
						);
						if (newWindow.document.body.innerHTML) {
							newWindow.document.body.innerHTML = newWindow.document.body.innerHTML +
								"<hr />" + debugMessage;
						} else {
							newWindow.document.writeln(
								"<html><head><title>Debug: " + header + "(" + group + ")</title></head>"
								+ "<body onload=\\"self.focus()\\">"
								+ debugMessage
								+ "</body></html>"
							);
						}
					}

				if (!top.Ext) {
					browserWindow(debugMessage, header, group);
				} else {
					top.Ext.onReady(function() {
						if (top && top.TYPO3 && top.TYPO3.Backend) {
							top.TYPO3.Backend.DebugConsole.openBrowserWindow(header, debugMessage, group);
						} else {
							browserWindow(debugMessage, header, group);
						}
					});
				}
			})();
		';
        echo \TYPO3\CMS\Core\Utility\GeneralUtility::wrapJS($script);
    }
示例#19
0
 /**
  * Sets the search paths from different sources, internal
  *
  * @return array Array of absolute paths (keys and values are equal)
  */
 protected static function getPathsInternal()
 {
     $pathsArr = array();
     $sysPathArr = array();
     // Image magick paths first
     // im_path_lzw take precedence over im_path
     if ($imPath = $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] ? $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] : $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']) {
         $imPath = self::fixPath($imPath);
         $pathsArr[$imPath] = $imPath;
     }
     // Add configured paths
     if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath']) {
         $sysPath = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath'], 1);
         foreach ($sysPath as $val) {
             $val = self::fixPath($val);
             $sysPathArr[$val] = $val;
         }
     }
     // Add path from environment
     // TODO: how does this work for WIN
     if ($GLOBALS['_SERVER']['PATH']) {
         $sep = TYPO3_OS == 'WIN' ? ';' : ':';
         $envPath = GeneralUtility::trimExplode($sep, $GLOBALS['_SERVER']['PATH'], 1);
         foreach ($envPath as $val) {
             $val = self::fixPath($val);
             $sysPathArr[$val] = $val;
         }
     }
     // Set common paths for Unix (only)
     if (TYPO3_OS !== 'WIN') {
         $sysPathArr = array_merge($sysPathArr, array('/usr/bin/' => '/usr/bin/', '/usr/local/bin/' => '/usr/local/bin/'));
     }
     $pathsArr = array_merge($pathsArr, $sysPathArr);
     return $pathsArr;
 }
示例#20
0
 /**
  * Check if php sql.safe_mode is enabled
  *
  * @return boolean TRUE if sql.safe_mode is enabled, FALSE if disabled
  * @deprecated since 6.2, will be removed two versions later
  */
 public static function isSqlSafeModeEnabled()
 {
     GeneralUtility::logDeprecatedFunction();
     return self::getIniValueBoolean('sql.safe_mode');
 }
示例#21
0
 /**
  * Generates an array with abstracted browser information
  *
  * @param string $userAgent The useragent string, \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('HTTP_USER_AGENT')
  * @return array Contains keys "browser", "version", "system
  */
 public static function getBrowserInfo($userAgent)
 {
     // Hook: $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/div/class.t3lib_utility_client.php']['getBrowserInfo']:
     $getBrowserInfoHooks =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/div/class.t3lib_utility_client.php']['getBrowserInfo'];
     if (is_array($getBrowserInfoHooks)) {
         foreach ($getBrowserInfoHooks as $hookFunction) {
             $returnResult = true;
             $hookParameters = ['userAgent' => &$userAgent, 'returnResult' => &$returnResult];
             // need reference for third parameter in \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction,
             // so create a reference to NULL
             $null = null;
             $hookResult = GeneralUtility::callUserFunction($hookFunction, $hookParameters, $null);
             if ($returnResult && is_array($hookResult) && !empty($hookResult)) {
                 return $hookResult;
             }
         }
     }
     $userAgent = trim($userAgent);
     $browserInfo = ['useragent' => $userAgent];
     // Analyze the userAgent string
     // Declare known browsers to look for
     $known = ['msie', 'firefox', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko', 'chrome', 'safari', 'seamonkey', 'navigator', 'mosaic', 'lynx', 'amaya', 'omniweb', 'avant', 'camino', 'flock', 'aol'];
     $matches = [];
     $pattern = '#(?P<browser>' . implode('|', $known) . ')[/ ]+(?P<version>[0-9]+(?:\\.[0-9]+)?)#';
     // Find all phrases (or return empty array if none found)
     if (!preg_match_all($pattern, strtolower($userAgent), $matches)) {
         // Microsoft Internet-Explorer 11 does not have a sign of "MSIE" or so in the useragent.
         // All checks from the pattern above fail here. Look for a special combination of
         // "Mozilla/5.0" in front, "Trident/7.0" in the middle and "like Gecko" at the end.
         // The version (revision) is given as "; rv:11.0" in the useragent then.
         unset($matches);
         $pattern = '#mozilla/5\\.0 \\(.*trident/7\\.0.*; rv:(?P<version>[0-9]+(?:\\.[0-9]+)?)\\) like gecko#i';
         if (preg_match_all($pattern, $userAgent, $matches)) {
             $browserInfo['browser'] = 'msie';
             $browserInfo['version'] = $matches['version'][0];
             $browserInfo['all'] = ['msie' => $matches['version'][0]];
         } else {
             $browserInfo['browser'] = 'unknown';
             $browserInfo['version'] = '';
             $browserInfo['all'] = [];
         }
     } else {
         // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
         // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
         // in the UA).  That's usually the most correct.
         // For IE use the first match as IE sends multiple MSIE with version, from higher to lower.
         $lastIndex = count($matches['browser']) - 1;
         $browserInfo['browser'] = $matches['browser'][$lastIndex];
         $browserInfo['version'] = $browserInfo['browser'] === 'msie' ? $matches['version'][0] : $matches['version'][$lastIndex];
         // But return all parsed browsers / version in an extra array
         $browserInfo['all'] = [];
         for ($i = 0; $i <= $lastIndex; $i++) {
             if (!isset($browserInfo['all'][$matches['browser'][$i]])) {
                 $browserInfo['all'][$matches['browser'][$i]] = $matches['version'][$i];
             }
         }
         // Replace gecko build date with version given by rv
         if (isset($browserInfo['all']['gecko'])) {
             preg_match_all('/rv:([0-9\\.]*)/', strtolower($userAgent), $version);
             if ($version[1][0]) {
                 $browserInfo['all']['gecko'] = $version[1][0];
             }
         }
     }
     $browserInfo['all_systems'] = [];
     if (strstr($userAgent, 'Win')) {
         // Windows
         if (strstr($userAgent, 'Windows NT 6.2') || strstr($userAgent, 'Windows NT 6.3')) {
             $browserInfo['all_systems'][] = 'win8';
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Windows NT 6.1')) {
             $browserInfo['all_systems'][] = 'win7';
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Windows NT 6.0')) {
             $browserInfo['all_systems'][] = 'winVista';
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Windows NT 5.1')) {
             $browserInfo['all_systems'][] = 'winXP';
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Windows NT 5.0')) {
             $browserInfo['all_systems'][] = 'win2k';
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Win98') || strstr($userAgent, 'Windows 98')) {
             $browserInfo['all_systems'][] = 'win98';
         } elseif (strstr($userAgent, 'Win95') || strstr($userAgent, 'Windows 95')) {
             $browserInfo['all_systems'][] = 'win95';
         } elseif (strstr($userAgent, 'WinNT') || strstr($userAgent, 'Windows NT')) {
             $browserInfo['all_systems'][] = 'winNT';
         } elseif (strstr($userAgent, 'Win16') || strstr($userAgent, 'Windows 311')) {
             $browserInfo['all_systems'][] = 'win311';
         }
     } elseif (strstr($userAgent, 'Mac')) {
         if (strstr($userAgent, 'iPad') || strstr($userAgent, 'iPhone') || strstr($userAgent, 'iPod')) {
             $browserInfo['all_systems'][] = 'iOS';
             $browserInfo['all_systems'][] = 'mac';
         } else {
             $browserInfo['all_systems'][] = 'mac';
         }
     } elseif (strstr($userAgent, 'Android')) {
         $browserInfo['all_systems'][] = 'android';
         $browserInfo['all_systems'][] = 'linux';
     } elseif (strstr($userAgent, 'Linux')) {
         $browserInfo['all_systems'][] = 'linux';
     } elseif (strstr($userAgent, 'BSD')) {
         $browserInfo['all_systems'][] = 'unix_bsd';
     } elseif (strstr($userAgent, 'SGI') && strstr($userAgent, ' IRIX ')) {
         $browserInfo['all_systems'][] = 'unix_sgi';
     } elseif (strstr($userAgent, ' SunOS ')) {
         $browserInfo['all_systems'][] = 'unix_sun';
     } elseif (strstr($userAgent, ' HP-UX ')) {
         $browserInfo['all_systems'][] = 'unix_hp';
     } elseif (strstr($userAgent, 'CrOS')) {
         $browserInfo['all_systems'][] = 'chrome';
         $browserInfo['all_systems'][] = 'linux';
     }
     return $browserInfo;
 }
示例#22
0
 /**
  * Explodes the input string into words.
  * This is done by splitting first by lines, then by space char. Each word will be in stored as a value in an array. Lines will be indicated by two subsequent empty values.
  *
  * @param string $str The string input
  * @return array Array with words.
  * @access private
  */
 public function explodeStringIntoWords($str)
 {
     $strArr = GeneralUtility::trimExplode(LF, $str);
     $outArray = array();
     foreach ($strArr as $lineOfWords) {
         $allWords = GeneralUtility::trimExplode(' ', $lineOfWords, TRUE);
         $outArray[] = $allWords;
         $outArray[] = array('');
         $outArray[] = array('');
     }
     return call_user_func_array('array_merge', $outArray);
 }
 /**
  * @param $playlistId
  * @return bool|\Google_Service_YouTube_PlaylistItemListResponse
  */
 public function getPlaylistVideos($playlistId)
 {
     try {
         $result = [];
         if (isset($playlistId)) {
             /** @var \Google_Service_YouTube_PlaylistItemListResponse $playlistItemsResponse */
             $playlistItemsResponse = $this->apiService->playlistItems->listPlaylistItems('snippet,status', array('playlistId' => $playlistId, 'maxResults' => 50));
             $result[] = $playlistItemsResponse;
             $nextPageToken = $playlistItemsResponse->getNextPageToken();
             while ($nextPageToken) {
                 $playlistItemsResponse = $this->apiService->playlistItems->listPlaylistItems('snippet,status', array('playlistId' => $playlistId, 'maxResults' => 50, 'pageToken' => $nextPageToken));
                 $result[] = $playlistItemsResponse;
                 $nextPageToken = $playlistItemsResponse->getNextPageToken();
             }
         }
         $realResult = [];
         foreach ($result as $_ => $collectionItem) {
             foreach ($collectionItem as $item) {
                 $realResult[] = $item;
             }
         }
         /** @var \Google_Service_YouTube_PlaylistItemListResponse $response */
         $response = GeneralUtility::makeInstance(Google_Service_YouTube_PlaylistItemListResponse::class);
         $response->setItems($realResult);
         return $response;
     } catch (\Google_Service_Exception $e) {
         error_log(sprintf('YouTube Playlist Extension: A service error occurred: %s', htmlspecialchars($e->getMessage())));
     } catch (\Google_Exception $e) {
         error_log(sprintf('YouTube Playlist Extension: An client error occurred: %s', htmlspecialchars($e->getMessage())));
     }
     return false;
 }
示例#24
0
 public function enhanceEventQuery(&$select, &$table, &$where, &$groupBy, &$orderBy)
 {
     $select .= ', tx_cal_event_category_mm.uid_foreign AS category_uid ';
     $table .= ' LEFT JOIN tx_cal_event_category_mm ON tx_cal_event_category_mm.uid_local = tx_cal_event.uid';
     $where .= $this->getCategorySearchString($this->conf['pidList'], true);
     $groupBy = 'tx_cal_event.uid';
     if ($this->conf['view.']['joinCategoryByAnd']) {
         $categoryArray = GeneralUtility::trimExplode(',', $this->conf['category'], 1);
         $groupBy .= ', tx_cal_event_category_mm.uid_foreign HAVING count(*) =' . count($categoryArray);
     }
     $orderBy .= ', tx_cal_event.uid,tx_cal_event_category_mm.sorting';
     if ($this->conf['view.'][$this->conf['view'] . '.']['event.']['additionalCategoryWhere']) {
         $where .= ' ' . $this->cObj->cObjGetSingle($this->conf['view.'][$this->conf['view'] . '.']['event.']['additionalCategoryWhere'], $this->conf['view.'][$this->conf['view'] . '.']['event.']['additionalCategoryWhere.']);
     }
 }
示例#25
0
 /**
  * Sends a redirect header response and exits. Additionally the URL is
  * checked and if needed corrected to match the format required for a
  * Location redirect header. By default the HTTP status code sent is
  * a 'HTTP/1.1 303 See Other'.
  *
  * @param string $url The target URL to redirect to
  * @param string $httpStatus An optional HTTP status header. Default is 'HTTP/1.1 303 See Other'
  */
 public static function redirect($url, $httpStatus = self::HTTP_STATUS_303)
 {
     self::setResponseCode($httpStatus);
     header('Location: ' . GeneralUtility::locationHeaderUrl($url));
     die;
 }
 /**
  * Update be_groups with tx_mooxnews_categorymounts set
  *
  * @param string $table
  * @param array $oldNewCategoryUidMapping
  */
 protected function updateCategoryPermissionFields($table, array $oldNewCategoryUidMapping)
 {
     $updatedRecords = 0;
     $rows = $this->databaseConnection->exec_SELECTgetRows('uid, category_perms, tx_mooxnews_categorymounts', $table, "tx_mooxnews_categorymounts != ''");
     foreach ($rows as $row) {
         $oldUids = GeneralUtility::trimExplode(',', $row['tx_mooxnews_categorymounts']);
         $newUids = $row['category_perms'] ? GeneralUtility::trimExplode(',', $row['category_perms']) : array();
         foreach ($oldUids as $oldUid) {
             if (!empty($oldNewCategoryUidMapping[$oldUid])) {
                 $newUids[] = $oldNewCategoryUidMapping[$oldUid];
             }
         }
         $newCategoryPerms = implode(',', array_unique($newUids));
         if ($newCategoryPerms !== $row['category_perms']) {
             $this->databaseConnection->exec_UPDATEquery($table, 'uid=' . $row['uid'], array('category_perms' => $newCategoryPerms));
             $updatedRecords++;
         }
     }
     $message = 'Updated ' . $updatedRecords . ' "' . $table . '" records';
     $status = FlashMessage::INFO;
     $title = '';
     $this->messageArray[] = array($status, $title, $message);
 }