sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function FacebookShareLink() { if (!$this->owner->hasMethod('AbsoluteLink')) { return false; } $pageURL = rawurlencode($this->owner->AbsoluteLink()); return ($pageURL) ? "https://www.facebook.com/sharer/sharer.php?u=$pageURL" : false; }
Generate a URL to share this content on Facebook. @return string|false
entailment
public function TwitterShareLink() { if (!$this->owner->hasMethod('AbsoluteLink')) { return false; } $pageURL = rawurlencode($this->owner->AbsoluteLink()); $text = rawurlencode($this->owner->getOGTitle()); return ($pageURL) ? "https://twitter.com/intent/tweet?text=$text&url=$pageURL" : false; }
Generate a URL to share this content on Twitter Specs: https://dev.twitter.com/web/tweet-button/web-intent. @return string|false
entailment
public function GooglePlusShareLink() { if (!$this->owner->hasMethod('AbsoluteLink')) { return false; } $pageURL = rawurlencode($this->owner->AbsoluteLink()); return ($pageURL) ? "https://plus.google.com/share?url=$pageURL" : false; }
Generate a URL to share this content on Google+ Specs: https://developers.google.com/+/web/snippet/article-rendering. @return string|false
entailment
public function PinterestShareLink() { $pinImage = ($this->owner->hasMethod('getPinterestImage')) ? $this->owner->getPinterestImage() : $this->owner->getOGImage(); if ($pinImage) { // OGImage may be an Image object or an absolute URL $imageURL = rawurlencode((is_string($pinImage)) ? $pinImage : $pinImage->getAbsoluteURL()); $pageURL = rawurlencode($this->owner->AbsoluteLink()); $description = rawurlencode($this->owner->getOGTitle()); // Combine Title, link and image in to rich link return "http://www.pinterest.com/pin/create/button/?url=$pageURL&media=$imageURL&description=$description"; } return false; }
Generate a URL to share this content on Pinterest Specs: https://developers.pinterest.com/pin_it/. @return string|false
entailment
public function LinkedInShareLink() { if (!$this->owner->hasMethod('AbsoluteLink')) { return false; } $pageURL = rawurlencode($this->owner->AbsoluteLink()); $title = rawurlencode($this->owner->getOGTitle()); $description = rawurlencode($this->owner->getOGDescription()); $source = rawurlencode($this->owner->getOGSiteName()); return "https://www.linkedin.com/shareArticle?mini=true&url=$pageURL&title=$title&summary=$description&source=$source"; }
Generate a URL to share this content on LinkedIn specs: https://developer.linkedin.com/docs/share-on-linkedin @return string|string
entailment
public function EmailShareLink() { if (!$this->owner->hasMethod('AbsoluteLink')) { return false; } $pageURL = $this->owner->AbsoluteLink(); $subject = rawurlencode(_t('JonoM\ShareCare\ShareCare.EmailSubject', 'Thought you might like this')); $body = rawurlencode(_t('JonoM\ShareCare\ShareCare.EmailBody', 'Thought of you when I found this: {URL}', array('URL' => $pageURL))); return ($pageURL) ? "mailto:?subject=$subject&body=$body" : false; }
Generate a 'mailto' URL to share this content via Email. @return string|false
entailment
public function getTwitterMetaTags() { $title = htmlspecialchars($this->owner->getOGTitle()); $description = htmlspecialchars($this->owner->getOGDescription()); $tMeta = "\n<meta name=\"twitter:title\" content=\"$title\">" . "\n<meta name=\"twitter:description\" content=\"$description\">"; // If we have a big enough image, include an image tag. $image = $this->owner->getOGImage(); // $image may be a string - don't generate a specific twitter tag // in that case as it is probably the default resource. if ($image instanceof Image && $image->getWidth() >= 280) { $imageURL = htmlspecialchars(Director::absoluteURL($image->Link())); $tMeta .= "\n<meta name=\"twitter:card\" content=\"summary_large_image\">" . "\n<meta name=\"twitter:image\" content=\"$imageURL\">"; } $username = self::config()->get('twitter_username'); if ($username) { $tMeta .= "\n<meta name=\"twitter:site\" content=\"@$username\">" . "\n<meta name=\"twitter:creator\" content=\"@$username\">"; } return $tMeta; }
Generate meta tag markup for Twitter Cards Specs: https://dev.twitter.com/cards/types/summary-large-image. @return string
entailment
public function build(InvokeSpec $call): string { $response = []; $units = $call->getUnits(); foreach ($units as $invoke) { /** @var Invoke $invoke */ $invoke = $this->preBuild($invoke); $response[] = [ 'jsonrpc' => '2.0', 'method' => $invoke->getRawMethod(), 'params' => $invoke->getRawParams(), 'id' => $invoke->getRawId() ]; } if ($call->isSingleCall()) { return json_encode($response[0]); } return json_encode($response); }
@param InvokeSpec $call @return string
entailment
private function preBuild(AbstractInvoke $invoke): AbstractInvoke { $result = $this->preBuild->handle(new BuilderContainer($this, $invoke)); if ($result instanceof BuilderContainer) { return $result->getInvoke(); } throw new \RuntimeException(); }
@param AbstractInvoke $invoke @return AbstractInvoke
entailment
public function generateScreenTopResolution($VisitorsID,$limit=20) { $arrScreenStatCount = false; $this->TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_screentopresolution'); $objScreenStatCount = \Database::getInstance() ->prepare("SELECT `v_s_w`, `v_s_h`, `v_s_iw`, `v_s_ih`, SUM(`v_screen_counter`) AS v_screen_sum FROM `tl_visitors_screen_counter` WHERE `vid` = ? GROUP BY `v_s_w`, `v_s_h`, `v_s_iw`, `v_s_ih` ORDER BY v_screen_sum DESC ") ->limit($limit) ->execute($VisitorsID); while ($objScreenStatCount->next()) { $arrScreenStatCount[] = array ( 'v_s_width' => $objScreenStatCount->v_s_w, 'v_s_height' => $objScreenStatCount->v_s_h, 'v_s_iwidth' => $objScreenStatCount->v_s_iw, 'v_s_iheight' => $objScreenStatCount->v_s_ih, 'v_screen_sum' => $objScreenStatCount->v_screen_sum ); } $this->TemplatePartial->ScreenTopResolution = $arrScreenStatCount; return $this->TemplatePartial->parse(); }
////////////////////////////////////////////////////////////
entailment
public function beforeTraverse(array $nodes) : array { // quick fix - if the list is empty, replace it it if (! $nodes) { return (new ParserFactory()) ->create(ParserFactory::PREFER_PHP7) ->parse(file_get_contents($this->reflectedClass->getFileName())); } return $nodes; }
{@inheritDoc} @param array $nodes @return \PhpParser\Node[]
entailment
public function request(string $request): string { $request = $this->preRequest($request); return $this->send($request); }
Execute request @param string $request @return string
entailment
private function preRequest(string $request): string { $result = $this->preRequest->handle(new TransportContainer($this, $request)); if ($result instanceof TransportContainer) { return $result->getRequest(); } throw new \RuntimeException(); }
@param string $request @return string
entailment
public function getUserClassName(string $className) : string { if (false === $position = strrpos($className, $this->generatedClassMarker)) { return $className; } return substr( $className, $this->generatedClassMarkerLength + $position, strrpos($className, '\\') - ($position + $this->generatedClassMarkerLength) ); }
{@inheritDoc}
entailment
public function getGeneratedClassName(string $className, array $options = array()) : string { return $this->generatedClassesNamespace . $this->generatedClassMarker . $this->getUserClassName($className) . '\\' . $this->parameterEncoder->encodeParameters($options); }
{@inheritDoc}
entailment
public static function logMessage($strMessage, $strLog=null) { if ($strLog === null) { $strLog = 'prod-' . date('Y-m-d') . '.log'; } else { $strLog = 'prod-' . date('Y-m-d') . '-' . $strLog . '.log'; } $strLogsDir = null; if (($container = \System::getContainer()) !== null) { $strLogsDir = $container->getParameter('kernel.logs_dir'); } if (!$strLogsDir) { $strLogsDir = TL_ROOT . '/var/logs'; } error_log(sprintf("[%s] %s\n", date('d-M-Y H:i:s'), $strMessage), 3, $strLogsDir . '/' . $strLog); }
Wrapper for old log_message @param string $strMessage @param string $strLogg
entailment
public static function useSocks5($host, $port = 1080, $user = null, $pass = null) { if ($host === null) { self::$_socks5 = []; } else { self::$_socks5 = ['conn' => 'tcp://' . $host . ':' . $port]; if ($user !== null && $pass !== null) { self::$_socks5['user'] = $user; self::$_socks5['pass'] = $pass; } } }
Set socks5 proxy server @param string $host proxy server address, passed null to disable @param int $port proxy server port, default to 1080 @param string $user authentication username @param string $pass authentication password
entailment
public static function connect($conn, $arg = null) { $obj = null; if (!isset(self::$_objs[$conn])) { self::$_objs[$conn] = []; } foreach (self::$_objs[$conn] as $tmp) { if (!($tmp->flag & self::FLAG_BUSY)) { Client::debug('reuse conn \'', $tmp->conn, '\': ', $tmp->sock); $obj = $tmp; break; } } if ($obj === null && count(self::$_objs[$conn]) < Client::$maxBurst) { $obj = new self($conn); self::$_objs[$conn][] = $obj; Client::debug('create conn \'', $conn, '\''); } if ($obj !== null) { $obj->arg = $arg; if ($obj->flag & self::FLAG_OPENED) { $obj->flag |= self::FLAG_REUSED; } else { if (!$obj->openSock()) { return false; } } $obj->flag |= self::FLAG_BUSY; $obj->outBuf = null; $obj->outLen = 0; } return $obj; }
Create connection, with built-in pool. @param string $conn connection string, like `protocal://host:port`. @param mixed $arg external argument, fetched by `[[getExArg()]]` @return static the connection object, null if it reaches the upper limit of concurrent, or false on failure.
entailment
public static function findBySock($sock) { $sock = strval($sock); return isset(self::$_refs[$sock]) ? self::$_refs[$sock] : null; }
Find connection object by socket, used after stream_select() @param resource $sock @return Connection the connection object or null if not found.
entailment
public function close($realClose = false) { $this->arg = null; $this->flag &= ~self::FLAG_BUSY; if ($realClose === true) { Client::debug('close conn \'', $this->conn, '\': ', $this->sock); $this->flag &= ~self::FLAG_OPENED; @fclose($this->sock); $this->delSockRef(); $this->sock = false; } else { Client::debug('free conn \'', $this->conn, '\': ', $this->sock); } }
Close the connection @param boolean $realClose whether to shutdown the connection, default is added to the pool for next request.
entailment
public function addWriteData($buf) { if ($this->outBuf === null) { $this->outBuf = $buf; } else { $this->outBuf .= $buf; } }
Append writing cache @param $buf string data content.
entailment
public function write($buf = null) { if ($buf === null) { if ($this->proxyState > 0) { return $this->proxyWrite(); } $len = 0; if ($this->hasDataToWrite()) { $buf = $this->outLen > 0 ? substr($this->outBuf, $this->outLen) : $this->outBuf; $len = $this->write($buf); if ($len !== false) { $this->outLen += $len; } } return $len; } $n = @fwrite($this->sock, $buf); if ($n === 0 && $this->ioEmptyError()) { $n = false; } $this->ioFlagReset(); return $n; }
Write data to socket @param string $buf the string to be written, passing null to flush cache. @return mixed the number of bytes were written, 0 if the buffer is full, or false on error.
entailment
public function getLine() { $line = @stream_get_line($this->sock, 2048, "\n"); if ($line === '' || $line === false) { $line = $this->ioEmptyError() ? false : null; } else { $line = rtrim($line, "\r"); } $this->ioFlagReset(); return $line; }
Read one line (not contains \r\n at the end) @return mixed line string, null when has not data, or false on error.
entailment
public function read($size = 8192) { $buf = @fread($this->sock, $size); if ($buf === '' || $buf === false) { $buf = $this->ioEmptyError() ? false : null; } $this->ioFlagReset(); return $buf; }
Read data from socket @param int $size the max number of bytes to be read. @return mixed the read string, null when has not data, or false on error.
entailment
public function proxyRead() { $proxyState = $this->proxyState; Client::debug('proxy readState: ', $proxyState); if ($proxyState === 2) { $buf = $this->read(2); if ($buf === "\x05\x00") { $this->proxyState = 5; } elseif ($buf === "\x05\x02") { $this->proxyState = 3; } } elseif ($proxyState === 4) { $buf = $this->read(2); if ($buf === "\x01\x00") { $this->proxyState = 5; } } elseif ($proxyState === 6) { $buf = $this->read(10); if (substr($buf, 0, 4) === "\x05\x00\x00\x01") { $this->proxyState = 0; } } return $proxyState !== $this->proxyState; }
Read data for proxy communication
entailment
public function proxyWrite() { Client::debug('proxy writeState: ', $this->proxyState); if ($this->proxyState === 1) { $buf = isset(self::$_socks5['user']) ? "\x05\x01\x02" : "\x05\x01\x00"; $this->proxyState++; return $this->write($buf); } elseif ($this->proxyState === 3) { if (!isset(self::$_socks5['user'])) { return false; } $buf = chr(0x01) . chr(strlen(self::$_socks5['user'])) . self::$_socks5['user'] . chr(strlen(self::$_socks5['pass'])) . self::$_socks5['pass']; $this->proxyState++; return $this->write($buf); } elseif ($this->proxyState === 5) { $pa = parse_url($this->conn); $buf = "\x05\x01\x00\x01" . pack('Nn', ip2long($pa['host']), isset($pa['port']) ? $pa['port'] : 80); $this->proxyState++; return $this->write($buf); } else { return false; } }
Write data for proxy communication @return mixed
entailment
public function generateNewsVisitHitTop($VisitorsID, $limit = 10, $parse = true) { $arrNewsStatCount = false; //News Tables exists? if (true === $this->getNewstableexists()) { $objNewsStatCount = \Database::getInstance() ->prepare("SELECT visitors_page_id, visitors_page_lang, SUM(visitors_page_visit) AS visitors_page_visits, SUM(visitors_page_hit) AS visitors_page_hits FROM tl_visitors_pages WHERE vid = ? AND visitors_page_type = ? GROUP BY visitors_page_id, visitors_page_lang ORDER BY visitors_page_visits DESC, visitors_page_hits DESC, visitors_page_id, visitors_page_lang ") ->limit($limit) ->execute($VisitorsID, self::PAGE_TYPE_NEWS); while ($objNewsStatCount->next()) { $alias = false; $aliases = $this->getNewsAliases($objNewsStatCount->visitors_page_id); if (false !== $aliases['PageAlias']) { $alias = $aliases['PageAlias'] .'/'. $aliases['NewsAlias']; } if (false !== $alias) { $arrNewsStatCount[] = array ( 'title' => $aliases['NewsArchivTitle'], 'alias' => $alias, 'lang' => $objNewsStatCount->visitors_page_lang, 'visits' => $objNewsStatCount->visitors_page_visits, 'hits' => $objNewsStatCount->visitors_page_hits ); } } if ($parse === true) { /* @var $TemplatePartial Template */ $TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_newsvisithittop'); $TemplatePartial->NewsVisitHitTop = $arrNewsStatCount; return $TemplatePartial->parse(); } return $arrNewsStatCount; } return false; }
////////////////////////////////////////////////////////////
entailment
public function enterNode(Node $node) { if ($node instanceof Namespace_) { $this->currentNamespace = $node; return $node; } return null; }
@param \PhpParser\Node $node @return \PhpParser\Node\Stmt\Namespace_|null
entailment
public function leaveNode(Node $node) { if ($node instanceof Namespace_) { $this->currentNamespace = null; } if ($node instanceof Class_) { $namespace = ($this->currentNamespace && is_array($this->currentNamespace->name->parts)) ? implode('\\', $this->currentNamespace->name->parts) : ''; if (trim($namespace . '\\' . (string)$node->name, '\\') === $this->matchedClassFQCN) { $node->extends = new FullyQualified($this->newParentClassFQCN); } return $node; } return null; }
{@inheritDoc} When leaving a node that is a class, replaces it with a modified version that extends the given parent class @todo can be abstracted away into a visitor that allows to modify the node via a callback @param \PhpParser\Node $node @return \PhpParser\Node\Stmt\Class_|null
entailment
protected function newBaseQueryBuilder() { $conn = $this->getConnection(); $grammar = $conn->getQueryGrammar(); return new QueryCacheBuilder($this->queryCache(), $conn, $grammar, $conn->getPostProcessor()); }
Overrides the default QueryBuilder to inject the Cache methods. @return QueryCacheBuilder
entailment
public function finishSave(array $options) { if ($this->getCacheBusting()) { $this->queryCache()->flush($this->getTable()); } parent::finishSave($options); }
Flushes the cache on insert/update. @param array $options @return void
entailment
public function delete() { if ($this->getCacheBusting()) { $this->queryCache()->flush($this->getTable()); } return parent::delete(); }
Flushes the cache on deletes. @return bool|null
entailment
public function invoke($object, string $method, array $parameters) { $handler = $object; $reflection = new \ReflectionMethod($handler, $method); if ($reflection->getNumberOfRequiredParameters() > count($parameters)) { throw new InvalidParamsException('Expected ' . $reflection->getNumberOfRequiredParameters() . ' parameters'); } $formalParameters = $reflection->getParameters(); $actualParameters = $this->prepareActualParameters($formalParameters, $parameters); try { $result = $reflection->invokeArgs($handler, $actualParameters); } catch (\Exception $exception) { throw new ServerErrorException($exception->getMessage(), $exception->getCode()); } return $this->castResult($result); }
@param mixed $object @param string $method @param array $parameters @return mixed
entailment
private function prepareActualParameters(array $formalParameters, array $parameters): array { $result = []; // Handle named parameters if ($this->isNamedArray($parameters)) { foreach ($formalParameters as $formalParameter) { /** @var \ReflectionParameter $formalParameter */ $formalType = (string) $formalParameter->getType(); $name = $formalParameter->name; if ($formalParameter->isOptional()) { if (!array_key_exists($name, $parameters)) { $result[$name] = $formalParameter->getDefaultValue(); continue; } if ($formalParameter->allowsNull() && $parameters[$name] === null) { $result[$name] = $parameters[$name]; continue; } $result[$name] = $formalParameter->getClass() !== null ? $this->toObject($formalParameter->getClass()->name, $parameters[$name]) : $this->matchType($formalType, $parameters[$name]); } if (!array_key_exists($name, $parameters)) { throw new InvalidParamsException('Named parameter error'); } $result[$name] = $this->matchType($formalType, $parameters[$name]); } return $result; } // Handle positional parameters foreach ($formalParameters as $position => $formalParameter) { /** @var \ReflectionParameter $formalParameter */ if ($formalParameter->isOptional() && !isset($parameters[$position])) { break; } if (!isset($parameters[$position])) { throw new InvalidParamsException('Positional parameter error'); } $formalType = (string) $formalParameter->getType(); $result[] = $formalParameter->getClass() !== null ? $this->toObject($formalParameter->getClass()->name, $parameters[$position]) : $this->matchType($formalType, $parameters[$position]); } return $result; }
@param \ReflectionParameter[] $formalParameters Formal parameters @param array $parameters Parameters from request (raw) @return array
entailment
private function matchType(string $formalType, $value) { // Parameter without type-hinting returns as is if ($formalType === '') { return $value; } if ($this->isType($formalType, $value)) { return $value; } throw new InvalidParamsException('Type hint failed'); }
@param string $formalType @param mixed $value @return mixed
entailment
private function toObject(string $formalClass, $value) { if ($this->typeAdapter->isClassRegistered($formalClass)) { try { return $this->typeAdapter->toObject($value); } catch (TypeCastException $exception) { throw new InvalidParamsException('Class cast failed'); } } throw new InvalidParamsException('Class hint failed'); }
@param string $formalClass @param mixed $value @return mixed
entailment
private function isType(string $type, $value) { switch ($type) { case 'bool': return is_bool($value); case 'int': return is_int($value); case 'float': return is_float($value) || is_int($value); case 'string': return is_string($value); case 'array': return is_array($value); default: throw new InvalidParamsException('Type match error'); } }
@param string $type @param $value @return bool
entailment
private function castResult($result) { try { $result = $this->typeAdapter->toArray($result); } catch (TypeCastException $exception) { return $result; } return $result; }
@param $result @return mixed
entailment
public function replaceInsertTagsVisitors($strTag) { $arrTag = StringUtil::trimsplit('::', $strTag); if ($arrTag[0] != 'visitors') { if ($arrTag[0] != 'cache_visitors') { return false; // nicht für uns } } \System::loadLanguageFile('tl_visitors'); if (isset($arrTag[1])) { $visitors_category_id = (int)$arrTag[1]; //Get Debug Settings $this->visitorSetDebugSettings($visitors_category_id); } if (false === self::$_BackendUser && true === $this->isContao45()) { $objTokenChecker = \System::getContainer()->get('contao.security.token_checker'); if ($objTokenChecker->hasBackendUser()) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': BackendUser: Yes' ); self::$_BackendUser = true; } else { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': BackendUser: No' ); } } if (!isset($arrTag[2])) { \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['no_key'], array('contao' => new ContaoContext('ModulVisitors ReplaceInsertTags '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); return false; // da fehlt was } if ($arrTag[2] == 'count') { /* __________ __ ___ _____________ ________ / ____/ __ \/ / / / | / /_ __/ _/ | / / ____/ / / / / / / / / / |/ / / / / // |/ / / __ / /___/ /_/ / /_/ / /| / / / _/ // /| / /_/ / \____/\____/\____/_/ |_/ /_/ /___/_/ |_/\____/ only */ ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitors = \Database::getInstance() ->prepare("SELECT tl_visitors.id AS id, visitors_block_time FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid) WHERE pid=? AND published=? ORDER BY id, visitors_name") ->limit(1) ->execute($visitors_category_id,1); if ($objVisitors->numRows < 1) { \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['wrong_katid'], array('contao' => new ContaoContext('ModulVisitors ReplaceInsertTags '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); return false; } while ($objVisitors->next()) { $this->visitorCountUpdate($objVisitors->id, $objVisitors->visitors_block_time, $visitors_category_id, self::$_BackendUser); $this->visitorCheckSearchEngine($objVisitors->id); ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , 'BOT: '.(int) $this->_BOT); ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , 'SE : '.(int) $this->_SE); if ($this->_BOT === false && $this->_SE === false) { $this->visitorCheckReferrer($objVisitors->id); } } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , 'Counted Server: True' ); return '<!-- counted -->'; } /* ____ __ ____________ __ ________ / __ \/ / / /_ __/ __ \/ / / /_ __/ / / / / / / / / / / /_/ / / / / / / / /_/ / /_/ / / / / ____/ /_/ / / / \____/\____/ /_/ /_/ \____/ /_/ */ $objVisitors = \Database::getInstance() ->prepare("SELECT tl_visitors.id AS id, visitors_name, visitors_startdate, visitors_visit_start, visitors_hit_start, visitors_average, visitors_thousands_separator FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid) WHERE pid=? AND published=? ORDER BY id, visitors_name") ->limit(1) ->execute($visitors_category_id,1); if ($objVisitors->numRows < 1) { \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['wrong_katid'], array('contao' => new ContaoContext('ModulVisitors ReplaceInsertTags '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); return false; } $objVisitors->next(); $boolSeparator = ($objVisitors->visitors_thousands_separator == 1) ? true : false; switch ($arrTag[2]) { case "name": ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); return trim($objVisitors->visitors_name); break; case "online": //VisitorsOnlineCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsOnlineCount = \Database::getInstance() ->prepare("SELECT COUNT(id) AS VOC FROM tl_visitors_blocker WHERE vid=? AND visitors_type=?") ->execute($objVisitors->id,'v'); $objVisitorsOnlineCount->next(); $VisitorsOnlineCount = ($objVisitorsOnlineCount->VOC === null) ? 0 : $objVisitorsOnlineCount->VOC; return ($boolSeparator) ? $this->getFormattedNumber($VisitorsOnlineCount,0) : $VisitorsOnlineCount; break; case "start": //VisitorsStartDate ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); if (!strlen($objVisitors->visitors_startdate)) { $VisitorsStartDate = ''; } else { global $objPage; $VisitorsStartDate = \Date::parse($objPage->dateFormat, $objVisitors->visitors_startdate); } return $VisitorsStartDate; break; case "totalvisit": //TotalVisitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsTotalCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV FROM tl_visitors_counter WHERE vid=?") ->execute($objVisitors->id); $VisitorsTotalVisitCount = $objVisitors->visitors_visit_start; //startwert if ($objVisitorsTotalCount->numRows > 0) { $objVisitorsTotalCount->next(); $VisitorsTotalVisitCount += ($objVisitorsTotalCount->SUMV === null) ? 0 : $objVisitorsTotalCount->SUMV; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsTotalVisitCount,0) : $VisitorsTotalVisitCount; break; case "totalhit": //TotalHitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsTotalCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_hit) AS SUMH FROM tl_visitors_counter WHERE vid=?") ->execute($objVisitors->id); $VisitorsTotalHitCount = $objVisitors->visitors_hit_start; //startwert if ($objVisitorsTotalCount->numRows > 0) { $objVisitorsTotalCount->next(); $VisitorsTotalHitCount += ($objVisitorsTotalCount->SUMH === null) ? 0 : $objVisitorsTotalCount->SUMH; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsTotalHitCount,0) : $VisitorsTotalHitCount; break; case "todayvisit": //TodaysVisitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsTodaysCount = \Database::getInstance() ->prepare("SELECT visitors_visit FROM tl_visitors_counter WHERE vid=? AND visitors_date=?") ->execute($objVisitors->id,date('Y-m-d')); if ($objVisitorsTodaysCount->numRows < 1) { $VisitorsTodaysVisitCount = 0; } else { $objVisitorsTodaysCount->next(); $VisitorsTodaysVisitCount = ($objVisitorsTodaysCount->visitors_visit === null) ? 0 : $objVisitorsTodaysCount->visitors_visit; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsTodaysVisitCount,0) : $VisitorsTodaysVisitCount; break; case "todayhit": //TodaysHitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsTodaysCount = \Database::getInstance() ->prepare("SELECT visitors_hit FROM tl_visitors_counter WHERE vid=? AND visitors_date=?") ->execute($objVisitors->id,date('Y-m-d')); if ($objVisitorsTodaysCount->numRows < 1) { $VisitorsTodaysHitCount = 0; } else { $objVisitorsTodaysCount->next(); $VisitorsTodaysHitCount = ($objVisitorsTodaysCount->visitors_hit === null) ? 0 : $objVisitorsTodaysCount->visitors_hit; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsTodaysHitCount,0) : $VisitorsTodaysHitCount; break; case "yesterdayvisit": //YesterdayVisitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsYesterdayCount = \Database::getInstance() ->prepare("SELECT visitors_visit FROM tl_visitors_counter WHERE vid=? AND visitors_date=?") ->execute($objVisitors->id,date('Y-m-d', strtotime( '-1 days' ) )); if ($objVisitorsYesterdayCount->numRows < 1) { $VisitorsYesterdayVisitCount = 0; } else { $objVisitorsYesterdayCount->next(); $VisitorsYesterdayVisitCount = ($objVisitorsYesterdayCount->visitors_visit === null) ? 0 : $objVisitorsYesterdayCount->visitors_visit; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsYesterdayVisitCount,0) : $VisitorsYesterdayVisitCount; break; case "yesterdayhit": //YesterdayHitCount ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); $objVisitorsYesterdayCount = \Database::getInstance() ->prepare("SELECT visitors_hit FROM tl_visitors_counter WHERE vid=? AND visitors_date=?") ->execute($objVisitors->id,date('Y-m-d', strtotime( '-1 days' ) )); if ($objVisitorsYesterdayCount->numRows < 1) { $VisitorsYesterdayHitCount = 0; } else { $objVisitorsYesterdayCount->next(); $VisitorsYesterdayHitCount = ($objVisitorsYesterdayCount->visitors_hit === null) ? 0 : $objVisitorsYesterdayCount->visitors_hit; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsYesterdayHitCount,0) : $VisitorsYesterdayHitCount; break; case "averagevisits": // Average Visits ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); if ($objVisitors->visitors_average) { $today = date('Y-m-d'); $yesterday = date('Y-m-d',mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); $objVisitorsAverageCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV, MIN( visitors_date ) AS MINDAY FROM tl_visitors_counter WHERE vid=? AND visitors_date<?") ->execute($objVisitors->id,$today); if ($objVisitorsAverageCount->numRows > 0) { $objVisitorsAverageCount->next(); $tmpTotalDays = floor( (strtotime($yesterday) - strtotime($objVisitorsAverageCount->MINDAY))/60/60/24 ); $VisitorsAverageVisitCount = ($objVisitorsAverageCount->SUMV === null) ? 0 : $objVisitorsAverageCount->SUMV; if ($tmpTotalDays > 0) { $VisitorsAverageVisits = round($VisitorsAverageVisitCount / $tmpTotalDays , 0); } else { $VisitorsAverageVisits = 0; } } } else { $VisitorsAverageVisits = 0; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsAverageVisits,0) : $VisitorsAverageVisits; break; case "pagehits": // Page Hits ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); //Page Data global $objPage; //if page from cache, we have no page-id if ($objPage->id == 0) { $objPage = $this->visitorGetPageObj(); } //$objPage->id == 0 $objPageStatCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_page_hit) AS visitors_page_hits FROM tl_visitors_pages WHERE vid = ? AND visitors_page_id = ? ") ->execute($objVisitors->id, $objPage->id); if ($objPageStatCount->numRows > 0) { $objPageStatCount->next(); $VisitorsPageHits = $objPageStatCount->visitors_page_hits; } else { $VisitorsPageHits = 0; } return ($boolSeparator) ? $this->getFormattedNumber($VisitorsPageHits,0) : $VisitorsPageHits; break; case "bestday": //Day with the most visitors ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2] ); if (!isset($arrTag[3])) { \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['no_param4'], array('contao' => new ContaoContext('ModulVisitors ReplaceInsertTags '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , $GLOBALS['TL_LANG']['tl_visitors']['no_param4'] ); return false; // da fehlt was } $objVisitorsBestday = \Database::getInstance() ->prepare("SELECT visitors_date, visitors_visit, visitors_hit FROM tl_visitors_counter WHERE vid=? ORDER BY visitors_visit DESC, visitors_hit DESC") ->limit(1) ->execute($objVisitors->id); if ($objVisitorsBestday->numRows > 0) { $objVisitorsBestday->next(); } switch ($arrTag[3]) { case "date": ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2].'::'.$arrTag[3] ); if (!isset($arrTag[4])) { return date($GLOBALS['TL_CONFIG']['dateFormat'],strtotime($objVisitorsBestday->visitors_date)); } else { return date($arrTag[4],strtotime($objVisitorsBestday->visitors_date)); } break; case "visits": ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2].'::'.$arrTag[3] ); return ($boolSeparator) ? $this->getFormattedNumber($objVisitorsBestday->visitors_visit,0) : $objVisitorsBestday->visitors_visit; break; case "hits": ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$arrTag[2].'::'.$arrTag[3] ); return ($boolSeparator) ? $this->getFormattedNumber($objVisitorsBestday->visitors_hit,0) : $objVisitorsBestday->visitors_hit; break; default: return false; break; } break; default: ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':' .$GLOBALS['TL_LANG']['tl_visitors']['wrong_key'] ); \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['wrong_key'], array('contao' => new ContaoContext('ModulVisitors ReplaceInsertTags '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); return false; break; } }
replaceInsertTags From TL 2.8 you can use prefix "cache_". Thus the InserTag will be not cached. (when "cache" is enabled) visitors::katid::name - VisitorsName visitors::katid::online - VisitorsOnlineCount visitors::katid::start - VisitorsStartDate visitors::katid::totalvisit - TotalVisitCount visitors::katid::totalhit - TotalHitCount visitors::katid::todayvisit - TodayVisitCount visitors::katid::todayhit - TodayHitCount visitors::katid::yesterdayvisit - YesterdayVisitCount visitors::katid::yesterdayhit - YesterdayHitCount visitors::katid::averagevisits - AverageVisits visitors::katid::pagehits - PageHits cache_visitors::katid::count - Counting (only) Not used in the templates: visitors::katid::bestday::date - Day (Date) with the most visitors visitors::katid::bestday::visits - Visits of the day with the most visitors visitors::katid::bestday::hits - Hits of the day with the most visitors! (not hits!) @param string $strTag @return bool / string
entailment
protected function visitorCountUpdate($vid, $BlockTime, $visitors_category_id, $BackendUser = false) { $ModuleVisitorChecks = new ModuleVisitorChecks($BackendUser); if (!isset($GLOBALS['TL_CONFIG']['mod_visitors_bot_check']) || $GLOBALS['TL_CONFIG']['mod_visitors_bot_check'] !== false) { if ($ModuleVisitorChecks->checkBot() === true) { $this->_BOT = true; return; //Bot / IP gefunden, wird nicht gezaehlt } } if ($ModuleVisitorChecks->checkUserAgent($visitors_category_id) === true) { $this->_PF = true; // Bad but functionally return ; //User Agent Filterung } //Debug log_message("visitorCountUpdate count: ".$this->Environment->httpUserAgent,"useragents-noblock.log"); $ClientIP = bin2hex(sha1($visitors_category_id . $ModuleVisitorChecks->visitorGetUserIP(),true)); // sha1 20 Zeichen, bin2hex 40 zeichen $BlockTime = ($BlockTime == '') ? 1800 : $BlockTime; //Sekunden $CURDATE = date('Y-m-d'); //Visitor Blocker \Database::getInstance() ->prepare("DELETE FROM tl_visitors_blocker WHERE CURRENT_TIMESTAMP - INTERVAL ? SECOND > visitors_tstamp AND vid = ? AND visitors_type = ?") ->execute($BlockTime, $vid, 'v'); //Hit Blocker for IE8 Bullshit and Browser Counting \Database::getInstance() ->prepare("DELETE FROM tl_visitors_blocker WHERE CURRENT_TIMESTAMP - INTERVAL ? SECOND > visitors_tstamp AND vid = ? AND visitors_type = ?") ->execute(3, $vid, 'h'); // 3 Sekunden Blockierung zw. Zählung per Tag und Zählung per Browser if ($ModuleVisitorChecks->checkBE() === true) { $this->_PF = true; // Bad but functionally return; // Backend eingeloggt, nicht zaehlen (Feature: #197) } //Test ob Hits gesetzt werden muessen (IE8 Bullshit and Browser Counting) $objHitIP = \Database::getInstance() ->prepare("SELECT id, visitors_ip FROM tl_visitors_blocker WHERE visitors_ip = ? AND vid = ? AND visitors_type = ?") ->execute($ClientIP, $vid, 'h'); //Hits und Visits lesen $objHitCounter = \Database::getInstance() ->prepare("SELECT id, visitors_hit, visitors_visit FROM tl_visitors_counter WHERE visitors_date = ? AND vid = ?") ->execute($CURDATE, $vid); //Hits setzen if ($objHitCounter->numRows < 1) { if ($objHitIP->numRows < 1) { //at first: block \Database::getInstance() ->prepare("INSERT INTO tl_visitors_blocker SET vid = ?, visitors_tstamp=CURRENT_TIMESTAMP, visitors_ip = ?, visitors_type = ?") ->execute($vid, $ClientIP, 'h'); // Insert $arrSet = array ( 'vid' => $vid, 'visitors_date' => $CURDATE, 'visitors_visit' => 1, 'visitors_hit' => 1 ); \Database::getInstance() ->prepare("INSERT IGNORE INTO tl_visitors_counter %s") ->set($arrSet) ->execute(); //for page counter $this->_HitCounted = true; } else { $this->_PF = true; // Prefetch found } $visitors_hits=1; $visitors_visit=1; } else { $objHitCounter->next(); $visitors_hits = $objHitCounter->visitors_hit +1; $visitors_visit= $objHitCounter->visitors_visit +1; if ($objHitIP->numRows < 1) { // Update \Database::getInstance() ->prepare("INSERT INTO tl_visitors_blocker SET vid = ?, visitors_tstamp=CURRENT_TIMESTAMP, visitors_ip = ?, visitors_type = ?") ->execute($vid, $ClientIP, 'h'); \Database::getInstance() ->prepare("UPDATE tl_visitors_counter SET visitors_hit=? WHERE id=?") ->execute($visitors_hits, $objHitCounter->id); //for page counter $this->_HitCounted = true; } else { $this->_PF = true; // Prefetch found } } //Visits / IP setzen $objVisitIP = \Database::getInstance() ->prepare("SELECT id, visitors_ip FROM tl_visitors_blocker WHERE visitors_ip = ? AND vid = ? AND visitors_type = ?") ->execute($ClientIP, $vid, 'v'); if ($objVisitIP->numRows < 1) { // not blocked: Insert IP + Update Visits \Database::getInstance() ->prepare("INSERT INTO tl_visitors_blocker SET vid = ?, visitors_tstamp = CURRENT_TIMESTAMP, visitors_ip = ?, visitors_type = ?") ->execute($vid, $ClientIP, 'v'); \Database::getInstance() ->prepare("UPDATE tl_visitors_counter SET visitors_visit = ? WHERE visitors_date = ? AND vid = ?") ->execute($visitors_visit, $CURDATE, $vid); //for page counter $this->_VisitCounted = true; } else { // blocked: Update tstamp \Database::getInstance() ->prepare("UPDATE tl_visitors_blocker SET visitors_tstamp = CURRENT_TIMESTAMP WHERE visitors_ip = ? AND vid = ? AND visitors_type = ?") ->execute($ClientIP, $vid, 'v'); $this->_VB = true; } //Page Counter if ($this->_HitCounted === true || $this->_VisitCounted === true) { global $objPage; //if page from cache, we have no page-id if ($objPage->id == 0) { $objPage = $this->visitorGetPageObj(); } //$objPage->id == 0 ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Page ID / Lang in Object: '. $objPage->id .' / '.$objPage->language); //#102, bei Readerseite den Beitrags-Alias zählen (Parameter vorhanden) //0 = reale Seite / 404 / Reader ohne Parameter - Auflistung der News/FAQs //1 = Nachrichten/News //2 = FAQ //3 = Isotope //403 = Forbidden $visitors_page_type = $this->visitorGetPageType($objPage); //bei News/FAQ id des Beitrags ermitteln und $objPage->id ersetzen //Fixed #211, Duplicate entry in tl_search $objPageIdOrg = $objPage->id; $objPageId = $this->visitorGetPageIdByType($objPage->id, $visitors_page_type, $objPage->alias); if (self::PAGE_TYPE_ISOTOPE != $visitors_page_type) { $objPageIdOrg = 0; //backward compatibility } $objPageHitVisit = \Database::getInstance() ->prepare("SELECT id, visitors_page_visit, visitors_page_hit FROM tl_visitors_pages WHERE visitors_page_date = ? AND vid = ? AND visitors_page_id = ? AND visitors_page_pid = ? AND visitors_page_lang = ? AND visitors_page_type = ? ") ->execute($CURDATE, $vid, $objPageId, $objPageIdOrg, $objPage->language, $visitors_page_type); // eventuell $GLOBALS['TL_LANGUAGE'] // oder $objPage->rootLanguage; // Sprache der Root-Seite if ($objPageHitVisit->numRows < 1) { if ($objPageId > 0) { //Page Counter Insert $arrSet = array ( 'vid' => $vid, 'visitors_page_date' => $CURDATE, 'visitors_page_id' => $objPageId, 'visitors_page_pid' => $objPageIdOrg, 'visitors_page_type' => $visitors_page_type, 'visitors_page_visit' => 1, 'visitors_page_hit' => 1, 'visitors_page_lang' => $objPage->language ); \Database::getInstance() ->prepare("INSERT IGNORE INTO tl_visitors_pages %s") ->set($arrSet) ->execute(); } } else { $objPageHitVisit->next(); $visitors_page_hits = $objPageHitVisit->visitors_page_hit; $visitors_page_visits = $objPageHitVisit->visitors_page_visit; if ($this->_HitCounted === true) { //Update Hit $visitors_page_hits += 1; } if ($this->_VisitCounted === true) { //Update Visit $visitors_page_visits += 1; } \Database::getInstance() ->prepare("UPDATE tl_visitors_pages SET visitors_page_hit = ?, visitors_page_visit = ? WHERE id = ? ") ->execute($visitors_page_hits, $visitors_page_visits, $objPageHitVisit->id); } } //Page Counter End if ($objVisitIP->numRows < 1) { //Browser Check wenn nicht geblockt //Only counting if User Agent is set. if ( strlen(\Environment::get('httpUserAgent'))>0 ) { /* Variante 3 */ $ModuleVisitorBrowser3 = new ModuleVisitorBrowser3(); $ModuleVisitorBrowser3->initBrowser(\Environment::get('httpUserAgent'),implode(",", \Environment::get('httpAcceptLanguage'))); if ($ModuleVisitorBrowser3->getLang() === null) { \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, 'ModuleVisitorBrowser3 Systemerror', array('contao' => new ContaoContext('ModulVisitors', TL_ERROR))); } else { $arrBrowser['Browser'] = $ModuleVisitorBrowser3->getBrowser(); $arrBrowser['Version'] = $ModuleVisitorBrowser3->getVersion(); $arrBrowser['Platform'] = $ModuleVisitorBrowser3->getPlatformVersion(); $arrBrowser['lang'] = $ModuleVisitorBrowser3->getLang(); //Anpassen an Version 1 zur Weiterverarbeitung if ($arrBrowser['Browser'] == 'unknown') { $arrBrowser['Browser'] = 'Unknown'; } if ($arrBrowser['Version'] == 'unknown') { $arrBrowser['brversion'] = $arrBrowser['Browser']; } else { $arrBrowser['brversion'] = $arrBrowser['Browser'] . ' ' . $arrBrowser['Version']; } if ($arrBrowser['Platform'] == 'unknown') { $arrBrowser['Platform'] = 'Unknown'; } //Debug if ( $arrBrowser['Platform'] == 'Unknown' || $arrBrowser['Platform'] == 'Mozilla' || $arrBrowser['Version'] == 'unknown' ) { //Debug log_message("Unbekannter User Agent: ".$this->Environment->httpUserAgent."", 'unknown.log'); //Debug } $objBrowserCounter = \Database::getInstance() ->prepare("SELECT id, visitors_counter FROM tl_visitors_browser WHERE vid = ? AND visitors_browser = ? AND visitors_os = ? AND visitors_lang = ?") ->execute($vid, $arrBrowser['brversion'], $arrBrowser['Platform'], $arrBrowser['lang']); //setzen if ($objBrowserCounter->numRows < 1) { // Insert $arrSet = array ( 'vid' => $vid, 'visitors_browser' => $arrBrowser['brversion'], // version 'visitors_os' => $arrBrowser['Platform'], // os 'visitors_lang' => $arrBrowser['lang'], 'visitors_counter' => 1 ); \Database::getInstance() ->prepare("INSERT INTO tl_visitors_browser %s") ->set($arrSet) ->execute(); } else { //Update $objBrowserCounter->next(); $visitors_counter = $objBrowserCounter->visitors_counter +1; // Update \Database::getInstance() ->prepare("UPDATE tl_visitors_browser SET visitors_counter=? WHERE id=?") ->execute($visitors_counter, $objBrowserCounter->id); } } // else von NULL } // if strlen } //VisitIP numRows }
Insert/Update Counter
entailment
protected function visitorGetPageObj() { $objPage = null; $pageId = null; $pageId = $this->getPageIdFromUrl(); // Alias, not ID :-( // Load a website root page object if there is no page ID if ($pageId === null) { $pageId = $this->visitorGetRootPageFromUrl(); } ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Page ID over URL: '. $pageId); // Get the current page object(s), NULL on type 404 $objPage = \PageModel::findPublishedByIdOrAlias($pageId); // Check the URL and language of each page if there are multiple results if ($objPage !== null && $objPage->count() > 1) { $objNewPage = null; $arrPages = array(); // Order by domain and language while ($objPage->next()) { $objCurrentPage = $objPage->current()->loadDetails(); $domain = $objCurrentPage->domain ?: '*'; $arrPages[$domain][$objCurrentPage->rootLanguage] = $objCurrentPage; // Also store the fallback language if ($objCurrentPage->rootIsFallback) { $arrPages[$domain]['*'] = $objCurrentPage; } } $strHost = \Environment::get('host'); // Look for a root page whose domain name matches the host name if (isset($arrPages[$strHost])) { $arrLangs = $arrPages[$strHost]; } else { $arrLangs = $arrPages['*']; // empty domain } // Use the first result (see #4872) if (!$GLOBALS['TL_CONFIG']['addLanguageToUrl']) { $objNewPage = current($arrLangs); } // Try to find a page matching the language parameter elseif (($lang = \Input::get('language')) != '' && isset($arrLangs[$lang])) { $objNewPage = $arrLangs[$lang]; } // Store the page object if (is_object($objNewPage)) { $objPage = $objNewPage; } } elseif ($objPage !== null && $objPage->count() == 1) { $objPage = $objPage->current()->loadDetails(); } elseif ($objPage === null) { //404 page aus dem Cache $pageId = $this->visitorGetRootPageFromUrl(false); $objPage = \PageModel::find404ByPid($pageId); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Page Root ID / Page ID 404: '. $pageId .' / '.$objPage->id); } return $objPage; }
visitorCountUpdate
entailment
protected function visitorCheckReferrer($vid) { if ($this->_HitCounted === true) { if ($this->_PF === false) { $ModuleVisitorReferrer = new ModuleVisitorReferrer(); $ModuleVisitorReferrer->checkReferrer(); $ReferrerDNS = $ModuleVisitorReferrer->getReferrerDNS(); $ReferrerFull= $ModuleVisitorReferrer->getReferrerFull(); //Debug log_message('visitorCheckReferrer $ReferrerDNS:'.print_r($ReferrerDNS,true), 'debug.log'); //Debug log_message('visitorCheckReferrer Host:'.print_r($this->ModuleVisitorReferrer->getHost(),true), 'debug.log'); if ($ReferrerDNS != 'o' && $ReferrerDNS != 'w') { // not the own, not wrong // Insert $arrSet = array ( 'vid' => $vid, 'tstamp' => time(), 'visitors_referrer_dns' => $ReferrerDNS, 'visitors_referrer_full'=> $ReferrerFull ); //Referrer setzen //Debug log_message('visitorCheckReferrer Referrer setzen', 'debug.log'); \Database::getInstance() ->prepare("INSERT INTO tl_visitors_referrer %s") ->set($arrSet) ->execute(); // Delete old entries $CleanTime = mktime(0, 0, 0, date("m")-4, date("d"), date("Y")); // Einträge >= 120 Tage werden gelöscht \Database::getInstance() ->prepare("DELETE FROM tl_visitors_referrer WHERE tstamp < ? AND vid = ?") ->execute($CleanTime, $vid); } } //if PF } //if VB }
Check for Referrer @param integer $vid Visitors ID
entailment
protected function visitorSetDebugSettings($visitors_category_id) { $GLOBALS['visitors']['debug']['tag'] = false; $GLOBALS['visitors']['debug']['checks'] = false; $GLOBALS['visitors']['debug']['referrer'] = false; $GLOBALS['visitors']['debug']['searchengine'] = false; $objVisitors = \Database::getInstance() ->prepare("SELECT visitors_expert_debug_tag, visitors_expert_debug_checks, visitors_expert_debug_referrer, visitors_expert_debug_searchengine FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid) WHERE pid=? AND published=? ORDER BY tl_visitors.id, visitors_name") ->limit(1) ->execute($visitors_category_id,1); while ($objVisitors->next()) { $GLOBALS['visitors']['debug']['tag'] = (boolean)$objVisitors->visitors_expert_debug_tag; $GLOBALS['visitors']['debug']['checks'] = (boolean)$objVisitors->visitors_expert_debug_checks; $GLOBALS['visitors']['debug']['referrer'] = (boolean)$objVisitors->visitors_expert_debug_referrer; $GLOBALS['visitors']['debug']['searchengine'] = (boolean)$objVisitors->visitors_expert_debug_searchengine; ModuleVisitorLog::writeLog('## START ##', '## DEBUG ##', 'T'.(int)$GLOBALS['visitors']['debug']['tag'] .'#C'. (int)$GLOBALS['visitors']['debug']['checks'] .'#R'.(int) $GLOBALS['visitors']['debug']['referrer'] .'#S'.(int)$GLOBALS['visitors']['debug']['searchengine']); } }
visitorCheckReferrer
entailment
protected function visitorGetPageType($objPage) { $PageId = $objPage->id; //Return: //0 = reale Seite / Reader ohne Parameter - Auflistung der News/FAQs //1 = Nachrichten/News //2 = FAQ //403 = Forbidden $page_type = self::PAGE_TYPE_NORMAL; if ($objPage->protected == 1) { //protected Seite. user $this->import('FrontendUser', 'User'); if (!$this->User->authenticate()) { $page_type = self::PAGE_TYPE_FORBIDDEN; ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageType: '. $page_type); return $page_type; } } //Set the item from the auto_item parameter //from class ModuleNewsReader#L48 if (!isset($_GET['items']) && \Config::get('useAutoItem') && isset($_GET['auto_item'])) { \Input::setGet('items', \Input::get('auto_item')); } if (!\Input::get('items')) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageType: '. $page_type); return $page_type; } //News Table exists? if (\Input::get('items') && \Database::getInstance()->tableExists('tl_news')) { //News Reader? $objReaderPage = \Database::getInstance() ->prepare("SELECT id FROM tl_news_archive WHERE jumpTo=?") ->limit(1) ->execute($PageId); if ($objReaderPage->numRows > 0) { //News Reader $page_type = self::PAGE_TYPE_NEWS; } } //FAQ Table exists? if (\Input::get('items') && \Database::getInstance()->tableExists('tl_faq_category')) { //FAQ Reader? $objReaderPage = \Database::getInstance() ->prepare("SELECT id FROM tl_faq_category WHERE jumpTo=?") ->limit(1) ->execute($PageId); if ($objReaderPage->numRows > 0) { //FAQ Reader $page_type = self::PAGE_TYPE_FAQ; } } //Isotope Table tl_iso_product exists? if (\Input::get('items') && \Database::getInstance()->tableExists('tl_iso_product')) { $strAlias = \Input::get('items'); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Get items: '. print_r($strAlias, true)); $objReaderPage = \Database::getInstance() ->prepare("SELECT id FROM tl_iso_product WHERE alias=?") ->limit(1) ->execute($strAlias); if ($objReaderPage->numRows > 0) { //Isotope Reader $page_type = self::PAGE_TYPE_ISOTOPE; } } ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageType: '. $page_type); return $page_type; }
Get Page-Type @param integer $objPage @return integer 0 = reale Seite, 1 = News, 2 = FAQ, 403 = Forbidden
entailment
protected function visitorGetPageIdByType($PageId,$PageType,$PageAlias) { if ($PageType == self::PAGE_TYPE_NORMAL) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdNormal: '. $PageId); return $PageId; } if ($PageType == self::PAGE_TYPE_FORBIDDEN) { //Page ID von der 403 Seite ermitteln - nicht mehr ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdNormal over 403: '. $PageId); return $PageId; } //Reader mit Parameter oder ohne? $uri = $_SERVER['REQUEST_URI']; // /news/james-wilson-returns.html $alias = ''; //steht suffix (html) am Ende? $urlSuffix = \System::getContainer()->getParameter('contao.url_suffix'); // default: .html if (substr($uri,-strlen($urlSuffix)) == $urlSuffix) { //Alias nehmen $alias = substr($uri,strrpos($uri,'/')+1,-strlen($urlSuffix)); if (false === $alias) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdReaderSelf: '. $PageId); return $PageId; // kein Parameter, Readerseite selbst } } else { $alias = substr($uri,strrpos($uri,'/')+1); } ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Alias: '. $alias); if ($PageType == self::PAGE_TYPE_NEWS) { //alias = james-wilson-returns $objNews = \Database::getInstance() ->prepare("SELECT id FROM tl_news WHERE alias=?") ->limit(1) ->execute($alias); if ($objNews->numRows > 0) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdNews: '. $objNews->id); return $objNews->id; } } if ($PageType == self::PAGE_TYPE_FAQ) { //alias = are-there-exams-how-do-they-work $objFaq = \Database::getInstance() ->prepare("SELECT id FROM tl_faq WHERE alias=?") ->limit(1) ->execute($alias); if ($objFaq->numRows > 0) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdFaq: '. $objFaq->id); return $objFaq->id; } } if ($PageType == self::PAGE_TYPE_ISOTOPE) { //alias = a-perfect-circle-thirteenth-step $objIsotope = \Database::getInstance() ->prepare("SELECT id FROM tl_iso_product WHERE alias=?") ->limit(1) ->execute($alias); if ($objIsotope->numRows > 0) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'PageIdIsotope: '. $objIsotope->id); return $objIsotope->id; } } ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'Unknown PageType: '. $PageType); }
Get Page-ID by Page-Type @param integer $PageId @param integer $PageType @param string $PageAlias @return integer
entailment
protected function isContao45() { $packages = \System::getContainer()->getParameter('kernel.packages'); $coreVersion = $packages['contao/core-bundle']; //a.b.c if ( version_compare($coreVersion, '4.5.0', '>=') ) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; }
Check if contao/cor-bundle >= 4.5.0 @return boolean
entailment
public function setHeader($key, $value = null, $toLower = true) { if (is_array($key)) { foreach ($key as $k => $v) { $this->setHeader($k, $v); } } else { if ($toLower === true) { $key = strtolower($key); } if ($value === null) { unset($this->_headers[$key]); } else { $this->_headers[$key] = $value; } } }
Set http header or headers @param mixed $key string key or key-value pairs to set multiple headers. @param string $value the header value when key is string, set null to remove header. @param boolean $toLower convert key to lowercase
entailment
public function addHeader($key, $value = null, $toLower = true) { if (is_array($key)) { foreach ($key as $k => $v) { $this->addHeader($k, $v); } } else { if ($value !== null) { if ($toLower === true) { $key = strtolower($key); } if (!isset($this->_headers[$key])) { $this->_headers[$key] = $value; } else { if (is_array($this->_headers[$key])) { $this->_headers[$key][] = $value; } else { $this->_headers[$key] = [$this->_headers[$key], $value]; } } } } }
Add http header or headers @param mixed $key string key or key-value pairs to be added. @param string $value the header value when key is string. @param boolean $toLower convert key to lowercase
entailment
public function getHeader($key = null, $toLower = true) { if ($key === null) { return $this->_headers; } if ($toLower === true) { $key = strtolower($key); } return isset($this->_headers[$key]) ? $this->_headers[$key] : null; }
Get a http header or all http headers @param mixed $key the header key to be got, or null to get all headers @param boolean $toLower convert key to lowercase @return array|string the header value, or headers array when key is null.
entailment
public function hasHeader($key, $toLower = true) { if ($toLower === true) { $key = strtolower($key); } return isset($this->_headers[$key]); }
Check HTTP header is set or not @param string $key the header key to be check, not case sensitive @param boolean $toLower convert key to lowercase @return boolean if there is http header with the name.
entailment
public function setRawCookie($key, $value, $expires = null, $domain = '-', $path = '/') { $domain = strtolower($domain); if (substr($domain, 0, 1) === '.') { $domain = substr($domain, 1); } if (!isset($this->_cookies[$domain])) { $this->_cookies[$domain] = []; } if (!isset($this->_cookies[$domain][$path])) { $this->_cookies[$domain][$path] = []; } $list = &$this->_cookies[$domain][$path]; if ($value === null || $value === '' || ($expires !== null && $expires < time())) { unset($list[$key]); } else { $list[$key] = ['value' => $value, 'expires' => $expires]; } }
Set a raw cookie @param string $key cookie name @param string $value cookie value @param integer $expires cookie will be expired after this timestamp. @param string $domain cookie domain @param string $path cookie path
entailment
public function clearCookie($domain = '-', $path = null) { if ($domain === null) { $this->_cookies = []; } else { $domain = strtolower($domain); if ($path === null) { unset($this->_cookies[$domain]); } else { if (isset($this->_cookies[$domain])) { unset($this->_cookies[$domain][$path]); } } } }
Clean all cookies @param string $domain use null to clean all cookies, '-' to clean current cookies. @param string $path
entailment
public function getCookie($key, $domain = '-') { $domain = strtolower($domain); if ($key === null) { $cookies = []; } while (true) { if (isset($this->_cookies[$domain])) { foreach ($this->_cookies[$domain] as $path => $list) { if ($key === null) { $cookies = array_merge($list, $cookies); } else { if (isset($list[$key])) { return rawurldecode($list[$key]['value']); } } } } if (($pos = strpos($domain, '.', 1)) === false) { break; } $domain = substr($domain, $pos); } return $key === null ? $cookies : null; }
Get cookie value @param string $key passing null to get all cookies @param string $domain passing '-' to fetch from current session, @return array|null|string
entailment
public function applyCookie($req) { // fetch cookies $host = $req->getHeader('host'); $path = $req->getUrlParam('path'); $cookies = $this->fetchCookieToSend($host, $path); if ($this !== $req) { $cookies = array_merge($cookies, $req->fetchCookieToSend($host, $path)); } // add to header $req->setHeader('cookie', null); foreach (array_chunk(array_values($cookies), 3) as $chunk) { $req->addHeader('cookie', implode('; ', $chunk)); } }
Apply cookies for request @param Request $req
entailment
public function fetchCookieToSend($host, $path) { $now = time(); $host = strtolower($host); $cookies = []; $domains = ['-', $host]; while (strlen($host) > 1 && ($pos = strpos($host, '.', 1)) !== false) { $host = substr($host, $pos + 1); $domains[] = $host; } foreach ($domains as $domain) { if (!isset($this->_cookies[$domain])) { continue; } foreach ($this->_cookies[$domain] as $_path => $list) { if (!strncmp($_path, $path, strlen($_path)) && (substr($_path, -1, 1) === '/' || substr($path, strlen($_path), 1) === '/') ) { foreach ($list as $k => $v) { if (!isset($cookies[$k]) && ($v['expires'] === null || $v['expires'] > $now)) { $cookies[$k] = $k . '=' . $v['value']; } } } } } return $cookies; }
Fetch cookies to be sent @param string $host @param string $path @return array
entailment
public function run() { $logger = \System::getContainer()->get('monolog.logger.contao'); if (false === self::$_BackendUser && true === $this->isContao45()) { $objTokenChecker = \System::getContainer()->get('contao.security.token_checker'); if ($objTokenChecker->hasBackendUser()) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': BackendUser: Yes' ); self::$_BackendUser = true; } else { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': BackendUser: No' ); } } //Parameter holen if ((int)\Input::get('vcid') > 0) { $visitors_category_id = (int)\Input::get('vcid'); $this->visitorScreenSetDebugSettings($visitors_category_id); $this->visitorScreenSetResolutions(); if ($this->_SCREEN !== false) { /* __________ __ ___ _____________ ________ / ____/ __ \/ / / / | / /_ __/ _/ | / / ____/ / / / / / / / / / |/ / / / / // |/ / / __ / /___/ /_/ / /_/ / /| / / / _/ // /| / /_/ / \____/\____/\____/_/ |_/ /_/ /___/_/ |_/\____/ only */ $objVisitors = \Database::getInstance() ->prepare("SELECT tl_visitors.id AS id, visitors_block_time FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id = tl_visitors.pid) WHERE pid = ? AND published = ? ORDER BY id , visitors_name") ->limit(1) ->execute($visitors_category_id,1); if ($objVisitors->numRows < 1) { $logger->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['wrong_screen_catid'], array('contao' => new ContaoContext('FrontendVisitors '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); } else { while ($objVisitors->next()) { $this->visitorScreenCountUpdate($objVisitors->id, $objVisitors->visitors_block_time, $visitors_category_id, self::$_BackendUser); } } } //SCREEN !== false } else { $logger->log(LogLevel::ERROR, $GLOBALS['TL_LANG']['tl_visitors']['wrong_screen_catid'], array('contao' => new ContaoContext('FrontendVisitors '. VISITORS_VERSION .'.'. VISITORS_BUILD, TL_ERROR))); } //Pixel und raus hier $objResponse = new Response( base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==') ); $objResponse->headers->set('Content-type', 'image/gif'); $objResponse->headers->set('Content-length', 43); return $objResponse; }
Run the controller @return Response
entailment
protected function visitorScreenSetResolutions() { $this->_SCREEN = array( "scrw" => (int)\Input::get('scrw'), "scrh" => (int)\Input::get('scrh'), "scriw" => (int)\Input::get('scriw'), "scrih" => (int)\Input::get('scrih') ); if ((int)\Input::get('scrw') == 0 || (int)\Input::get('scrh') == 0 || (int)\Input::get('scriw') == 0 || (int)\Input::get('scrih') == 0 ) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , 'ERR: '.print_r(array( "scrw" => \Input::get('scrw'), "scrh" => \Input::get('scrh'), "scriw" => \Input::get('scriw'), "scrih" => \Input::get('scrih') ), true) ); $this->_SCREEN = false; } }
Set $_SCREEN variable
entailment
protected function visitorScreenCountUpdate($vid, $BlockTime, $visitors_category_id, $BackendUser = false) { ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ': '.print_r($this->_SCREEN, true) ); $ModuleVisitorChecks = new ModuleVisitorChecks($BackendUser); if ($ModuleVisitorChecks->checkBot() === true) { //Debug log_message("visitorCountUpdate BOT=true","debug.log"); return; //Bot / IP gefunden, wird nicht gezaehlt } if ($ModuleVisitorChecks->checkUserAgent($visitors_category_id) === true) { //Debug log_message("visitorCountUpdate UserAgent=true","debug.log"); return ; //User Agent Filterung } if ($ModuleVisitorChecks->checkBE() === true) { return; // Backend eingeloggt, nicht zaehlen (Feature: #197) } //Debug log_message("visitorCountUpdate count: ".$this->Environment->httpUserAgent,"useragents-noblock.log"); $ClientIP = bin2hex(sha1($visitors_category_id . $ModuleVisitorChecks->visitorGetUserIP(),true)); // sha1 20 Zeichen, bin2hex 40 zeichen $BlockTime = ($BlockTime == '') ? 1800 : $BlockTime; //Sekunden $CURDATE = date('Y-m-d'); //Visitor Screen Blocker \Database::getInstance() ->prepare("DELETE FROM tl_visitors_blocker WHERE CURRENT_TIMESTAMP - INTERVAL ? SECOND > visitors_tstamp AND vid = ? AND visitors_type = ?") ->execute($BlockTime, $vid, 's'); //Blocker IP lesen, sofern vorhanden $objVisitBlockerIP = \Database::getInstance() ->prepare("SELECT id, visitors_ip FROM tl_visitors_blocker WHERE visitors_ip = ? AND vid = ? AND visitors_type = ?") ->execute($ClientIP, $vid, 's'); //Debug ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':\n'.$objVisitBlockerIP->query ); //Daten lesen, nur Screen Angaben, die Inner Angaben werden jedesmal überschrieben $objScreenCounter = \Database::getInstance() ->prepare("SELECT id, v_screen_counter FROM tl_visitors_screen_counter WHERE v_date = ? AND vid = ? AND v_s_w = ? AND v_s_h = ?") ->execute($CURDATE, $vid, $this->_SCREEN['scrw'], $this->_SCREEN['scrh']); if ($objScreenCounter->numRows < 1) { if ($objVisitBlockerIP->numRows < 1) { // Insert IP + Update Visits \Database::getInstance() ->prepare("INSERT INTO tl_visitors_blocker SET vid=?, visitors_tstamp=CURRENT_TIMESTAMP, visitors_ip=?, visitors_type=?") ->execute($vid, $ClientIP, 's'); // Insert $arrSet = array ( 'vid' => $vid, 'v_date' => $CURDATE, 'v_s_w' => $this->_SCREEN['scrw'], 'v_s_h' => $this->_SCREEN['scrh'], 'v_s_iw' => $this->_SCREEN['scriw'], 'v_s_ih' => $this->_SCREEN['scrih'], 'v_screen_counter' => 1 ); \Database::getInstance() ->prepare("INSERT IGNORE INTO tl_visitors_screen_counter %s") ->set($arrSet) ->execute(); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ': insert into tl_visitors_screen_counter' ); return ; } else { //Debug ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.'Update tstamp' ); // Update tstamp \Database::getInstance() ->prepare("UPDATE tl_visitors_blocker SET visitors_tstamp=CURRENT_TIMESTAMP WHERE visitors_ip=? AND vid=? AND visitors_type=?") ->execute($ClientIP, $vid, 's'); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ': update tl_visitors_blocker' ); return ; } } else { //Debug ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$objScreenCounter->numRows ); if ($objVisitBlockerIP->numRows < 1) { //Debug ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.$objVisitBlockerIP->numRows ); // Insert IP \Database::getInstance() ->prepare("INSERT INTO tl_visitors_blocker SET vid=?, visitors_tstamp=CURRENT_TIMESTAMP, visitors_ip=?, visitors_type=?") ->execute($vid, $ClientIP, 's'); $objScreenCounter->next(); //Update der Screen Counter, Inner Daten dabei aktualisieren \Database::getInstance() ->prepare("UPDATE tl_visitors_screen_counter SET v_s_iw = ?, v_s_ih = ?, v_screen_counter = ? WHERE v_date = ? AND vid = ? AND v_s_w = ? AND v_s_h = ?") ->execute($this->_SCREEN['scriw'], $this->_SCREEN['scrih'], $objScreenCounter->v_screen_counter +1, $CURDATE, $vid, $this->_SCREEN['scrw'], $this->_SCREEN['scrh'] ); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ': update tl_visitors_screen_counter' ); } else { //Debug ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ':'.'Update tstamp' ); // Update tstamp \Database::getInstance() ->prepare("UPDATE tl_visitors_blocker SET visitors_tstamp=CURRENT_TIMESTAMP WHERE visitors_ip=? AND vid=? AND visitors_type=?") ->execute($ClientIP, $vid, 's'); ModuleVisitorLog::writeLog(__METHOD__ , __LINE__ , ': update tl_visitors_blocker' ); } } return ; }
Insert/Update Counter
entailment
protected function visitorScreenSetDebugSettings($visitors_category_id) { $GLOBALS['visitors']['debug']['screenresolutioncount'] = false; $objVisitors = \Database::getInstance() ->prepare("SELECT visitors_expert_debug_screenresolutioncount FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid) WHERE pid=? AND published=? ORDER BY tl_visitors.id, visitors_name") ->limit(1) ->execute($visitors_category_id,1); while ($objVisitors->next()) { $GLOBALS['visitors']['debug']['screenresolutioncount'] = (boolean)$objVisitors->visitors_expert_debug_screenresolutioncount; ModuleVisitorLog::writeLog('## START ##', '## SCREEN DEBUG ##', '#S'.(int)$GLOBALS['visitors']['debug']['screenresolutioncount']); } }
visitorScreenCountUpdate
entailment
public function setName($name){ if(!is_string($name) && !is_numeric($name)){ throw new \Exception("Falscher Dateityp (".gettype($name).") number or string expected!"); } $this->name = $name; }
Diagrammname setzen
entailment
public function setHeight($height){ if(!is_int($height)){ throw new \Exception("Falscher Dateityp (".gettype($height).") integer expected!"); } $this->height = $height; return true; }
Höhe des Diagramms setzen
entailment
public function setWidth($width){ if(!is_int($width)){ throw new \Exception("Falscher Dateityp (".gettype($width).") integer expected!"); } $this->width = $width; return true; }
Breite des Diagramms setzen
entailment
public function setMaxvalueHeight($maxvalue_height){ if(!is_int($maxvalue_height)){ throw new \Exception("Falscher Dateityp (".gettype($maxvalue_height).") integer expected!"); } $this->maxvalue_height = $maxvalue_height; return true; }
Balkenhöhe des Maximalwertes setzen
entailment
public function addX($x){ if(!is_numeric($x) && !is_string($x)){ throw new \Exception("Falscher Dateityp (".gettype($x).") number or string expected!"); } $this->x[] = $x; return true; }
Fügt einen X-Wert hinzu
entailment
public function addY($y){ if(!is_numeric($y)){ throw new \Exception("Falscher Dateityp (".gettype($y).") number expected!"); } $this->y[] = $y; return true; }
Fügt einen Y-Wert hinzu
entailment
public function addY2($y2){ if(!is_numeric($y2)){ throw new \Exception("Falscher Dateityp (".gettype($y2).") number expected!"); } $this->y2[] = $y2; return true; }
Fügt einen Y2-Wert hinzu
entailment
public static function createDefault(string $class): Rule { $rule = new Rule($class); $reflection = new \ReflectionClass($class); $properties = $reflection->getProperties(); foreach ($properties as $property) { /** @var \ReflectionProperty $property */ $rule->assign($property->getName(), $property->getName()); } return $rule; }
Create rule with one-to-one mapping @param string $class @return Rule
entailment
public function assign(string $property, string $key) { $this->doAssign($property, $key); return $this; }
Simple property-key pair assigning @param string $property Object property @param string $key Map key @return $this
entailment
public function assignConstructor(string $property, string $key, callable $fx) { $this->doAssign($property, $key); $this->constructors[$property] = $fx; return $this; }
Assign property constructor @param string $property @param string $key @param callable $fx @return $this
entailment
public function assignSerializer(string $property, string $key, callable $fx) { $this->doAssign($property, $key); $this->serializers[$property] = $fx; return $this; }
Assign property serializer @param string $property @param string $key @param callable $fx @return $this
entailment
public function execute(): string { $calls = $this->requestParser->parse($this->requestProvider->getPayload()); $result = $this->processor->process($calls); return $this->responseBuilder->build($result); }
Run server @return string
entailment
public function encodeParameters(array $parameters) : string { return str_replace('+/=', '†‡•', base64_encode(serialize($parameters))); }
Converts the given parameters into a set of characters that are safe to use in a class name @param array $parameters @return string
entailment
public function set( $method = null, $mount = null, $path = null, $handler = null, string $info = null ) : object { $this->mount = rtrim($mount, "/"); $this->path = $path; $this->handler = $handler; $this->info = $info; $this->method = $method; if (is_string($method)) { $this->method = array_map("trim", explode("|", $method)); } if (is_array($this->method)) { $this->method = array_map("strtoupper", $this->method); } return $this; }
Set values for route. @param string|array $method as request method to support @param string $mount where to mount the path @param string $path for this route @param string|array|callable $handler for this path, callable or equal @param string $info description of the route @return $this
entailment
public function match(string $query, string $method = null) { $this->arguments = []; $this->methodMatched = null; $this->pathMatched = null; $matcher = new RouteMatcher(); $res = $matcher->match( $this->mount, $this->path, $this->getAbsolutePath(), $query, $this->method, $method ); $this->arguments = $matcher->arguments; $this->methodMatched = $matcher->methodMatched; $this->pathMatched = $matcher->pathMatched; return $res; }
Check if the route matches a query and request method. @param string $query to match against @param string $method as request method @return boolean true if query matches the route
entailment
public function handle( string $path = null, ContainerInterface $di = null ) { if ($this->mount) { // Remove the mount path to get base for controller $len = strlen($this->mount); if (substr($path, 0, $len) == $this->mount) { $path = ltrim(substr($path, $len), "/"); } } try { $handler = new RouteHandler(); return $handler->handle($this->methodMatched, $path, $this->handler, $this->arguments, $di); } catch (ConfigurationException $e) { throw new ConfigurationException( $e->getMessage() . " Route matched method='{$this->methodMatched}', mount='{$this->mount}', path='$path', handler='" . ( is_string($this->handler) ? "$this->handler" : "array/object" ) . "'." ); } }
Handle the action for the route. @param string $path the matched path @param ContainerInjectableInterface $di container with services @return mixed
entailment
public function getMatchedPath() { $path = $this->pathMatched; if ($this->mount) { $len = strlen($this->mount); if (substr($path, 0, $len) == $this->mount) { $path = ltrim(substr($path, $len), "/"); } } return $path; }
Get the matched basename of the path, its the part without the mount point. @return string|null
entailment
public function getAbsolutePath() { if (empty($this->mount) && is_null($this->path)) { return null; } if (empty($this->mount)) { return $this->path; } return $this->mount . "/" . $this->path; }
Get the absolute $path by adding $mount. @return string|null as absolute path for this route.
entailment
public function getHandlerType(ContainerInterface $di = null) : string { $handler = new RouteHandler(); return $handler->getHandlerType($this->handler, $di); }
Get the handler type as a informative string. @param ContainerInjectableInterface $di container with services @return string representing the handler.
entailment
public function reset() { $this->status = 400; $this->statusText = 'Bad Request'; $this->body = ''; $this->error = null; $this->timeCost = 0; $this->clearHeader(); $this->clearCookie(); }
Reset object
entailment
public function redirect($url) { // has redirect from upstream if (($this->status === 301 || $this->status === 302) && ($this->hasHeader('location'))) { return; } // @fixme need a better solution $this->numRedirected--; $this->status = 302; $this->setHeader('location', $url); }
Redirect to another url This method can be used in request callback. @param string $url target url to be redirected to.
entailment
public function getJson() { if (stripos($this->getHeader('content-type'), '/json') !== false) { return json_decode($this->body, true); } else { return false; } }
Get json response data @return mixed
entailment
public function publishSlides() { $slides = SlideImage::get(); $ct = 0; foreach ($this->getSlides() as $slide) { if ($slide->ShowSlide == 1) { if (!$slide->Name) { $slide->Name = "No Name"; } $slide->writeToStage('Stage'); $slide->publishRecursive(); ++$ct; } } static::write_message($ct . " SlideImages updated"); }
mark all ProductDetail records as ShowInMenus = 0.
entailment
public function getConn() { if ($this->conn === null) { $this->conn = Connection::connect($this->req->getUrlParam('conn'), $this); if ($this->conn === false) { $this->res->error = Connection::getLastError(); $this->finish(); } else { if ($this->conn !== null) { $this->conn->addWriteData($this->getRequestBuf()); } } } return $this->conn; }
Get connection @return Connection the connection object, returns null if the connection fails or need to queue.
entailment
public function finish($type = 'NORMAL') { $this->finished = true; if ($type === 'BROKEN') { $this->res->error = Connection::getLastError(); } else { if ($type !== 'NORMAL') { $this->res->error = ucfirst(strtolower($type)); } } // gzip decode $encoding = $this->res->getHeader('content-encoding'); if ($encoding !== null && strstr($encoding, 'gzip')) { $this->res->body = Client::gzdecode($this->res->body); } // parser $this->res->timeCost = microtime(true) - $this->timeBegin; $this->cli->runParser($this->res, $this->req, $this->key); // conn if ($this->conn) { // close conn $close = $this->res->getHeader('connection'); $this->conn->close($type !== 'NORMAL' || !strcasecmp($close, 'close')); $this->conn = null; // redirect if (($this->res->status === 301 || $this->res->status === 302) && $this->res->numRedirected < $this->req->getMaxRedirect() && ($location = $this->res->getHeader('location')) !== null ) { Client::debug('redirect to \'', $location, '\''); $req = $this->req; if (!preg_match('/^https?:\/\//i', $location)) { $pa = $req->getUrlParams(); $url = $pa['scheme'] . '://' . $pa['host']; if (isset($pa['port'])) { $url .= ':' . $pa['port']; } if (substr($location, 0, 1) == '/') { $url .= $location; } else { $url .= substr($pa['path'], 0, strrpos($pa['path'], '/') + 1) . $location; } $location = $url; /// FIXME: strip relative '../../' } // change new url $prevUrl = $req->getUrl(); $req->setUrl($location); if (!$req->getHeader('referer')) { $req->setHeader('referer', $prevUrl); } if ($req->getMethod() !== 'HEAD') { $req->setMethod('GET'); } $req->clearCookie(); $req->setHeader('host', null); $req->setHeader('x-server-ip', null); $req->setHeader('content-type', null); $req->setBody(null); // reset response $this->res->numRedirected++; $this->finished = $this->headerOk = false; return $this->res->reset(); } } Client::debug('finished', $this->res->hasError() ? ' (' . $this->res->error . ')' : ''); $this->req = $this->cli = null; }
Finish the processor @param string $type finish type, supports: NORMAL, BROKEN, TIMEOUT
entailment
public static function spawn($cmd, $cwd = null, LoggerInterface $logger = null) { return new self($cmd, $cwd, $logger); }
Spawn a new instance of Expect for the given command. You can optionally specify a working directory and a PSR compatible logger to use. @param string $cmd @param string $cwd @param LoggerInterface $logger @return $this
entailment
public function expect($output, $timeout = self::DEFAULT_TIMEOUT) { $this->steps[] = [self::EXPECT, $output, $timeout]; return $this; }
Register a step to expect the given text to show up on stdout. Expect will block and keep checking the stdout buffer until your expectation shows up or the timeout is reached, whichever comes first. @param string $output @param int $timeout @return $this
entailment
public function send($input) { if (stripos(strrev($input), PHP_EOL) === false) { $input = $input . PHP_EOL; } $this->steps[] = [self::SEND, $input]; return $this; }
Register a step to send the given text on stdin. A newline is added to each string to simulate pressing enter. @param string $input @return $this
entailment
public function run() { $this->createProcess(); foreach ($this->steps as $step) { if ($step[0] === self::EXPECT) { $expectation = $step[1]; $timeout = $step[2]; $this->waitForExpectedResponse($expectation, $timeout); } else { $input = $step[1]; $this->sendInput($input); } } $this->closeProcess(); }
Run the process and execute the registered steps. The program will block until the steps are completed or a timeout occurs. @return null @throws \RuntimeException If the process can not be created. @throws \Yuloh\Expect\Exceptions\ProcessTimeoutException if the process times out. @throws \Yuloh\Expect\Exceptions\UnexpectedEOFException if an unexpected EOF is found. @throws \Yuloh\Expect\Exceptions\ProcessTerminatedException if the process is terminated before the expectation is met.
entailment
private function createProcess() { $descriptorSpec = [ ['pipe', 'r'], // stdin ['pipe', 'w'], // stdout ['pipe', 'r'] // stderr ]; $this->process = proc_open($this->cmd, $descriptorSpec, $this->pipes, $this->cwd); if (!is_resource($this->process)) { throw new \RuntimeException('Could not create the process.'); } }
Create the process. @return null @throws \RuntimeException If the process can not be created.
entailment
private function closeProcess() { fclose($this->pipes[0]); fclose($this->pipes[1]); fclose($this->pipes[2]); proc_close($this->process); }
Close the process. @return null
entailment
private function waitForExpectedResponse($expectation, $timeout) { $response = null; $lastLoggedResponse = null; $buffer = ''; $start = time(); stream_set_blocking($this->pipes[1], false); while (true) { if (time() - $start >= $timeout) { throw new ProcessTimeoutException(); } if (feof($this->pipes[1])) { throw new UnexpectedEOFException(); } if (!$this->isRunning()) { throw new ProcessTerminatedException(); } $buffer .= fread($this->pipes[1], 4096); $response = static::trimAnswer($buffer); if ($response !== '' && $response !== $lastLoggedResponse) { $lastLoggedResponse = $response; $this->logger->info("Expected '{$expectation}', got '{$response}'"); } if (fnmatch($expectation, $response)) { return; } } }
Wait for the given response to show on stdout. @param string $expectation The expected output. Will be glob matched. @return null @throws \Yuloh\Expect\Exceptions\ProcessTimeoutException if the process times out. @throws \Yuloh\Expect\Exceptions\UnexpectedEOFException if an unexpected EOF is found. @throws \Yuloh\Expect\Exceptions\ProcessTerminatedException if the process is terminated before the expectation is met.
entailment
private function isRunning() { if (!is_resource($this->process)) { return false; } $status = proc_get_status($this->process); return $status['running']; }
Determine if the process is running. @return boolean
entailment
protected function reset() { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , 'Referrer Raw: ' . $_SERVER['HTTP_REFERER'] ); //NEVER TRUST USER INPUT if (function_exists('filter_var')) // Adjustment for hoster without the filter extension { $this->_http_referrer = isset($_SERVER['HTTP_REFERER']) ? filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL) : self::REFERRER_UNKNOWN ; } else { $this->_http_referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : self::REFERRER_UNKNOWN ; } //Fixed #206 $this->_http_referrer = Encoding::toUTF8( urldecode( $this->_http_referrer ) ); $this->_referrer_DNS = self::REFERRER_UNKNOWN; if ($this->_http_referrer == '' || $this->_http_referrer == '-') { //ungueltiger Referrer $this->_referrer_DNS = self::REFERRER_WRONG; $this->_wrong_detail = 'Invalid referrer'; } }
Reset all properties
entailment
protected function vhost() { $host = rtrim($_SERVER['HTTP_HOST']); if (empty($host)) { $host = $_SERVER['SERVER_NAME']; } $host = preg_replace('/[^A-Za-z0-9\[\]\.:-]/', '', $host); if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $xhost = preg_replace('/[^A-Za-z0-9\[\]\.:-]/', '', rtrim($_SERVER['HTTP_X_FORWARDED_HOST'],'/')); } else { $xhost = ''; } return (!empty($xhost) ? $xhost : $host) ; }
Return the current URL without path or query string or protocol @return string
entailment
public function generate(array $ast) : string { $code = parent::generate($ast); if (! $this->canEval) { $fileName = sys_get_temp_dir() . '/EvaluatingGeneratorStrategy.php.tmp.' . uniqid('', true); file_put_contents($fileName, "<?php\n" . $code); require $fileName; unlink($fileName); return $code; } eval($code); return $code; }
Evaluates the generated code before returning it {@inheritDoc}
entailment
public function setUrl($url) { $this->_rawUrl = $url; if (strncasecmp($url, 'http://', 7) && strncasecmp($url, 'https://', 8) && isset($_SERVER['HTTP_HOST'])) { if (substr($url, 0, 1) != '/') { $url = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/') + 1) . $url; } $url = 'http://' . $_SERVER['HTTP_HOST'] . $url; } $this->_url = str_replace('&amp;', '&', $url); $this->_urlParams = null; }
Set request URL Relative url will be converted to full url by adding host and protocol. @param string $url raw url
entailment
public function getUrlParams() { if ($this->_urlParams === null) { $pa = @parse_url($this->getUrl()); $pa['scheme'] = isset($pa['scheme']) ? strtolower($pa['scheme']) : 'http'; if ($pa['scheme'] !== 'http' && $pa['scheme'] !== 'https') { return false; } if (!isset($pa['host'])) { return false; } if (!isset($pa['path'])) { $pa['path'] = '/'; } // basic auth if (isset($pa['user']) && isset($pa['pass'])) { $this->applyBasicAuth($pa['user'], $pa['pass']); } // convert host to IP address $port = isset($pa['port']) ? intval($pa['port']) : ($pa['scheme'] === 'https' ? 443 : 80); $pa['ip'] = $this->hasHeader('x-server-ip') ? $this->getHeader('x-server-ip') : self::getIp($pa['host']); $pa['conn'] = ($pa['scheme'] === 'https' ? 'ssl' : 'tcp') . '://' . $pa['ip'] . ':' . $port; // host header if (!$this->hasHeader('host')) { $this->setHeader('host', strtolower($pa['host'])); } else { $pa['host'] = $this->getHeader('host'); } $this->_urlParams = $pa; } return $this->_urlParams; }
Get url parameters @return array the parameters parsed from URL, or false on error
entailment
public function getUrlParam($key) { $pa = $this->getUrlParams(); return isset($pa[$key]) ? $pa[$key] : null; }
Get url parameter by key @param string $key parameter name @return string the parameter value or null if non-exists.
entailment
public function getBody() { $body = ''; if ($this->_method === 'POST' || $this->_method === 'PUT') { if ($this->_body === null) { $this->_body = $this->getPostBody(); } $this->setHeader('content-length', strlen($this->_body)); $body = $this->_body . Client::CRLF; } return $body; }
Get http request body Appending post fields and files. @return string request body
entailment
public function setBody($body) { $this->_body = $body; $this->setHeader('content-length', $body === null ? null : strlen($body)); }
Set http request body @param string $body content string.
entailment