sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function revokeMembership($user) { try { foreach($user->membershipList as $group) { if ($group->resync_on_login) { $user->membershipList()->detach($group); } } } catch (\Exception $ex) { Log::error('Exception revoking local group membership for user: ' . $user->username . ', Exception message: ' . $ex->getMessage()); Log::error($ex->getTraceAsString()); } }
Revoke membership to all local group that are marked with 'resync_on_login' as 1 or true. @param $user The user to revoke group membership from.
entailment
private function replicateMembershipFromLDAP($user) { $adldap = false; try { $username = $user->username; $groupModel = $this->createGroupModel(); $ldapConOp = $this->GetLDAPConnectionOptions(); $ldapRecursive = Settings::get('eloquent-ldap.recursive_groups'); if (Settings::get('eloquent-ldap.debug')) { // Set LDAP debug log level - useful in DEV, dangerous in PROD!! ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); } // Connect to AD/LDAP $adldap = new Adldap(); $adldap->addProvider($ldapConOp); $provider = $adldap->connect(); // Locate the user $adldapUser = $provider->search()->users()->find($username); // Request the user's group membership. $adldapGroups = $adldapUser->getGroups([], true); foreach($adldapGroups as $adldapGroup) { try { $adldapGroupName = $adldapGroup->getName(); $localGroup = null; $localGroup = $groupModel->where('name', $adldapGroupName)->firstOrFail(); if ( !$user->isMemberOf($adldapGroupName) ) { $user->membershipList()->attach($localGroup->id); } } catch (ModelNotFoundException $e) { // Mute the exception as we expect not to find all groups. } } } catch (\Exception $ex) { Log::error('Exception replicating group membership for user: ' . $user->username . ', Exception message: ' . $ex->getMessage()); Log::error($ex->getTraceAsString()); $this->handleLDAPError($adldap); } // Close connection. if (isset($provider)) { unset($provider); } // Close connection. if (isset($adldap)) { unset($adldap); } }
Grants membership to local groups for each LDAP/AD group that the user is a member of. See the option "LDAP_RECURSIVE_GROUPS" to enable deep LDAP/AD group probe. NOTE: This will not maintain the hierarchical structure of the groups, instead the structure will be 'flattened'. If you want to maintain the hierarchical structure, set the option "LDAP_RECURSIVE_GROUPS" to false, and build a group structure that mirrors the LDAP/AD structure. @param $user The user to replicate group membership for. @throws Exception
entailment
private function validateLDAPCredentials(array $credentials) { $credentialsValidated = false; $adldap = false; try { $userPassword = $credentials['password']; $userName = $credentials['username']; $ldapConOp = $this->GetLDAPConnectionOptions(); if (Settings::get('eloquent-ldap.debug')) { // Set LDAP debug log level - useful in DEV, dangerous in PROD!! ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); } // Try to authenticate using AD/LDAP // Connect to AD/LDAP $adldap = new Adldap(); $adldap->addProvider($ldapConOp); $provider = $adldap->connect(); // For LDAP servers, the authentication is done with the full DN, // Not the username with the suffix as is done for MSAD servers. if ('LDAP' === Settings::get('eloquent-ldap.server_type')) { $ldapUser = $this->getLDAPUser($userName); $userName = $this->GetArrayValueOrDefault($ldapUser, 'dn', ''); } $authUser = $provider->auth()->attempt($userName, $userPassword); // If the user got authenticated if ($authUser == true) { $credentialsValidated = true; } else { $this->handleLDAPError($adldap); $credentialsValidated = false; } } catch (\Exception $ex) { Log::error('Exception validating LDAP credential for user: ' . $userName . ', Exception message: ' . $ex->getMessage()); Log::error($ex->getTraceAsString()); $this->handleLDAPError($adldap); $credentialsValidated = false; } // Close connection. if (isset($provider)) { unset($provider); } // Close connection. if (isset($adldap)) { unset($adldap); } return $credentialsValidated; }
Validates the credentials against the configured LDAP/AD server. The credentials are passed in an array with the keys 'username' and 'password'. @param array $credentials The credentials to validate. @return boolean
entailment
private function handleLDAPError(\Adldap\Adldap $adldap) { if (false != $adldap) { // May be helpful for finding out what and why went wrong. $adLDAPError = $adldap->getConnection()->getLastError(); if ("Success" != $adLDAPError) { Log::error('Problem with LDAP:' . $adLDAPError); } } }
Logs the last LDAP error if it is not "Success". @param array $adldap The instance of the adLDAP object to check for error.
entailment
public function fire() { $url = $this->argument('url'); // Remote request. $invoke = (preg_match('/^http(s)?:/', $url)) ? 'invokeRemote' : 'invoke'; // Method to call. $method = $this->option('request'); $method = strtolower($method); $method = (in_array($method, array('get', 'post', 'put', 'delete', 'patch', 'head'))) ? $method : 'get'; // Parameters. $parameters = $this->option('data'); if ($parameters) { parse_str($parameters, $parameters); } $response = $this->api->$invoke($url, $method, $parameters); if ($response instanceof View) { return $this->info($response->render()); } if (is_array($response) or is_object($response)) { return $this->info(var_export($response, true)); } return $this->info($response); }
Execute the console command. @return mixed
entailment
public function instantiate($className) { if ($cloneable = self::$cachedCloneables->$className) { return clone $cloneable; } $factory = self::$cachedInstantiators->$className; /* @var $factory Closure */ return $factory(); }
{@inheritDoc}
entailment
public function buildFactory($className) { $reflectionClass = $this->getReflectionClass($className); if ($this->isInstantiableViaReflection($reflectionClass)) { return function () use ($reflectionClass) { return $reflectionClass->newInstanceWithoutConstructor(); }; } $serializedString = sprintf( '%s:%d:"%s":0:{}', $this->getSerializationFormat($reflectionClass), strlen($className), $className ); $this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString); return function () use ($serializedString) { return unserialize($serializedString); }; }
@internal @private Builds a {@see \Closure} capable of instantiating the given $className without invoking its constructor. This method is only exposed as public because of PHP 5.3 compatibility. Do not use this method in your own code @param string $className @return Closure
entailment
private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, $serializedString) { set_error_handler(function ($code, $message, $file, $line) use ($reflectionClass, & $error) { $error = UnexpectedValueException::fromUncleanUnSerialization( $reflectionClass, $message, $code, $file, $line ); }); try { unserialize($serializedString); } catch (Exception $exception) { restore_error_handler(); throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception); } restore_error_handler(); if ($error) { throw $error; } }
@param ReflectionClass $reflectionClass @param string $serializedString @throws UnexpectedValueException @return void
entailment
private function isInstantiableViaReflection(ReflectionClass $reflectionClass) { if (\PHP_VERSION_ID >= 50600) { return ! ($reflectionClass->isInternal() && $reflectionClass->isFinal()); } return \PHP_VERSION_ID >= 50400 && ! $this->hasInternalAncestors($reflectionClass); }
@param ReflectionClass $reflectionClass @return bool
entailment
private function getSerializationFormat(ReflectionClass $reflectionClass) { if ($this->isPhpVersionWithBrokenSerializationFormat() && $reflectionClass->implementsInterface('Serializable') ) { return self::SERIALIZATION_FORMAT_USE_UNSERIALIZER; } return self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER; }
Verifies if the given PHP version implements the `Serializable` interface serialization with an incompatible serialization format. If that's the case, use serialization marker "C" instead of "O". @link http://news.php.net/php.internals/74654 @param ReflectionClass $reflectionClass @return string the serialization format marker, either self::SERIALIZATION_FORMAT_USE_UNSERIALIZER or self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER
entailment
private function getInstantiatorsMap() { $that = $this; // PHP 5.3 compatibility return self::$cachedInstantiators = self::$cachedInstantiators ?: new CallbackLazyMap(function ($className) use ($that) { return $that->buildFactory($className); }); }
Builds or fetches the instantiators map @return CallbackLazyMap
entailment
private function getCloneablesMap() { $cachedInstantiators = $this->getInstantiatorsMap(); $that = $this; return self::$cachedCloneables = self::$cachedCloneables ?: new CallbackLazyMap(function ($className) use ($cachedInstantiators, $that) { /* @var $factory Closure */ $factory = $cachedInstantiators->$className; $instance = $factory(); if (! $that->isSafeToClone(new ReflectionClass($className))) { return null; } return $instance; }); }
Builds or fetches the cloneables map @return CallbackLazyMap
entailment
public function up() { //====== // USERS //====== // Either uncomment the section below to create the users table if it // was not already done before, or use it as an example for your own // migration. // // Create users table // Schema::create('users', function (Blueprint $table) { // $table->increments('id'); // $table->string('first_name'); // $table->string('last_name'); // $table->string('username')->unique(); // $table->string('email')->unique(); // $table->string('password', 60); // $table->rememberToken(); // $table->timestamps(); // }); // USERS: Add the auth_type column. Schema::table('users', function (Blueprint $table) { $table->string('auth_type')->nullable(); }); //======= // GROUPS //======= // Either uncomment the section below to create the groups table if it // was not already done before, or use it as an example for your own // migration. // // Create table for storing groups // Schema::create('groups', function (Blueprint $table) { // $table->increments('id'); // $table->string('name')->unique(); // $table->string('display_name')->nullable(); // $table->string('description')->nullable(); // $table->timestamps(); // }); // // // Create table for associating groups to users (Many-to-Many) // Schema::create('group_user', function (Blueprint $table) { // $table->integer('user_id')->unsigned(); // $table->integer('group_id')->unsigned(); // // $table->foreign('user_id')->references('id')->on('users') // ->onUpdate('cascade')->onDelete('cascade'); // $table->foreign('group_id')->references('id')->on('groups') // ->onUpdate('cascade')->onDelete('cascade'); // // $table->primary(['user_id', 'group_id']); // }); // GROUPS: Add the resync_on_login column. Schema::table('groups', function (Blueprint $table) { $table->boolean('resync_on_login')->default(false); }); }
Run the migrations. @return void
entailment
public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('auth_type'); }); // Uncomment the section below if the users table was created above. // // Drop the users table. // Schema::drop('users'); Schema::table('groups', function (Blueprint $table) { $table->dropColumn('resync_on_login'); }); // Uncomment the section below if the groups table was created above. // // Drop the groups table. // Schema::drop('groups'); // // Drop the group user link table. // Schema::drop('group_user'); }
Reverse the migrations. @return void
entailment
protected function settingForm() { return Administrator::form(function (Form $form) { $form->display('username', trans('admin.username')); $form->text('name', trans('admin.name'))->rules('required'); $form->email('email', trans('Email')); $form->mobile('mobile', trans('Mobile')); $form->image('avatar', trans('admin.avatar')); $form->password('password', trans('admin.password'))->rules('confirmed|required'); $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required') ->default(function ($form) { return $form->model()->password; }); $form->setAction(admin_base_path('auth/setting')); $form->ignore(['password_confirmation']); $form->saving(function (Form $form) { if ($form->password && $form->model()->password != $form->password) { $form->password = bcrypt($form->password); } }); $form->saved(function () { admin_toastr(trans('admin.update_succeeded')); return redirect(admin_base_path('auth/setting')); }); }); }
Model-form for user setting. @return Form
entailment
public function handle() { if (empty($this->option('name'))) { $this->importAll(); } else { $name = $this->option('name'); $name = str_replace('-', '', $name); if (method_exists($this, $name)) { call_user_func([$this, $name]); } } $this->line('<info>Laravel admin extensions installed.</info> '); }
Execute the console command.
entailment
public function registerApi() { $this->app['api.request'] = $this->app->share(function($app) { $remoteClient = new Client(); return new Api($app['config'], $app['router'], $app['request'], $remoteClient); }); }
Register Api. @return void
entailment
public function registerApiCallCommand() { $this->app['api.call'] = $this->app->share(function($app) { return new Commands\ApiCallCommand($app['api.request']); }); }
Register Api Call command. @return void
entailment
public function run() { // add default menus. Menu::truncate(); Menu::insert([ [ 'parent_id' => 0, 'order' => 1, 'title' => '系统管理', 'icon' => 'fa-tasks', 'uri' => '/', ], [ 'parent_id' => 1, 'order' => 1, 'title' => 'Index', 'icon' => 'fa-bar-chart', 'uri' => '/', ], [ 'parent_id' => 1, 'order' => 2, 'title' => 'Admin', 'icon' => 'fa-tasks', 'uri' => '', ], [ 'parent_id' => 3, 'order' => 3, 'title' => 'Users', 'icon' => 'fa-users', 'uri' => 'auth/users', ], [ 'parent_id' => 3, 'order' => 4, 'title' => 'Roles', 'icon' => 'fa-user', 'uri' => 'auth/roles', ], [ 'parent_id' => 3, 'order' => 5, 'title' => 'Permission', 'icon' => 'fa-ban', 'uri' => 'auth/permissions', ], [ 'parent_id' => 3, 'order' => 6, 'title' => 'Menu', 'icon' => 'fa-bars', 'uri' => 'auth/menu', ], [ 'parent_id' => 3, 'order' => 7, 'title' => 'Operation log', 'icon' => 'fa-history', 'uri' => 'auth/logs', ], ]); // add role to menu. Menu::find(2)->roles()->save(Role::first()); }
Run the database seeds.
entailment
public function make($data, $code, $overwrite = false) { // Status returned. $status = (preg_match('/^(1|2|3)/', $code)) ? 'success' : 'error'; // Change object to array. if (is_object($data)) { $data = $data->toArray(); } // Data as a string. if (is_string($data)) { $data = array('message' => $data); } // Overwrite response format. if ($overwrite === true) { $response = $data; } else { $message = $this->statuses[$code]; // Custom return message. if (isset($data['message'])) { $message = $data['message']; unset($data['message']); } // Available data response. $response = array( 'status' => $status, 'code' => $code, 'message' => $message, 'data' => $data, 'pagination' => null ); // Merge if data has anything else. if (isset($data['data'])) { $response = array_merge($response, $data); } // Remove empty array. $response = array_filter($response, function($value) { return ! is_null($value); }); // Remove empty data. if ($this->config['removeEmptyData'] && empty($response['data'])) { unset($response['data']); } } // Header response. $header = ($this->config['httpResponse']) ? $code : 200; return Response::make($response, $header); }
Make json data format. @param mixed $data @param integer $code @param boolean $overwrite @return string
entailment
public function configureRemoteClient($configurations) { foreach ($configurations as $option => $value) { call_user_func_array(array($this->remoteClient, 'setDefaultOption'), array($option, $value)); } }
Configure remote client for http request. @param array $configuration array ( 'verify' => false, //allows self signed certificates 'verify', '/path/to/cacert.pem', //custom certificate 'headers/X-Foo', 'Bar', //custom header 'auth', array('username', 'password', 'Digest'), //custom authentication )
entailment
public function invoke($uri, $method, $parameters = array()) { // Request URI. if ( ! preg_match('/^http(s)?:/', $uri)) { $uri = '/'.ltrim($uri, '/'); } try { // Store the original request data and route. $originalInput = $this->request->input(); $originalRoute = $this->router->getCurrentRoute(); // Masking route to allow testing with PHPUnit. if ( ! $originalRoute instanceof Route) { $originalRoute = new Route(new \Symfony\Component\HttpFoundation\Request()); } // Create a new request to the API resource $request = $this->request->create($uri, strtoupper($method), $parameters); // Replace the request input... $this->request->replace($request->input()); // Dispatch request. $dispatch = $this->router->dispatch($request); if (method_exists($dispatch, 'getOriginalContent')) { $response = $dispatch->getOriginalContent(); } else { $response = $dispatch->getContent(); } // Decode json content. if ($dispatch->headers->get('content-type') == 'application/json') { if (function_exists('json_decode') and is_string($response)) { $response = json_decode($response, true); } } // Restore the request input and route back to the original state. $this->request->replace($originalInput); // This method have been removed from Laravel. //$this->router->setCurrentRoute($originalRoute); return $response; } catch (NotFoundHttpException $e) { //trigger_error('Not found'); var_dump($e->getMessage()); } catch (FatalErrorException $e) { var_dump($e->getMessage()); } }
Call internal URI with parameters. @param string $uri @param string $method @param array $parameters @return mixed
entailment
public function invokeRemote($uri, $method, $parameters = array()) { $remoteClient = $this->getRemoteClient(); // Make request. $request = call_user_func_array(array($remoteClient, $method), array($uri, null, $parameters)); // Send request. $response = $request->send(); // Body responsed. $body = (string) $response->getBody(); // Decode json content. if ($response->getContentType() == 'application/json') { if (function_exists('json_decode') and is_string($body)) { $body = json_decode($body, true); } } return $body; }
Invoke with remote uri. @param string $uri @param string $method @param array $parameters @return mixed
entailment
public function index() { return Admin::content(function (Content $content) { $content->header(trans('admin.menu')); $content->description(trans('admin.list')); $content->row(function (Row $row) { $row->column(6, $this->treeView()->render()); $row->column(6, function (Column $column) { $form = new \Encore\Admin\Widgets\Form(); $form->action(admin_base_path('auth/menu')); $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions()); $form->text('title', trans('admin.title'))->rules('required'); $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp()); $form->text('uri', trans('admin.uri')); $form->multipleSelect('roles', trans('admin.roles'))->options(Role::all()->pluck('name', 'id')); $form->radio('blank', '加载方式')->options(['0' => 'pjax', '1'=>'no-pjax' ])->default('0'); $form->hidden('_token')->default(csrf_token()); $column->append((new Box(trans('admin.new'), $form))->style('success')); }); }); }); }
Index interface. @return Content
entailment
public function form() { return Menu::form(function (Form $form) { $form->display('id', 'ID'); $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions()); $form->text('title', trans('admin.title'))->rules('required'); $form->icon('icon', trans('admin.icon'))->default('fa-bars')->help($this->iconHelp()); $form->text('uri', trans('admin.uri')); $form->multipleSelect('roles', trans('admin.roles'))->options(Role::all()->pluck('name', 'id')); $form->radio('blank', '加载方式')->options(['0' => 'pjax', '1'=>'no-pjax' ])->default('0'); $form->display('created_at', trans('admin.created_at')); $form->display('updated_at', trans('admin.updated_at')); }); }
Make a form builder. @return Form
entailment
public static function debug($msg) { if ($msg === 'open' || $msg === 'close') { self::$_debugOpen = $msg === 'open'; } elseif (self::$_debugOpen === true) { $key = self::$_processKey === null ? '' : '[' . self::$_processKey . '] '; echo '[DEBUG] ', date('H:i:s '), $key, implode('', func_get_args()), self::CRLF; } }
Open/close debug mode @param string $msg
entailment
public function setParser($p) { if ($p === null || $p instanceof ParseInterface || is_callable($p)) { $this->_parser = $p; } }
Set response parse handler @param callable $p parse handler
entailment
public function runParser($res, $req, $key = null) { if ($this->_parser !== null) { self::debug('run parser: ', $req->getRawUrl()); if ($this->_parser instanceof ParseInterface) { $this->_parser->parse($res, $req, $key); } else { call_user_func($this->_parser, $res, $req, $key); } } }
Run parse handler @param Response $res response object @param Request $req request object @param mixed $key the key string of multi request
entailment
public function head($url, $params = []) { if (is_array($url)) { return $this->mhead($url, $params); } return $this->exec($this->buildRequest('HEAD', $url, $params)); }
Shortcut of HEAD request @param string $url request URL string. @param array $params query params appended to URL. @return Response result response object.
entailment
public function get($url, $params = []) { if (is_array($url)) { return $this->mget($url, $params); } return $this->exec($this->buildRequest('GET', $url, $params)); }
Shortcut of GET request @param string $url request URL string. @param array $params extra query params, appended to URL. @return Response result response object.
entailment
public function delete($url, $params = []) { if (is_array($url)) { return $this->mdelete($url, $params); } return $this->exec($this->buildRequest('DELETE', $url, $params)); }
Shortcut of DELETE request @param string $url request URL string. @param array $params extra query params, appended to URL. @return Response result response object.
entailment
public function post($url, $params = []) { $req = $url instanceof Request ? $url : $this->buildRequest('POST', $url); foreach ($params as $key => $value) { $req->addPostField($key, $value); } return $this->exec($req); }
Shortcut of POST request @param string|Request $url request URL string, or request object. @param array $params post fields. @return Response result response object.
entailment
public function put($url, $content = '') { $req = $url instanceof Request ? $url : $this->buildRequest('PUT', $url); $req->setBody($content); return $this->exec($req); }
Shortcut of PUT request @param string|Request $url request URL string, or request object. @param string $content content to be put. @return Response result response object.
entailment
public function getJson($url, $params = []) { $req = $this->buildRequest('GET', $url, $params); $req->setHeader('accept', 'application/json'); $res = $this->exec($req); return $res === false ? false : $res->getJson(); }
Shortcut of GET restful request as json format @param string $url request URL string. @param array $params extra query params, appended to URL. @return array result json data, or false on failure.
entailment
public function exec($req) { // build recs $recs = []; if ($req instanceof Request) { $recs[] = new Processor($this, $req); } elseif (is_array($req)) { foreach ($req as $key => $value) { if ($value instanceof Request) { $recs[$key] = new Processor($this, $value, $key); } } } if (count($recs) === 0) { return false; } // loop to process while (true) { // build select fds $rfds = $wfds = $xrec = []; $xfds = null; foreach ($recs as $rec) { /* @var $rec Processor */ self::$_processKey = $rec->key; if ($rec->finished || !($conn = $rec->getConn())) { continue; } if ($this->_timeout !== null) { $xrec[] = $rec; } $rfds[] = $conn->getSock(); if ($conn->hasDataToWrite()) { $wfds[] = $conn->getSock(); } } self::$_processKey = null; if (count($rfds) === 0 && count($wfds) === 0) { // all tasks finished break; } // select sockets self::debug('stream_select(rfds[', count($rfds), '], wfds[', count($wfds), ']) ...'); if ($this->_timeout === null) { $num = stream_select($rfds, $wfds, $xfds, null); } else { $sec = intval($this->_timeout); $usec = intval(($this->_timeout - $sec) * 1000000); $num = stream_select($rfds, $wfds, $xfds, $sec, $usec); } self::debug('select result: ', $num === false ? 'false' : $num); if ($num === false) { trigger_error('stream_select() error', E_USER_WARNING); break; } elseif ($num > 0) { // wfds foreach ($wfds as $sock) { if (!($conn = Connection::findBySock($sock))) { continue; } $rec = $conn->getExArg(); /* @var $rec Processor */ self::$_processKey = $rec->key; $rec->send(); } // rfds foreach ($rfds as $sock) { if (!($conn = Connection::findBySock($sock))) { continue; } $rec = $conn->getExArg(); /* @var $rec Processor */ self::$_processKey = $rec->key; $rec->recv(); } } else { // force to close request foreach ($xrec as $rec) { self::$_processKey = $rec->key; $rec->finish('TIMEOUT'); } } } // return value if (!is_array($req)) { $ret = $recs[0]->res; } else { $ret = []; foreach ($recs as $key => $rec) { $ret[$key] = $rec->res; } } return $ret; }
Execute http requests @param Request|Request[] $req the request object, or array of multiple requests @return Response|Response[] result response object, or response array for multiple requests
entailment
protected function buildRequest($method, $url, $params = []) { if (count($params) > 0) { $url .= strpos($url, '?') === false ? '?' : '&'; $url .= http_build_query($params); } return new Request($url, $method); }
Build a http request @param string $method @param string $url @param array $params @return Request
entailment
protected function buildRequests($method, $urls, $params = []) { $reqs = []; foreach ($urls as $key => $url) { $reqs[$key] = $this->buildRequest($method, $url, $params); } return $reqs; }
Build multiple http requests @param string $method @param array $urls @param array $params @return Request[]
entailment
public function generate(array $ast) : string { $this->traverser->traverse($ast); $generatedCode = parent::generate($ast); $className = trim($this->visitor->getNamespace() . '\\' . $this->visitor->getName(), '\\'); $fileName = $this->fileLocator->getGeneratedClassFileName($className); $tmpFileName = $fileName . '.' . uniqid('', true); // renaming files is necessary to avoid race conditions when the same file is written multiple times // in a short time period file_put_contents($tmpFileName, "<?php\n\n" . $generatedCode); rename($tmpFileName, $fileName); return $generatedCode; }
Write generated code to disk and return the class code {@inheritDoc} @throws \CodeGenerationUtils\Visitor\Exception\UnexpectedValueException
entailment
public function contentcontrollerInit() { // only call custom script if page has Slides and DataExtension if (DataObject::has_extension($this->owner->Classname, FlexSlider::class)) { if ($this->owner->getSlideShow()->exists()) { $this->getCustomScript(); } } }
add requirements to PageController init()
entailment
public function call(string $method, array $parameters) { if ($this->isSingleRequest) { $this->units = []; } $this->units[] = new Invoke($this->generatorId->get(), $method, $parameters); if ($this->isSingleRequest) { $resultSpecifier = $this->execute(new InvokeSpec($this->units, true)); if (!$resultSpecifier->isSingleResult()) { throw new InvalidResponseException(); } list($result) = $resultSpecifier->getResults(); if ($result instanceof Result) { /** @var Result $result */ return $result->getResult(); } elseif ($result instanceof Error) { /** @var Error $result */ if ($this->serverErrorMode === self::ERRMODE_EXCEPTION) { throw $result->getBaseException(); } } return null; } return $this; }
Make request @param string $method @param array $parameters @return $this|mixed @throws JsonRpcException
entailment
public function notification(string $method, array $parameters) { if ($this->isSingleRequest) { $this->units = []; } $this->units[] = new Notification($method, $parameters); if ($this->isSingleRequest) { $this->execute(new InvokeSpec($this->units, true)); return null; } return $this; }
Make notification request @param string $method @param array $parameters @return $this|null
entailment
public function batchExecute() { $results = $this->execute(new InvokeSpec($this->units, false))->getResults(); // Make right order in sequence of results. It's required operation, because JSON-RPC2 // specification define: "The Response objects being returned from a batch call MAY be returned // in any order within the Array. The Client SHOULD match contexts between the set of Request objects and the // resulting set of Response objects based on the id member within each Object." $callMap = []; foreach ($this->units as $index => $unit) { /** @var Invoke $unit */ $callMap[$unit->getRawId()] = $index; } if (count($results) !== count($this->units)) { throw new InvalidResponseException(); } $resultSequence = []; foreach ($results as $result) { if ($result instanceof Result) { /** @var Result $result */ $resultSequence[ $callMap[$result->getId()] ] = $result->getResult(); } elseif ($result instanceof Error) { /** @var Error $result */ $resultSequence[ $callMap[$result->getId()] ] = $this->serverErrorMode === self::ERRMODE_EXCEPTION ? $result->getBaseException() : null; } } ksort($resultSequence); $this->units = []; return $resultSequence; }
Execute batch request @return array
entailment
private function execute(InvokeSpec $call): ResultSpec { $request = $this->requestBuilder->build($call); $response = $this->transport->request($request); return $this->responseParser->parse($response); }
@param InvokeSpec $call @return ResultSpec
entailment
protected function compile() { $intCatIdAllowed = false; /* if ($this->intKatID == 0) //direkter Aufruf ohne ID { $objVisitorsKatID = \Database::getInstance() ->prepare("SELECT MIN(pid) AS ANZ FROM tl_visitors") ->execute(); $objVisitorsKatID->next(); if ($objVisitorsKatID->ANZ === null) { $this->intKatID = 0; } else { $this->intKatID = $objVisitorsKatID->ANZ; } }*/ //alle Kategorien holen die der User sehen darf $arrVisitorCategories = $this->getVisitorCategoriesByUsergroups(); // no categories : array('id' => '0', 'title' => '---------'); // empty array : array('id' => '0', 'title' => '---------'); // array[0..n] : array(0, array('id' => '1', ....), 1, ....) if ($this->intKatID == 0) //direkter Aufruf ohne ID { $this->intKatID = $this->getCatIdByCategories($arrVisitorCategories); $this->boolAllowReset = $this->isUserInVisitorStatisticResetGroups($this->intKatID); } else { // ID des Aufrufes erlaubt? foreach ($arrVisitorCategories as $value) { if ($this->intKatID == $value['id']) { $intCatIdAllowed = true; } } if ( false === $intCatIdAllowed ) { $this->intKatID = $this->getCatIdByCategories($arrVisitorCategories); } } // Alle Zähler je Kat holen, die Aktiven zuerst $objVisitorsX = \Database::getInstance() ->prepare("SELECT id FROM tl_visitors WHERE pid=? ORDER BY published DESC,id") ->execute($this->intKatID); $intRowsX = $objVisitorsX->numRows; $intAnzCounter=0; if ($intRowsX>0) { //Vorbereiten Chart $ModuleVisitorCharts = new ModuleVisitorCharts(); $ModuleVisitorCharts->setName($GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['visit'].' (<span style="color:red">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['chart_red'].'</span>)'); $ModuleVisitorCharts->setName2($GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['hit'].' (<span style="color:green">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['chart_green'].'</span>)'); $ModuleVisitorCharts->setHeight(270); // setMaxvalueHeight + 20 + 20 +10 $ModuleVisitorCharts->setWidth(330); $ModuleVisitorCharts->setMaxvalueHeight(220); // Balkenhöhe setzen while ($objVisitorsX->next()) { // 14 Tages Stat [0..13] und Vorgabewerte [100,104,110] (ehemals 7) $arrVisitorsStatDays[$intAnzCounter] = $this->getFourteenDays($this->intKatID,$objVisitorsX->id); $objVisitorsID = $arrVisitorsStatDays[$intAnzCounter][104]['VisitorsID']; //Monat Stat $arrVisitorsStatMonth[$intAnzCounter] = $this->getMonth($objVisitorsID); //Other Monat Stat $arrVisitorsStatOtherMonth[$intAnzCounter] = $this->getOtherMonth($objVisitorsID); //Other Year Stat $arrVisitorsStatOtherYears[$intAnzCounter] = $this->getOtherYears($objVisitorsID); //Total Visits Hits $arrVisitorsStatTotal[$intAnzCounter] = $this->getTotal($objVisitorsID); // Durchschnittswerte $arrVisitorsStatAverage[$intAnzCounter] = $this->getAverage($objVisitorsID); // Week Stat $arrVisitorsStatWeek[$intAnzCounter] = $this->getWeeks($objVisitorsID); // Online $arrVisitorsStatOnline[$intAnzCounter] = $this->getVisitorsOnline($objVisitorsID); //BestDay $arrVisitorsStatBestDay[$intAnzCounter] = $this->getBestDay($objVisitorsID); //BadDay $arrVisitorsStatBadDay[$intAnzCounter] = $this->getBadDay($objVisitorsID); //Chart //Debug log_message(print_r(array_reverse($arrVisitorsStatDays[$intAnzCounter]),true), 'debug.log'); $day = 0; $days = count($arrVisitorsStatDays[$intAnzCounter]); foreach (array_reverse($arrVisitorsStatDays[$intAnzCounter]) as $key => $valuexy) { if (isset($valuexy['visitors_date_ymd'])) { $day++; if ($days - $day < 17) { //Debug log_message(print_r(substr($valuexy['visitors_date'],0,2),true), 'debug.log'); //Debug log_message(print_r($valuexy['visitors_visit'],true), 'debug.log'); // chart resetten, wie? fehlt noch $ModuleVisitorCharts->addX(substr($valuexy['visitors_date_ymd'],8,2).'<br>'.substr($valuexy['visitors_date_ymd'],5,2)); $ModuleVisitorCharts->addY(str_replace(array('.',',',' ','\''),array('','','',''),$valuexy['visitors_visit'])); // Formatierte Zahl wieder in reine Zahl $ModuleVisitorCharts->addY2(str_replace(array('.',',',' ','\''),array('','','',''),$valuexy['visitors_hit'])); // Formatierte Zahl wieder in reine Zahl } } } $arrVisitorsChart[$intAnzCounter] = $ModuleVisitorCharts->display(false); //Page Hits $arrVisitorsPageVisitHits[$intAnzCounter] = ModuleVisitorStatPageCounter::getInstance()->generatePageVisitHitTop($objVisitorsID,20); $arrVisitorsPageVisitHitsDays[$intAnzCounter] = ModuleVisitorStatPageCounter::getInstance()->generatePageVisitHitDays($objVisitorsID,20,7); $arrVisitorsPageVisitHitsToday[$intAnzCounter] = ModuleVisitorStatPageCounter::getInstance()->generatePageVisitHitToday($objVisitorsID,5); $arrVisitorsPageVisitHitsYesterday[$intAnzCounter] = ModuleVisitorStatPageCounter::getInstance()->generatePageVisitHitYesterday($objVisitorsID,5); // News $arrVisitorsNewsVisitHits[$intAnzCounter] = ModuleVisitorStatNewsFaqCounter::getInstance()->generateNewsVisitHitTop($objVisitorsID,10,true); // Faq $arrVisitorsFaqVisitHits[$intAnzCounter] = ModuleVisitorStatNewsFaqCounter::getInstance()->generateFaqVisitHitTop($objVisitorsID,10,true); // Isotope $arrVisitorsIsotopeVisitHits[$intAnzCounter] = ModuleVisitorStatIsotopeProductCounter::getInstance()->generateIsotopeVisitHitTop($objVisitorsID,20,true); //Browser $arrVSB = $this->getBrowserTop($objVisitorsID); $arrVisitorsStatBrowser[$intAnzCounter] = $arrVSB['TOP']; $arrVisitorsStatBrowser2[$intAnzCounter] = $arrVSB['TOP2']; $arrVisitorsStatBrowserDefinition[$intAnzCounter] = $arrVSB['DEF']; //Referrer $arrVisitorsStatReferrer[$intAnzCounter] = $this->getReferrerTop($objVisitorsID); //Screen Resolutions $arrVisitorsScreenTopResolution[$intAnzCounter] = ModuleVisitorStatScreenCounter::getInstance()->generateScreenTopResolution($objVisitorsID,20); $arrVisitorsScreenTopResolutionDays[$intAnzCounter] = ModuleVisitorStatScreenCounter::getInstance()->generateScreenTopResolutionDays($objVisitorsID,20,30); $intAnzCounter++; } //while X next } // if intRowsX >0 if (!isset($GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['footer'])) { $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['footer'] = ''; } // Version, Base, Footer $this->Template->visitors_version = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['modname'] . ' ' . VISITORS_VERSION .'.'. VISITORS_BUILD; $this->Template->visitors_base = \Environment::get('base'); $this->Template->visitors_footer = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['footer']; $this->Template->theme = $this->getTheme(); $this->Template->theme0 = 'bundles/bugbustervisitors/flexible'; // for down0.gif $this->Template->allow_reset = $this->boolAllowReset; $this->Template->visitorsanzcounter = $intAnzCounter; $this->Template->visitorsstatDays = $arrVisitorsStatDays; $this->Template->visitorsstatWeeks = $arrVisitorsStatWeek; $this->Template->visitorsstatMonths = $arrVisitorsStatMonth; $this->Template->visitorsstatOtherMonths = $arrVisitorsStatOtherMonth; $this->Template->visitorsstatOtherYears = $arrVisitorsStatOtherYears; $this->Template->visitorsstatTotals = $arrVisitorsStatTotal; $this->Template->visitorsstatAverages = $arrVisitorsStatAverage; $this->Template->visitorsstatOnline = $arrVisitorsStatOnline; $this->Template->visitorsstatBestDay = $arrVisitorsStatBestDay; $this->Template->visitorsstatBadDay = $arrVisitorsStatBadDay; $this->Template->visitorsstatChart = $arrVisitorsChart; $this->Template->visitorsstatPageVisitHits = $arrVisitorsPageVisitHits; $this->Template->visitorsstatPageVisitHitsDays = $arrVisitorsPageVisitHitsDays; $this->Template->visitorsstatPageVisitHitsToday = $arrVisitorsPageVisitHitsToday; $this->Template->visitorsstatPageVisitHitsYesterday = $arrVisitorsPageVisitHitsYesterday; $this->Template->visitorsstatNewsVisitHits = $arrVisitorsNewsVisitHits; $this->Template->visitorsstatFaqVisitHits = $arrVisitorsFaqVisitHits; $this->Template->visitorsstatIsotopeVisitHits = $arrVisitorsIsotopeVisitHits; $this->Template->visitorsstatBrowser = $arrVisitorsStatBrowser; $this->Template->visitorsstatBrowser2 = $arrVisitorsStatBrowser2; $this->Template->visitorsstatBrowserDefinition = $arrVisitorsStatBrowserDefinition; $this->Template->visitorsstatReferrer = $arrVisitorsStatReferrer; $this->Template->visitorsstatScreenTop = $arrVisitorsScreenTopResolution; $this->Template->visitorsstatScreenTopDays = $arrVisitorsScreenTopResolutionDays; //Debug log_message(print_r($this->Template->visitorsstatBrowser,true), 'debug.log'); //Debug log_message(print_r($this->Template->visitorsstatAverages,true), 'debug.log'); // Kat sammeln $this->Template->visitorskats = $arrVisitorCategories; $this->Template->visitorskatid = $this->intKatID; $this->Template->visitorsstatkat = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['kat']; $this->Template->visitors_export_title = $GLOBALS['TL_LANG']['tl_visitors_stat_export']['export_button_title']; $this->Template->visitors_exportfield = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['kat'].' '.$GLOBALS['TL_LANG']['tl_visitors_stat_export']['export']; //ExportDays $this->Template->visitors_export_days = (isset($_SESSION['VISITORS_EXPORT_DAYS'])) ? $_SESSION['VISITORS_EXPORT_DAYS'] : 365; //SearchEngines $arrSE = $this->getSearchEngine($this->intKatID); if ($arrSE !== false) { $this->Template->visitorssearchengines = $arrSE['SearchEngines']; $this->Template->visitorssearchenginekeywords = $arrSE['SearchEngineKeywords']; } else { $this->Template->visitorssearchengine = false; } }
Generate module
entailment
protected function getFourteenDays($KatID, $VisitorsXid) { $visitors_today_visit = 0; $visitors_today_hit = 0; $visitors_yesterday_visit = 0; $visitors_yesterday_hit = 0; $visitors_visit_start = 0; $visitors_hit_start = 0; $visitors_day_of_week_prefix = ''; //Anzahl Tage zu erst auslesen die angezeigt werden sollen $objVisitors = \Database::getInstance()->prepare("SELECT tv.visitors_statistic_days FROM tl_visitors tv WHERE tv.pid = ? AND tv.id = ?") ->limit(1) ->execute($KatID, $VisitorsXid); while ($objVisitors->next()) { $visitors_statistic_days = $objVisitors->visitors_statistic_days; } if ($visitors_statistic_days < 14) { $visitors_statistic_days = 14; } if ($visitors_statistic_days > 99) { $visitors_statistic_days = 99; } // 7 Tages Statistik und Vorgabewerte $objVisitors = \Database::getInstance() ->prepare("SELECT tv.id, tv.visitors_name, tv.visitors_startdate, tv.visitors_visit_start, tv.visitors_hit_start, tv.published, tvc.visitors_date, tvc.visitors_visit, tvc.visitors_hit FROM tl_visitors tv, tl_visitors_counter tvc WHERE tv.id = tvc.vid AND tv.pid = ? AND tv.id = ? ORDER BY tv.visitors_name , tvc.visitors_date DESC") ->limit($visitors_statistic_days) ->execute($KatID, $VisitorsXid); $intRowsVisitors = $objVisitors->numRows; if ($intRowsVisitors>0) { // Zählungen vorhanden while ($objVisitors->next()) { if ($objVisitors->published == 1) { $objVisitors->published = '<span class="visitors_stat_yes">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['pub_yes'].'</span>'; } else { $objVisitors->published = '<span class="visitors_stat_no">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['pub_no'].'</span>'; } if (!strlen($objVisitors->visitors_startdate)) { $visitors_startdate = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['startdate_not_defined']; } else { $visitors_startdate = $this->parseDateVisitors($GLOBALS['TL_LANGUAGE'], $objVisitors->visitors_startdate); } // day of the week prüfen if (strpos($GLOBALS['TL_CONFIG']['dateFormat'],'D')===false // day of the week short && strpos($GLOBALS['TL_CONFIG']['dateFormat'],'l')===false) // day of the week long { $visitors_day_of_week_prefix = 'D, '; } $arrVisitorsStat[] = array ( 'visitors_id' => $objVisitors->id, 'visitors_name' => \StringUtil::specialchars(ampersand($objVisitors->visitors_name)), 'visitors_active' => $objVisitors->published, 'visitors_date' => $this->parseDateVisitors($GLOBALS['TL_LANGUAGE'], strtotime($objVisitors->visitors_date), $visitors_day_of_week_prefix), 'visitors_date_ymd' => $objVisitors->visitors_date, 'visitors_startdate' => $visitors_startdate, 'visitors_visit' => $this->getFormattedNumber($objVisitors->visitors_visit,0), 'visitors_hit' => $this->getFormattedNumber($objVisitors->visitors_hit,0) ); if ($objVisitors->visitors_date == date("Y-m-d")) { $visitors_today_visit = $objVisitors->visitors_visit; $visitors_today_hit = $objVisitors->visitors_hit; } if ($objVisitors->visitors_date == date("Y-m-d", time()-(60*60*24))) { $visitors_yesterday_visit = $objVisitors->visitors_visit; $visitors_yesterday_hit = $objVisitors->visitors_hit; } } // while $arrVisitorsStat[104]['VisitorsID'] = $objVisitors->id; $visitors_visit_start = $objVisitors->visitors_visit_start; $visitors_hit_start = $objVisitors->visitors_hit_start; } else { $objVisitors = \Database::getInstance() ->prepare("SELECT tv.id, tv.visitors_name, tv.visitors_startdate, tv.published FROM tl_visitors tv WHERE tv.pid = ? AND tv.id = ? ORDER BY tv.visitors_name") ->limit(1) ->execute($KatID, $VisitorsXid); $objVisitors->next(); if ($objVisitors->published == 1) { $objVisitors->published = '<span class="visitors_stat_yes">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['pub_yes'].'</span>'; } else { $objVisitors->published = '<span class="visitors_stat_no">'.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['pub_no'].'</span>'; } if (!strlen($objVisitors->visitors_startdate)) { $visitors_startdate = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['startdate_not_defined']; } else { $visitors_startdate = $this->parseDateVisitors($GLOBALS['TL_LANGUAGE'],$objVisitors->visitors_startdate); } $arrVisitorsStat[] = array ( 'visitors_id' => $objVisitors->id, 'visitors_name' => \StringUtil::specialchars(ampersand($objVisitors->visitors_name)), 'visitors_active' => $objVisitors->published, 'visitors_startdate' => $visitors_startdate ); $arrVisitorsStat[104]['VisitorsID'] = 0; } $arrVisitorsStat[100]['visitors_today_visit'] = $this->getFormattedNumber($visitors_today_visit,0); $arrVisitorsStat[100]['visitors_today_hit'] = $this->getFormattedNumber($visitors_today_hit,0); $arrVisitorsStat[100]['visitors_yesterday_visit'] = $this->getFormattedNumber($visitors_yesterday_visit,0); $arrVisitorsStat[100]['visitors_yesterday_hit'] = $this->getFormattedNumber($visitors_yesterday_hit,0); $arrVisitorsStat[110]['visitors_visit_start'] = $this->getFormattedNumber($visitors_visit_start,0); $arrVisitorsStat[110]['visitors_hit_start'] = $this->getFormattedNumber($visitors_hit_start,0); return $arrVisitorsStat; }
14 Tagesstat und Vorgabewerte
entailment
protected function getMonth($VisitorsID) { $LastMonthVisits = 0; $LastMonthHits = 0; $CurrentMonthVisits = 0; $CurrentMonthHits = 0; $YearCurrentMonth = date('Y-m-d'); $YearLastMonth = date('Y-m-d' ,mktime(0, 0, 0, date("m")-1, 1, date("Y"))); $CurrentMonth = (int)date('m'); $LastMonth = (int)date('m',mktime(0, 0, 0, date("m")-1, 1, date("Y"))); $ORDER = ($CurrentMonth > $LastMonth) ? 'DESC' : 'ASC'; // damit immer eine absteigene Monatsreihenfolge kommt if ($VisitorsID) { $sqlMonth = 'SELECT EXTRACT( MONTH FROM visitors_date ) AS M, SUM( visitors_visit ) AS SUMV , SUM( visitors_hit ) AS SUMH FROM tl_visitors_counter WHERE vid=? AND visitors_date BETWEEN ? AND ? GROUP BY M ORDER BY M %s'; $sqlMonth = sprintf($sqlMonth, $ORDER); //Total je Monat (aktueller und letzter) $objVisitorsToMo = \Database::getInstance() ->prepare($sqlMonth) ->limit(2) ->execute($VisitorsID, $YearLastMonth, $YearCurrentMonth); $intRows = $objVisitorsToMo->numRows; if ($intRows>0) { $objVisitorsToMo->next(); if ( (int)$objVisitorsToMo->M == (int)date('m') ) { $CurrentMonthVisits = $objVisitorsToMo->SUMV; $CurrentMonthHits = $objVisitorsToMo->SUMH; } if ( (int)$objVisitorsToMo->M == (int)date('m',mktime(0, 0, 0, date("m")-1, 1, date("Y"))) ) { $LastMonthVisits = $objVisitorsToMo->SUMV; $LastMonthHits = $objVisitorsToMo->SUMH; } if ($intRows==2) { $objVisitorsToMo->next(); if ( (int)$objVisitorsToMo->M == (int)date('m',mktime(0, 0, 0, date("m")-1, 1, date("Y"))) ) { $LastMonthVisits = $objVisitorsToMo->SUMV; $LastMonthHits = $objVisitorsToMo->SUMH; } } } } return array('LastMonthVisits' => $this->getFormattedNumber($LastMonthVisits,0), 'LastMonthHits' => $this->getFormattedNumber($LastMonthHits,0), 'CurrentMonthVisits' => $this->getFormattedNumber($CurrentMonthVisits,0), 'CurrentMonthHits' => $this->getFormattedNumber($CurrentMonthHits,0) ); }
Monatswerte (Aktueller und Letzer)
entailment
protected function getOtherMonth($VisitorsID) { $StartMonth = date('Y-m-d',mktime(0, 0, 0, date("m")-11, 1, date("Y"))); // aktueller Monat -11 $EndMonth = date('Y-m-d',mktime(0, 0, 0, date("m")-1 , 0, date("Y"))); // letzter Tag des vorletzten Monats if ($VisitorsID) { //Total je Monat (aktueller und letzter) $objVisitorsToMo = \Database::getInstance() ->prepare('SELECT EXTRACT( YEAR FROM visitors_date ) AS Y, EXTRACT( MONTH FROM visitors_date ) AS M, SUM( visitors_visit ) AS SUMV, SUM( visitors_hit ) AS SUMH FROM tl_visitors_counter WHERE vid=? AND visitors_date BETWEEN ? AND ? GROUP BY Y, M ORDER BY Y DESC, M DESC') ->execute($VisitorsID,$StartMonth,$EndMonth); $intRows = $objVisitorsToMo->numRows; $arrOtherMonth = array(); if ($intRows>0) { while ($objVisitorsToMo->next()) { $arrOtherMonth[] = array($objVisitorsToMo->Y, $GLOBALS['TL_LANG']['MONTHS'][($objVisitorsToMo->M - 1)], $this->getFormattedNumber($objVisitorsToMo->SUMV,0), $this->getFormattedNumber($objVisitorsToMo->SUMH,0) ); } } } return $arrOtherMonth; }
Monatswerte (Vorletzter und älter, max 10)
entailment
protected function getOtherYears($VisitorsID) { $StartYear = date('Y-m-d',mktime(0, 0, 0, 1, 1, date("Y")-11)); // aktuelles Jahr -11 $EndYear = date('Y-m-d'); // Aktuelles Datum if ($VisitorsID) { //Total je Monat (aktueller und letzter) $objVisitorsToYear = \Database::getInstance() ->prepare('SELECT EXTRACT( YEAR FROM visitors_date ) AS Y, SUM( visitors_visit ) AS SUMV, SUM( visitors_hit ) AS SUMH FROM tl_visitors_counter WHERE vid=? AND visitors_date BETWEEN ? AND ? GROUP BY Y ORDER BY Y DESC') ->execute($VisitorsID,$StartYear,$EndYear); $intRows = $objVisitorsToYear->numRows; $arrOtherYear = array(); if ($intRows>0) { while ($objVisitorsToYear->next()) { $arrOtherYear[] = array($objVisitorsToYear->Y, $this->getFormattedNumber($objVisitorsToYear->SUMV,0), $this->getFormattedNumber($objVisitorsToYear->SUMH,0) ); } } } return $arrOtherYear; }
Jahreswerte (Aktuelles und älter (10) = max 11)
entailment
protected function getAverage($VisitorsID) { $VisitorsAverageVisits = 0; $VisitorsAverageHits = 0; $VisitorsAverageVisits30 = 0; $VisitorsAverageHits30 = 0; $VisitorsAverageVisits60 = 0; $VisitorsAverageHits60 = 0; $tmpTotalDays = 0; if ($VisitorsID) { $today = date('Y-m-d'); $yesterday = date('Y-m-d',mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); //Durchschnittswerte bis heute 00:00 Uhr, also bis einschließlich gestern $objVisitorsAverageCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV, SUM(visitors_hit) AS SUMH, MIN( visitors_date ) AS MINDAY FROM tl_visitors_counter WHERE vid=? AND visitors_date<?") ->execute($VisitorsID,$today); if ($objVisitorsAverageCount->numRows > 0) { $objVisitorsAverageCount->next(); $tmpTotalDays = floor(1+(strtotime($yesterday) - strtotime($objVisitorsAverageCount->MINDAY))/60/60/24 ); $VisitorsAverageVisitCount = ($objVisitorsAverageCount->SUMV === null) ? 0 : $objVisitorsAverageCount->SUMV; $VisitorsAverageHitCount = ($objVisitorsAverageCount->SUMH === null) ? 0 : $objVisitorsAverageCount->SUMH; if ($tmpTotalDays >0) { $VisitorsAverageVisits = $this->getFormattedNumber($VisitorsAverageVisitCount / $tmpTotalDays , 2); $VisitorsAverageHits = $this->getFormattedNumber($VisitorsAverageHitCount / $tmpTotalDays , 2); } } if ($tmpTotalDays > 30) { //Durchschnittswerte der letzten 30 Tage $day30 = date('Y-m-d',mktime(0, 0, 0, date("m")-1 , date("d")-1 ,date("Y"))); $objVisitorsAverageCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV, SUM(visitors_hit) AS SUMH FROM tl_visitors_counter WHERE vid=? AND visitors_date BETWEEN ? AND ?") ->execute($VisitorsID,$day30,$yesterday); if ($objVisitorsAverageCount->numRows > 0) { $objVisitorsAverageCount->next(); $VisitorsAverageVisitCount = ($objVisitorsAverageCount->SUMV === null) ? 0 : $objVisitorsAverageCount->SUMV; $VisitorsAverageHitCount = ($objVisitorsAverageCount->SUMH === null) ? 0 : $objVisitorsAverageCount->SUMH; $VisitorsAverageVisits30 = $this->getFormattedNumber($VisitorsAverageVisitCount / 30 , 2); $VisitorsAverageHits30 = $this->getFormattedNumber($VisitorsAverageHitCount / 30 , 2); } } if ($tmpTotalDays > 60) { //Durchschnittswerte der letzten 60 Tage $day60 = date('Y-m-d',mktime(0, 0, 0, date("m")-2 , date("d")-1 ,date("Y"))); $objVisitorsAverageCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV, SUM(visitors_hit) AS SUMH FROM tl_visitors_counter WHERE vid=? AND visitors_date BETWEEN ? AND ?") ->execute($VisitorsID,$day60,$yesterday); if ($objVisitorsAverageCount->numRows > 0) { $objVisitorsAverageCount->next(); $VisitorsAverageVisitCount = ($objVisitorsAverageCount->SUMV === null) ? 0 : $objVisitorsAverageCount->SUMV; $VisitorsAverageHitCount = ($objVisitorsAverageCount->SUMH === null) ? 0 : $objVisitorsAverageCount->SUMH; $VisitorsAverageVisits60 = $this->getFormattedNumber($VisitorsAverageVisitCount / 60 , 2); $VisitorsAverageHits60 = $this->getFormattedNumber($VisitorsAverageHitCount / 60 , 2); } } } return array('VisitorsAverageVisits' => $VisitorsAverageVisits, 'VisitorsAverageHits' => $VisitorsAverageHits, 'VisitorsAverageDays' => "&nbsp;", //$tmpTotalDays, 'VisitorsAverageVisits30' => $VisitorsAverageVisits30, 'VisitorsAverageHits30' => $VisitorsAverageHits30, 'VisitorsAverageDays30' => ($VisitorsAverageHits30 === 0) ? '<span class="mod_visitors_be_average_nodata">(30)&nbsp;</span>' : '(30)&nbsp;', 'VisitorsAverageVisits60' => $VisitorsAverageVisits60, 'VisitorsAverageHits60' => $VisitorsAverageHits60, 'VisitorsAverageDays60' => ($VisitorsAverageHits60 === 0) ? '<span class="mod_visitors_be_average_nodata">(60)&nbsp;</span>' : '(60)&nbsp;', ); }
Average Stat
entailment
protected function getWeeks($VisitorsID) { /* * YEARWEEK('2013-12-31', 3) ergibt 201401 (iso Jahr der iso Woche)! * muss so sein, da sonst between nicht funktioniert * (Current muss größer sein als Last) * daher muss PHP auch das ISO Jahr zurückgeben! */ $LastWeekVisits = 0; $LastWeekHits = 0; $CurrentWeekVisits = 0; $CurrentWeekHits = 0; $CurrentWeek = date('W'); $LastWeek = date('W', mktime(0, 0, 0, date("m"), date("d")-7, date("Y")) ); $YearCurrentWeek = date('o'); $YearLastWeek = date('o', mktime(0, 0, 0, date("m"), date("d")-7, date("Y")) ); if ($VisitorsID) { //Total je Woche (aktuelle und letzte) $objVisitorsToWe = \Database::getInstance() ->prepare('SELECT YEARWEEK(visitors_date, 3) AS YW, SUM(visitors_visit) AS SUMV, SUM(visitors_hit) AS SUMH FROM tl_visitors_counter WHERE vid = ? AND YEARWEEK(visitors_date, 3) BETWEEN ? AND ? GROUP BY YW ORDER BY YW DESC') ->limit(2) ->execute($VisitorsID,$YearLastWeek.$LastWeek,$YearCurrentWeek.$CurrentWeek); $intRows = $objVisitorsToWe->numRows; if ($intRows>0) { $objVisitorsToWe->next(); if ($objVisitorsToWe->YW == $YearCurrentWeek.$CurrentWeek) { $CurrentWeekVisits = $objVisitorsToWe->SUMV; $CurrentWeekHits = $objVisitorsToWe->SUMH; } if ($objVisitorsToWe->YW == $YearLastWeek.$LastWeek) { $LastWeekVisits = $objVisitorsToWe->SUMV; $LastWeekHits = $objVisitorsToWe->SUMH; } if ($intRows==2) { $objVisitorsToWe->next(); if ($objVisitorsToWe->YW == $YearLastWeek.$LastWeek) { $LastWeekVisits = $objVisitorsToWe->SUMV; $LastWeekHits = $objVisitorsToWe->SUMH; } } } } return array('LastWeekVisits' => $this->getFormattedNumber($LastWeekVisits,0), 'LastWeekHits' => $this->getFormattedNumber($LastWeekHits,0), 'CurrentWeekVisits'=> $this->getFormattedNumber($CurrentWeekVisits,0), 'CurrentWeekHits' => $this->getFormattedNumber($CurrentWeekHits,0) ); }
Wochenwerte
entailment
protected function getTotal($VisitorsID) { $VisitorsTotalVisitCount = 0; $VisitorsTotalHitCount = 0; if ($VisitorsID) { //Total seit Zählung $objVisitorsTotalCount = \Database::getInstance() ->prepare("SELECT SUM(visitors_visit) AS SUMV, SUM(visitors_hit) AS SUMH FROM tl_visitors_counter WHERE vid=?") ->execute($VisitorsID); if ($objVisitorsTotalCount->numRows > 0) { $objVisitorsTotalCount->next(); $VisitorsTotalVisitCount = ($objVisitorsTotalCount->SUMV === null) ? 0 : $objVisitorsTotalCount->SUMV; $VisitorsTotalHitCount = ($objVisitorsTotalCount->SUMH === null) ? 0 : $objVisitorsTotalCount->SUMH; } } return array('VisitorsTotalVisitCount' => $this->getFormattedNumber($VisitorsTotalVisitCount,0), 'VisitorsTotalHitCount' => $this->getFormattedNumber($VisitorsTotalHitCount,0) ); }
Total Hits und Visits
entailment
protected function setZero() { if (false === $this->boolAllowReset) { return ; } $intCID = preg_replace('@\D@', '', \Input::get('zid')); // only digits if ($intCID>0) { // mal sehen ob ein Startdatum gesetzt war $objVisitorsDate = \Database::getInstance() ->prepare("SELECT visitors_startdate FROM tl_visitors WHERE id=?") ->execute($intCID); $objVisitorsDate->next(); if (0 < (int)$objVisitorsDate->visitors_startdate) { // ok es war eins gesetzt, dann setzen wir es wieder \Database::getInstance() ->prepare("UPDATE tl_visitors SET tstamp=?, visitors_startdate=? WHERE id=?") ->execute( time(), strtotime(date('Y-m-d')), $intCID ); } // und nun die eigendlichen counter \Database::getInstance() ->prepare("DELETE FROM tl_visitors_counter WHERE vid=?") ->execute($intCID); \Database::getInstance() ->prepare("DELETE FROM tl_visitors_blocker WHERE vid=?") ->execute($intCID); \Database::getInstance() ->prepare("DELETE FROM tl_visitors_browser WHERE vid=?") ->execute($intCID); \Database::getInstance() ->prepare("DELETE FROM tl_visitors_pages WHERE vid=?") ->execute($intCID); \Database::getInstance() ->prepare("DELETE FROM tl_visitors_screen_counter WHERE vid=?") ->execute($intCID); } return ; }
Statistic, set on zero
entailment
protected function setZeroBrowser() { if (false === $this->boolAllowReset) { return ; } $intCID = preg_replace('@\D@', '', \Input::get('zid')); // only digits if ($intCID>0) { // Browser \Database::getInstance() ->prepare("DELETE FROM tl_visitors_browser WHERE vid=?") ->execute($intCID); } return ; }
Statistic, set on zero
entailment
protected function getBrowserTop($VisitorsID) { $topNo = 20; $VisitorsBrowserVersion = array(); $VisitorsBrowserLang = array(); $VisitorsBrowserOS = array(); if ($VisitorsID) { //Version $objVisitorsBrowserVersion = \Database::getInstance() ->prepare("SELECT `visitors_browser`, SUM(`visitors_counter`) AS SUMBV FROM tl_visitors_browser WHERE vid=? AND visitors_browser !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=? GROUP BY `visitors_browser` ORDER BY SUMBV DESC, visitors_browser ASC") ->limit($topNo) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserVersion->numRows > 0) { while ($objVisitorsBrowserVersion->next()) { $VisitorsBrowserVersion[] = array($objVisitorsBrowserVersion->visitors_browser, $objVisitorsBrowserVersion->SUMBV); } } //Version without number $objVisitorsBrowserVersion2 = \Database::getInstance() ->prepare("SELECT visitors_browser, SUM(`visitors_counter`) AS SUMBV FROM (SELECT SUBSTRING_INDEX(`visitors_browser`,' ',1) AS visitors_browser, `visitors_counter` FROM tl_visitors_browser WHERE vid=? AND visitors_browser !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=? ) AS A GROUP BY `visitors_browser` ORDER BY SUMBV DESC, visitors_browser ASC") ->limit(10) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserVersion2->numRows > 0) { while ($objVisitorsBrowserVersion2->next()) { $VisitorsBrowserVersion2[] = array($objVisitorsBrowserVersion2->visitors_browser, $objVisitorsBrowserVersion2->SUMBV); } } // Unknown Version $objVisitorsBrowserVersion = \Database::getInstance() ->prepare("SELECT SUM(`visitors_counter`) AS SUMBV FROM `tl_visitors_browser` WHERE `vid`=? AND `visitors_browser` =? AND `visitors_os` =?") //AND (visitors_browser =? OR SUBSTRING_INDEX(`visitors_browser`,' ',1) =?) //GROUP BY `visitors_browser` //ORDER BY SUMBV DESC, visitors_browser ASC" ->limit(1) ->execute($VisitorsID,'Unknown','Unknown'); // ,'Mozilla' if ($objVisitorsBrowserVersion->numRows > 0) { while ($objVisitorsBrowserVersion->next()) { $VisitorsBrowserVersionUNK = $objVisitorsBrowserVersion->SUMBV; } } //Count all versions $objVisitorsBrowserVersion = \Database::getInstance() ->prepare("SELECT COUNT(DISTINCT `visitors_browser`) AS SUMBV FROM tl_visitors_browser WHERE vid=? AND visitors_browser !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=?") ->limit(1) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserVersion->numRows > 0) { while ($objVisitorsBrowserVersion->next()) { $VisitorsBrowserVersionKNO = $objVisitorsBrowserVersion->SUMBV; } } //Language $objVisitorsBrowserLang = \Database::getInstance() ->prepare("SELECT `visitors_lang`, SUM(`visitors_counter`) AS SUMBL FROM tl_visitors_browser WHERE vid=? AND `visitors_lang` !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=? GROUP BY `visitors_lang` ORDER BY SUMBL DESC, `visitors_lang` ASC") ->limit($topNo) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserLang->numRows > 0) { while ($objVisitorsBrowserLang->next()) { $VisitorsBrowserLang[] = array($objVisitorsBrowserLang->visitors_lang, $objVisitorsBrowserLang->SUMBL); } } //OS $objVisitorsBrowserOS = \Database::getInstance() ->prepare("SELECT `visitors_os`, SUM(`visitors_counter`) AS SUMBOS FROM tl_visitors_browser WHERE vid=? AND visitors_os !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=? GROUP BY `visitors_os` ORDER BY SUMBOS DESC, visitors_os ASC") ->limit($topNo) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserOS->numRows > 0) { while ($objVisitorsBrowserOS->next()) { $VisitorsBrowserOS[] = array($objVisitorsBrowserOS->visitors_os, $objVisitorsBrowserOS->SUMBOS); } } //Count all OS $objVisitorsBrowserOS = \Database::getInstance() ->prepare("SELECT COUNT(DISTINCT `visitors_os`) AS SUMBOS FROM tl_visitors_browser WHERE vid=? AND visitors_os !=? AND SUBSTRING_INDEX(`visitors_browser`,' ',1) !=?") ->limit(1) ->execute($VisitorsID,'Unknown','Mozilla'); if ($objVisitorsBrowserOS->numRows > 0) { while ($objVisitorsBrowserOS->next()) { $VisitorsBrowserOSALL = $objVisitorsBrowserOS->SUMBOS; } } } for ($BT=0; $BT<$topNo; $BT++) { $VisitorsBrowserVersion[$BT] = (isset($VisitorsBrowserVersion[$BT][0])) ? $VisitorsBrowserVersion[$BT] : '0'; $VisitorsBrowserLang[$BT] = (isset($VisitorsBrowserLang[$BT][0])) ? $VisitorsBrowserLang[$BT] : '0'; $VisitorsBrowserOS[$BT] = (isset($VisitorsBrowserOS[$BT][0])) ? $VisitorsBrowserOS[$BT] : '0'; //Platz 1-20 [0..19] $arrBrowserTop[$BT] = array($VisitorsBrowserVersion[$BT], $VisitorsBrowserLang[$BT],$VisitorsBrowserOS[$BT]); } $VisitorsBrowserVersionUNK = (isset($VisitorsBrowserVersionUNK)) ? $VisitorsBrowserVersionUNK : 0; $VisitorsBrowserVersionKNO = (isset($VisitorsBrowserVersionKNO)) ? $VisitorsBrowserVersionKNO : 0; $VisitorsBrowserOSALL = (isset($VisitorsBrowserOSALL)) ? $VisitorsBrowserOSALL : 0; //Version without number for ($BT=0; $BT<10; $BT++) { $VisitorsBrowserVersion2[$BT] = (isset($VisitorsBrowserVersion2[$BT][0])) ? $VisitorsBrowserVersion2[$BT] : array(0,0); } //Debug log_message(print_r($VisitorsBrowserVersion2,true), 'debug.log'); return array('TOP' =>$arrBrowserTop ,'TOP2'=>$VisitorsBrowserVersion2 ,'DEF' =>array('UNK' => $VisitorsBrowserVersionUNK, 'KNO' => $VisitorsBrowserVersionKNO, 'OSALL'=> $VisitorsBrowserOSALL)); }
TOP Browser
entailment
protected function getSearchEngine($VisitorsKatID) { $VisitorsSearchEngines = array(); // only searchengines $VisitorsSearchEngineKeywords = array(); //searchengine - keywords, order by keywords $day60 = mktime(0, 0, 0, date("m")-2 , date("d") ,date("Y")); $objVisitors = \Database::getInstance() ->prepare("SELECT tl_visitors.id AS id FROM tl_visitors LEFT JOIN tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid) WHERE tl_visitors.pid=? AND published=? ORDER BY id") ->limit(1) ->execute($VisitorsKatID,1); if ($objVisitors->numRows > 0) { $objVisitors->next(); $VisitorsID = $objVisitors->id; $objVisitorsSearchEngines = \Database::getInstance() ->prepare("SELECT `visitors_searchengine`, count(*) as anz FROM `tl_visitors_searchengines` WHERE `vid`=? AND `tstamp` > ? GROUP BY 1 ORDER BY anz DESC") ->limit(20) ->execute($VisitorsID,$day60); if ($objVisitorsSearchEngines->numRows > 0) { while ($objVisitorsSearchEngines->next()) { if ('Generic' == $objVisitorsSearchEngines->visitors_searchengine) { $objVisitorsSearchEngines->visitors_searchengine = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['searchengine_unknown']; } $VisitorsSearchEngines[] = array($objVisitorsSearchEngines->visitors_searchengine, $objVisitorsSearchEngines->anz); } } $objVisitorsSearchEngineKeywords = \Database::getInstance() ->prepare("SELECT `visitors_searchengine`, lower(`visitors_keywords`) AS keyword, count(*) AS anz FROM `tl_visitors_searchengines` WHERE `vid`=? AND `tstamp` > ? GROUP BY 1,2 ORDER BY anz DESC") ->limit(20) ->execute($VisitorsID,$day60); if ($objVisitorsSearchEngineKeywords->numRows > 0) { while ($objVisitorsSearchEngineKeywords->next()) { // Issue #67 if ('notdefined' == $objVisitorsSearchEngineKeywords->keyword) { $objVisitorsSearchEngineKeywords->keyword = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['not_defined']; } if ('Generic' == $objVisitorsSearchEngineKeywords->visitors_searchengine) { $objVisitorsSearchEngineKeywords->visitors_searchengine = $GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['searchengine_unknown']; } $VisitorsSearchEngineKeywords[] = array($objVisitorsSearchEngineKeywords->visitors_searchengine, $objVisitorsSearchEngineKeywords->keyword, $objVisitorsSearchEngineKeywords->anz); } } } if (0 == count($VisitorsSearchEngines) && 0 == count($VisitorsSearchEngineKeywords)) { return false; } return array('SearchEngines' => $VisitorsSearchEngines, 'SearchEngineKeywords' =>$VisitorsSearchEngineKeywords); }
TOP 20 SearchEngine @param integer $VisitorsID Category-ID des Zählers @return array
entailment
protected function getReferrerTop($VisitorsID) { $topNo = 30; $VisitorsReferrerTop = array(); if ($VisitorsID) { //Version $objVisitorsReferrerTop = \Database::getInstance() ->prepare("SELECT `visitors_referrer_dns`, count(`id`) AS SUMRT FROM tl_visitors_referrer WHERE vid=? GROUP BY `visitors_referrer_dns` ORDER BY SUMRT DESC, visitors_referrer_dns ASC") ->limit($topNo) ->execute($VisitorsID); if ($objVisitorsReferrerTop->numRows > 0) { while ($objVisitorsReferrerTop->next()) { if ($objVisitorsReferrerTop->visitors_referrer_dns !== '-') { $VisitorsReferrerTop[] = array($objVisitorsReferrerTop->visitors_referrer_dns, $objVisitorsReferrerTop->SUMRT, $VisitorsID); } else { $VisitorsReferrerTop[] = array('- ('.$GLOBALS['TL_LANG']['MSC']['tl_visitors_stat']['referrer_direct'].')', $objVisitorsReferrerTop->SUMRT, 0); } } } } return $VisitorsReferrerTop; }
TOP 30 Referrer @param integer $VisitorsID ID des Zählers @return array
entailment
protected function parseDateVisitors($language='en', $intTstamp=null, $prefix='') { switch ($language) { case 'de': $strModified = $prefix . 'd.m.Y'; break; case 'en': $strModified = $prefix . 'Y-m-d'; break; default : $strModified = $prefix . $GLOBALS['TL_CONFIG']['dateFormat']; break; } if (is_null($intTstamp)) { $strDate = date($strModified); } elseif (!is_numeric($intTstamp)) { return ''; } else { $strDate = \Date::parse($strModified, $intTstamp); } return $strDate; }
Timestamp nach Datum in deutscher oder internationaler Schreibweise @param string $language @param insteger $intTstamp @return string
entailment
protected function getVisitorsOnline($VisitorsID) { $objVisitorsOnlineCount = \Database::getInstance() ->prepare("SELECT COUNT(id) AS VOC FROM tl_visitors_blocker WHERE vid=? AND visitors_type=?") ->execute($VisitorsID,'v'); $objVisitorsOnlineCount->next(); return ($objVisitorsOnlineCount->VOC === null) ? 0 : $objVisitorsOnlineCount->VOC; }
Get VisitorsOnline @param integer $VisitorsID ID des Zählers @return integer
entailment
protected function getBestDay($VisitorsID) { $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($VisitorsID); if ($objVisitorsBestday->numRows > 0) { $objVisitorsBestday->next(); $visitors_date = $this->parseDateVisitors($GLOBALS['TL_LANGUAGE'],strtotime($objVisitorsBestday->visitors_date)); $visitors_visits = $this->getFormattedNumber($objVisitorsBestday->visitors_visit,0); $visitors_hits = $this->getFormattedNumber($objVisitorsBestday->visitors_hit,0); } else { $visitors_date = ''; $visitors_visits = 0; $visitors_hits = 0; } return array('VisitorsBestDayDate' => $visitors_date, 'VisitorsBestDayVisits' => $visitors_visits, 'VisitorsBestDayHits' => $visitors_hits ); }
Get Best Day Data (most Visitors on this day) @param integer $VisitorsID ID des Zählers @return array Date,Visits,Hits
entailment
protected function getBadDay($VisitorsID) { $objVisitorsBadday = \Database::getInstance() ->prepare("SELECT visitors_date, visitors_visit, visitors_hit FROM tl_visitors_counter WHERE vid=? AND visitors_date < ? ORDER BY visitors_visit ASC, visitors_hit ASC") ->limit(1) ->execute($VisitorsID, date('Y-m-d')); if ($objVisitorsBadday->numRows > 0) { $objVisitorsBadday->next(); $visitors_date = $this->parseDateVisitors($GLOBALS['TL_LANGUAGE'],strtotime($objVisitorsBadday->visitors_date)); $visitors_visits = $this->getFormattedNumber($objVisitorsBadday->visitors_visit,0); $visitors_hits = $this->getFormattedNumber($objVisitorsBadday->visitors_hit,0); } else { $visitors_date = ''; $visitors_visits = 0; $visitors_hits = 0; } return array('VisitorsBadDayDate' => $visitors_date, 'VisitorsBadDayVisits' => $visitors_visits, 'VisitorsBadDayHits' => $visitors_hits ); }
Get Bad Day Data (fewest Visitors on this day) @param integer $VisitorsID ID des Zählers @return array Date,Visits,Hits
entailment
protected function getVisitorCategoriesByUsergroups() { $arrVisitorCats = array(); $objVisitorCat = \Database::getInstance() ->prepare("SELECT `id` , `title` , `visitors_stat_protected` , `visitors_stat_groups` FROM tl_visitors_category WHERE 1 ORDER BY title ") ->execute(); while ($objVisitorCat->next()) { if ( true === $this->isUserInVisitorStatGroups($objVisitorCat->visitors_stat_groups, (bool) $objVisitorCat->visitors_stat_protected) ) { $arrVisitorCats[] = array ( 'id' => $objVisitorCat->id, 'title' => $objVisitorCat->title ); } } if (0 == count($arrVisitorCats)) { $arrVisitorCats[] = array('id' => '0', 'title' => '---------'); } return $arrVisitorCats; }
Get visitor categories by usergroups @param array $Usergroups @return array
entailment
protected function isUserInVisitorStatGroups($visitors_stat_groups, $visitors_stat_protected) { if ( true === $this->User->isAdmin ) { //Debug log_message('Ich bin Admin', 'visitors_debug.log'); return true; // Admin darf immer } //wenn Schutz nicht aktiviert ist, darf jeder if (false === $visitors_stat_protected) { //Debug log_message('Schutz nicht aktiviert', 'visitors_debug.log'); return true; } //Schutz aktiviert, Einschränkungen vorhanden? if (0 == strlen($visitors_stat_groups)) { //Debug log_message('visitor_stat_groups ist leer', 'visitors_debug.log'); return false; // nicht gefiltert, also darf keiner außer Admin } //mit isMemberOf ermitteln, ob user Member einer der Cat Groups ist foreach (deserialize($visitors_stat_groups) as $id => $groupid) { if ( true === $this->User->isMemberOf($groupid) ) { //Debug log_message('Ich bin in der richtigen Gruppe', 'visitors_debug.log'); return true; // User is Member of visitor_stat_group } } //Debug log_message('Ich bin in der falschen Gruppe', 'visitors_debug.log'); return false; }
Check if User member of group in visitor statistik groups @param string DB Field "visitors_stat_groups", serialized array @return bool true / false
entailment
public static function getIdentifier(string $name) : string { return str_replace( '.', '', uniqid( preg_match(static::VALID_IDENTIFIER_FORMAT, $name) ? $name : static::DEFAULT_IDENTIFIER, true ) ); }
Generates a valid unique identifier from the given name @param string $name @return string
entailment
public function parse(string $payload): ResultSpec { $data = @json_decode($payload, true); if (!is_array($data)) { throw new BaseClientException('Parse error', JsonRpcException::PARSE_ERROR); } $units = []; if ($this->isSingleResponse($data)) { $units[] = $this->decodeResult($data); return new ResultSpec($units, true); } /** @var array $data */ foreach ($data as $response) { $units[] = $this->decodeResult($response); } return new ResultSpec($units, false); }
@param string $payload @return ResultSpec
entailment
private function decodeResult(array $record): AbstractResult { $record = $this->preParse($record); if ($this->isValidResult($record)) { $unit = new Result($record['id'], $record['result']); } elseif ($this->isValidError($record)) { $exceptionClass = $this->exceptionMap[$record['error']['code']] ?? ServerErrorException::class; $unit = new Error($record['id'], new $exceptionClass( $record['error']['data']['message'] ?? $record['error']['message'] ?? 'Server error', $record['error']['data']['code'] ?? 0 )); } else { throw new InvalidResponseException(); } return $unit; }
@param array $record @return AbstractResult
entailment
private function isValidResult($payload): bool { if (!is_array($payload)) { return false; } $headerValid = array_key_exists('jsonrpc', $payload) && $payload['jsonrpc'] === '2.0'; $resultValid = array_key_exists('result', $payload); $idValid = array_key_exists('id', $payload); return $headerValid && $resultValid && $idValid; }
@param array $payload @return bool
entailment
private function isValidError($payload): bool { if (!is_array($payload)) { return false; } $headerValid = array_key_exists('jsonrpc', $payload) && $payload['jsonrpc'] === '2.0'; $errorValid = array_key_exists('error', $payload) && is_array($payload['error']) && array_key_exists('code', $payload['error']) && is_int($payload['error']['code']) && array_key_exists('message', $payload['error']) && is_string($payload['error']['message']); $idValid = array_key_exists('id', $payload); return $headerValid && $errorValid && $idValid; }
@param array $payload @return bool
entailment
private function preParse(array $data): array { $result = $this->preParse->handle(new ParserContainer($this, $data)); if ($result instanceof ParserContainer) { return $result->getValue(); } throw new \RuntimeException(); }
@param array $data @return array
entailment
public function decode(EntityInterface $entity) { $idField = $this->_primaryKey; $hashid = $entity->get($idField); if (!$hashid) { return false; } $field = $this->_config['field']; if (!$field) { return false; } $id = $this->decodeHashid($hashid); $entity->set($field, $id); $entity->setDirty($field, false); return true; }
Sets up hashid for model. @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved @return bool True if save should proceed, false otherwise
entailment
public function encode(EntityInterface $entity) { $idField = $this->_primaryKey; $id = $entity->get($idField); if (!$id) { return false; } $field = $this->_config['field']; if (!$field) { return false; } $hashid = $this->encodeId($id); $entity->set($field, $hashid); $entity->setDirty($field, false); return true; }
Sets up hashid for model. @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved @return bool True if save should proceed, false otherwise
entailment
public function findHashed(Query $query, array $options) { $field = $this->_config['field']; if (!$field) { return $query; } $idField = $this->_primaryKey; $query->formatResults(function ($results) use ($field, $idField) { $newResult = []; $results->each(function ($row, $key) use ($field, $idField, &$newResult) { if (!empty($row[$idField])) { $row[$field] = $this->encodeId($row[$idField]); if ($row instanceof EntityInterface) { $row->setDirty($field, false); } $newResult[] = $row; } elseif (is_string($row)) { $newResult[$this->encodeId($key)] = $row; } else { $newResult[] = $row; } }); return new Collection($newResult); }); if (!empty($options[static::HID])) { $id = $this->decodeHashid($options[static::HID]); $query->where([$idField => $id]); } $first = $this->_config['findFirst'] === true ? 'first' : $this->_config['findFirst']; if (!$first || !empty($options['noFirst'])) { return $query; } return $query->first(); }
Custom finder for hashids field. Options: - hid (required), best to use HashidBehavior::HID constant - noFirst (optional, to leave the query open for adjustments, no first() called) @param \Cake\ORM\Query $query Query. @param array $options Array of options as described above @return \Cake\ORM\Query|\Cake\Datasource\EntityInterface
entailment
public function spacy_entities( $text, $lang = 'en' ) { $data = $this->post_call('/spacy/entities', ['text' => $text, 'lang' => $lang ] ); return ( !empty($data['entities']) ) ? $data['entities'] : null; }
Spacy.io Entity Extraction
entailment
public function afinn_sentiment( $text, $lang = 'en' ) { $data = $this->post_call('/afinn', ['text' => $text, 'lang' => $lang ] ); return ( isset($data['afinn']) ) ? $data['afinn'] : null; }
AFINN Sentiment Analysis
entailment
public function summarize( $text, $word_count = null ) { $data = $this->post_call('/gensim/summarize', ['text' => $text, 'word_count' => $word_count ] ); return ( !empty($data['summarize']) ) ? $data['summarize'] : null; }
Summarize long text
entailment
public function newspaper_html( $html ) { $data = $this->post_call('/newspaper', ['html' => $html ] ); return ( !empty($data['newspaper']) ) ? $data['newspaper'] : null; }
Article Extraction from HTML
entailment
public function newspaper( $url ) { $data = $this->get_call('/newspaper', ['url' => $url ] ); return ( !empty($data['newspaper']) ) ? $data['newspaper'] : null; }
Article Extraction from URL
entailment
public function readability( $url ) { $data = $this->get_call('/readability', ['url' => $url ] ); return ( !empty($data['readability']) ) ? $data['readability'] : null; }
Readability Article Extraction from URL
entailment
public function readability_html( $html ) { $data = $this->post_call('/readability', ['html' => $html ] ); return ( !empty($data['readability']) ) ? $data['readability'] : null; }
Readability Article Extraction from HTML
entailment
public function sentiment( $text, $language = null ) { $data = $this->post_call('/polyglot/sentiment', ['text' => $text, 'lang' => $language ] ); return ( isset($data['sentiment']) ) ? $data['sentiment'] : null; }
Sentiment Analysis by Polyglot
entailment
public function neighbours( $word, $lang = 'en') { $data = $this->get_call('/polyglot/neighbours', ['word' => $word, 'lang' => $lang ] ); return ( !empty($data['neighbours']) ) ? $data['neighbours'] : null; }
Get neighbouring words
entailment
public function polyglot_entities( $text, $language = null ) { $data = $this->post_call('/polyglot/entities', ['text' => $text, 'lang' => $language] ); $this->msg( $data ); return new \Web64\Nlp\Classes\PolyglotResponse( $data['polyglot'] ); }
Get entities and sentiment analysis of text
entailment
public function language( $text ) { $data = $this->post_call('/langid', ['text' => $text] ); if ( isset($data['langid']) && isset($data['langid']['language'])) { // return 'no' for Norwegian Bokmaal and Nynorsk if ( $data['langid']['language'] == 'nn' || $data['langid']['language'] == 'nb' ) return 'no'; return $data['langid']['language']; } return null; }
Get language code for text
entailment
public function addHost( $host ) { $host = rtrim( $host , '/'); if ( array_search($host, $this->api_hosts) === false) $this->api_hosts[] = $host; }
Internals
entailment
private function msg( $value ) { if ( $this->debug ) { if ( is_array($value) ) { fwrite(STDOUT, print_r( $value, true ) . PHP_EOL ); } else fwrite(STDOUT, $value . PHP_EOL ); } }
debug message
entailment
private function chooseHost() { $random_a = $this->api_hosts; shuffle($random_a); // pick random host foreach( $random_a as $api_url ) { $this->msg( "chooseHost() - Testing: $api_url "); $content = @file_get_contents( $api_url ); if ( empty( $content ) ) { $this->msg( $content ); // Failed $this->msg( "- Ignoring failed API URL: $api_url " ); //print_r( $http_response_header ); }else{ $this->api_url = $api_url; $this->msg( "- Working API URL: $api_url" ); return true; } $this->msg( $content ); } return false; }
find working host
entailment
public function generatePageVisitHitTop($VisitorsID, $limit = 20, $parse = true) { $arrPageStatCount = false; $objPageStatCount = \Database::getInstance() ->prepare("SELECT visitors_page_id, visitors_page_lang, visitors_page_type, 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 IN (?,?) GROUP BY visitors_page_id, visitors_page_lang, visitors_page_type ORDER BY visitors_page_visits DESC, visitors_page_hits DESC, visitors_page_id, visitors_page_lang ") ->limit($limit) ->execute($VisitorsID, self::PAGE_TYPE_NORMAL, self::PAGE_TYPE_FORBIDDEN); while ($objPageStatCount->next()) { switch ($objPageStatCount->visitors_page_type) { case self::PAGE_TYPE_NORMAL : $objPage = \PageModel::findWithDetails($objPageStatCount->visitors_page_id); $alias = $objPage->alias; break; case self::PAGE_TYPE_FORBIDDEN : $alias = false; $objPage = \PageModel::findWithDetails($objPageStatCount->visitors_page_id); $alias403 = $this->getForbiddenAlias($objPageStatCount->visitors_page_id, $objPageStatCount->visitors_page_lang); $alias = $alias403 .' ['.$objPage->alias.']'; break; default: $alias = '-/-'; break; } if (false !== $alias) { $arrPageStatCount[] = array ( 'alias' => $alias, 'lang' => $objPageStatCount->visitors_page_lang, 'visits' => $objPageStatCount->visitors_page_visits, 'hits' => $objPageStatCount->visitors_page_hits ); } } if ($parse === true) { $this->TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_pagevisithittop'); $this->TemplatePartial->PageVisitHitTop = $arrPageStatCount; return $this->TemplatePartial->parse(); } else { return $arrPageStatCount; } }
////////////////////////////////////////////////////////////
entailment
public function generatePageVisitHitTopDays($VisitorsID, $days = 365, $parse = false) { $STARTDATE = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-$days, date("Y")) ); $arrPageStatCount = false; $objPageStatCount = \Database::getInstance() ->prepare("SELECT visitors_page_id, visitors_page_pid, visitors_page_lang, visitors_page_type, 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_date >= ? GROUP BY visitors_page_id, visitors_page_pid, visitors_page_lang, visitors_page_type ORDER BY visitors_page_visits DESC, visitors_page_hits DESC, visitors_page_id, visitors_page_pid, visitors_page_lang ") ->execute($VisitorsID, $STARTDATE); while ($objPageStatCount->next()) { switch ($objPageStatCount->visitors_page_type) { case self::PAGE_TYPE_NORMAL : $objPage = \PageModel::findWithDetails($objPageStatCount->visitors_page_id); $alias = $objPage->alias; break; case self::PAGE_TYPE_NEWS : $alias = false; $aliases = $this->getNewsAliases($objPageStatCount->visitors_page_id); if (false !== $aliases['PageAlias']) { $alias = $aliases['PageAlias'] .'/'. $aliases['NewsAlias']; } break; case self::PAGE_TYPE_FAQ : $alias = false; $aliases = $this->getFaqAliases($objPageStatCount->visitors_page_id); if (false !== $aliases['PageAlias']) { $alias = $aliases['PageAlias'] .'/'. $aliases['FaqAlias']; } break; case self::PAGE_TYPE_ISOTOPE: $alias = false; $aliases = $this->getIsotopeAliases($objPageStatCount->visitors_page_id, $objPageStatCount->visitors_page_pid); if (false !== $aliases['PageAlias']) { $alias = $aliases['PageAlias'] .'/'. $aliases['ProductAlias']; } break; case self::PAGE_TYPE_FORBIDDEN : $alias = false; $objPage = \PageModel::findWithDetails($objPageStatCount->visitors_page_id); $alias403 = $this->getForbiddenAlias($objPageStatCount->visitors_page_id, $objPageStatCount->visitors_page_lang); $alias = $alias403 .' ['.$objPage->alias.']'; break; default: $alias = '-/-'; break; } if (false !== $alias) { $arrPageStatCount[] = array ( 'alias' => $alias, 'lang' => $objPageStatCount->visitors_page_lang, 'visits' => $objPageStatCount->visitors_page_visits, 'hits' => $objPageStatCount->visitors_page_hits ); } } if ($parse === true) { $this->TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_pagevisithittop'); $this->TemplatePartial->PageVisitHitTop = $arrPageStatCount; return $this->TemplatePartial->parse(); } else { return $arrPageStatCount; } }
generatePageVisitHitTopDays speziell für den Export Filterung nach Anzahl Tagen @param integer $VisitorsID @param number $days @param string $parse @return string|multitype:string NULL
entailment
public function updateCMSFields(FieldList $fields) { // Remove all Meta fields $fields->removeByName('Metadata'); // Add summary fields $fields->addFieldToTab('Root.Main', TextAreaField::create('MetaDescription', _t('JonoM\ShareCare\ShareCareSummary.SummaryTitle','Content summary')) ->setDescription(_t('JonoM\ShareCare\ShareCareSummary.SummaryDescription','Summarise the content of this page. This will be used for search engine results and social media so make it enticing.')) ->setAttribute('placeholder', $this->owner->getDefaultOGDescription()) ->setRows(2), 'Content'); $imgFieldDescription = _t('JonoM\ShareCare\ShareCareSummary.ImageDescription','Choose an image to represent this page in listings and on social media.'); if (!$this->owner->MetaImageID && $this->owner->isPublished()) { $imgFieldDescription .= " <i style=\"color:#ec720f\">" . _t('JonoM\ShareCare\ShareCareSummary.ImageDescriptionNotEmpty','For best results, please don\'t leave this empty.') . "</i>"; } $fields->addFieldToTab('Root.Main', UploadField::create('MetaImage', _t('JonoM\ShareCare\ShareCareSummary.ImageTitle','Summary image')) ->setAllowedFileCategories('image') ->setAllowedMaxFileNumber(1) ->setDescription($imgFieldDescription), 'Content'); }
Add and re-arrange CMS fields for streamlined summary editing.
entailment
public function getOGDescription() { // Use MetaDescription if set if ($this->owner->MetaDescription) { $description = trim($this->owner->MetaDescription); if (!empty($description)) { return $description; } } return $this->owner->getDefaultOGDescription(); }
The description that will be used in the 'og:description' open graph tag. Use a custom value if set, or fallback to a default value. @return string
entailment
public function getDefaultOGDescription() { // Fall back to Content if ($this->owner->Content) { $description = trim($this->owner->obj('Content')->Summary(20, 5)); if (!empty($description)) { return $description; } } return false; }
The default/fallback value to be used in the 'og:description' open graph tag. @return string
entailment
public function leaveNode(Node $node) { $filter = $this->filter; if (! $node instanceof ClassMethod || null === ($filterResult = $filter($node))) { return null; } if (false === $filterResult) { return false; } $node->stmts = array( new Throw_( new New_( new FullyQualified('BadMethodCallException'), array(new Arg(new String_('Method is disabled'))) ) ) ); return $node; }
Replaces the given node if it is a class method and matches according to the given callback @param \PhpParser\Node $node @return bool|null|\PhpParser\Node\Stmt\ClassMethod
entailment
public function checkBot() { $bundles = array_keys(\System::getContainer()->getParameter('kernel.bundles')); // old \ModuleLoader::getActive() if ( !in_array( 'BugBusterBotdetectionBundle', $bundles ) ) { //BugBusterBotdetectionBundle Modul fehlt, Abbruch \System::getContainer() ->get('monolog.logger.contao') ->log(LogLevel::ERROR, 'contao-botdetection-bundle extension required for extension: Visitors!', array('contao' => new ContaoContext('ModuleVisitorChecks checkBot ', TL_ERROR))); ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , print_r($bundles, true) ); return false; } $ModuleBotDetection = new ModuleBotDetection(); if ($ModuleBotDetection->checkBotAllTests()) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; }
Spider Bot Check @return bool
entailment
public function checkUserAgent($visitors_category_id) { if (\Environment::get('httpUserAgent')) { $UserAgent = trim(\Environment::get('httpUserAgent')); } else { return false; // Ohne Absender keine Suche } $arrUserAgents = array(); $objUserAgents = \Database::getInstance() ->prepare("SELECT `visitors_useragent` FROM `tl_module` WHERE `type` = ? AND `visitors_categories` = ?") ->execute('visitors',$visitors_category_id); if ($objUserAgents->numRows) { while ($objUserAgents->next()) { $arrUserAgents = array_merge($arrUserAgents,explode(",", $objUserAgents->visitors_useragent)); } } if (strlen(trim($arrUserAgents[0])) == 0) { return false; // keine Angaben im Modul } // Suche $CheckUserAgent=str_replace($arrUserAgents, '#', $UserAgent); if ($UserAgent != $CheckUserAgent) { // es wurde ersetzt also was gefunden ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; }
HTTP_USER_AGENT Special Check @return bool
entailment
public function checkBE() { if ($this->isContao45()) { if ($this->_BackendUser) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; } //Contao <4.5.0 $strCookie = 'BE_USER_AUTH'; $hash = sha1(session_id() . (!\Config::get('privacyAnonymizeIp') ? \Environment::get('ip') : '') . $strCookie); if (\Input::cookie($strCookie) == $hash) { // Try to find the session $objSession = \SessionModel::findByHashAndName($hash, $strCookie); // Validate the session ID and timeout if ($objSession !== null && $objSession->sessionID == session_id() && (\Config::get('privacyAnonymizeIp') || $objSession->ip == \Environment::get('ip')) && ($objSession->tstamp + $GLOBALS['TL_CONFIG']['sessionTimeout']) > time()) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; }
BE Login Check basiert auf Frontend.getLoginStatus @return bool
entailment
public function isDomain($host) { $dnsResult = false; //$this->_vhost : Host.TLD //idn_to_ascii $dnsResult = @dns_get_record( \Idna::encode( $host ), DNS_ANY ); if ( $dnsResult ) { ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': True' ); return true; } ModuleVisitorLog::writeLog( __METHOD__ , __LINE__ , ': False' ); return false; }
Check if Domain valid @param string Host / domain.tld @return boolean
entailment
public function isContao45() { //Thanks fritzmg for this hint // get the Contao version $version = PrettyVersions::getVersion('contao/core-bundle'); // check for Contao >=4.5 if (\Composer\Semver\Semver::satisfies($version->getShortVersion(), '>=4.5')) { 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 visitorGetUserIP() { $UserIP = \Environment::get('ip'); if (strpos($UserIP, ',') !== false) //first IP { $UserIP = trim( substr($UserIP, 0, strpos($UserIP, ',') ) ); } if ( true === $this->visitorIsPrivateIP($UserIP) && false === empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) { //second try $HTTPXFF = $_SERVER['HTTP_X_FORWARDED_FOR']; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $UserIP = \Environment::get('ip'); if (strpos($UserIP, ',') !== false) //first IP { $UserIP = trim( substr($UserIP, 0, strpos($UserIP, ',') ) ); } $_SERVER['HTTP_X_FORWARDED_FOR'] = $HTTPXFF; } return $UserIP; }
Get User IP @return string
entailment
public function log($level, $message, array $context = array()) { fwrite($this->stream, $this->formatMessage($this->interpolate($message, $context))); }
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context @return null
entailment
public function updateCMSFields(FieldList $fields) { $msg = _t('JonoM\ShareCare\ShareCare.CMSMessage', 'When this page is shared by people on social media it will look something like this:'); $tab = 'Root.' . _t('JonoM\ShareCare\ShareCare.TabName', 'Share'); if ($msg) { $fields->addFieldToTab($tab, new LiteralField('ShareCareMessage', '<div class="message notice"><p>' . $msg . '</p></div>')); } $fields->addFieldToTab($tab, new LiteralField('ShareCarePreview', $this->owner->RenderWith('ShareCarePreview', array( 'IncludeTwitter' => self::config()->get('twitter_card'), 'IncludePinterest' => self::config()->get('pinterest') )))); }
Add a Social Media tab with a preview of share appearance to the CMS.
entailment
public function clearFacebookCache() { if ($this->owner->hasMethod('AbsoluteLink')) { $anonymousUser = new Member(); if ($this->owner->can('View', $anonymousUser)) { $client = new Client(); try { $client->request('GET', 'https://graph.facebook.com/', [ 'query' => [ 'id' => $this->owner->AbsoluteLink(), 'scrape' => true, ] ]); } catch (\Exception $e) { user_error($e->getMessage(), E_USER_WARNING); } } } }
Tell Facebook to re-scrape this URL, if it is accessible to the public.
entailment