Repository: shetabit/visitor Branch: master Commit: 274d4afa2f3b Files: 35 Total size: 52.2 KB Directory structure: gitextract_1jbvs2nu/ ├── .gitattributes ├── .gitignore ├── CHANGELOG.md ├── CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── LICENSE.md ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── composer.json ├── config/ │ └── visitor.php ├── database/ │ └── migrations/ │ ├── add_geo_raw_to_visits_table.php.stub │ └── create_visits_table.php.stub ├── phpunit.xml ├── src/ │ ├── Agent.php │ ├── Contracts/ │ │ ├── GeoIpResolver.php │ │ └── UserAgentParser.php │ ├── Drivers/ │ │ ├── JenssegersAgent.php │ │ └── UAParser.php │ ├── Exceptions/ │ │ ├── DriverNotFoundException.php │ │ └── ResolverNotFoundException.php │ ├── Facade/ │ │ ├── Agent.php │ │ └── Visitor.php │ ├── Middlewares/ │ │ └── LogVisits.php │ ├── Models/ │ │ └── Visit.php │ ├── Provider/ │ │ ├── AgentServiceProvider.php │ │ └── VisitorServiceProvider.php │ ├── Resolvers/ │ │ └── GeoIp/ │ │ ├── NullResolver.php │ │ └── SteveBaumanResolver.php │ ├── Traits/ │ │ ├── CanVisit.php │ │ ├── Visitable.php │ │ └── Visitor.php │ ├── Visitor.php │ └── helpers.php └── tests/ └── TestCase.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ /.gitattributes export-ignore /phpunit.xml export-ignore /tests export-ignore /ISSUE_TEMPLATE.md export-ignore /PULL_REQUEST_TEMPLATE.md export-ignore ================================================ FILE: .gitignore ================================================ .idea vendor/ /composer.lock ================================================ FILE: CHANGELOG.md ================================================ # Changelog All Notable changes to `visitor` will be documented in this file. Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles. ## Date - 2019-01-09 ### Fixed - Nothing ### Added - Nothing ### Deprecated - Nothing ### Fixed - Nothing ### Removed - Nothing ### Security - Nothing ================================================ FILE: CONDUCT.md ================================================ # Contributor Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at `khanzadimahdi@gmail.com`. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/shetabit/visitor). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``. - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. **Happy coding**! ================================================ FILE: ISSUE_TEMPLATE.md ================================================ ## Detailed description Provide a detailed description of the change or addition you are proposing. Make it clear if the issue is a bug, an enhancement or just a question. ## Context Why is this change important to you? How would you use it? How can it benefit other users? ## Possible implementation Not obligatory, but suggest an idea for implementing addition or change. ## Your environment Include as many relevant details about the environment you experienced the bug in and how to reproduce it. * Version used (e.g. PHP 7.2, HHVM 3): * Operating system and version (e.g. Ubuntu 19.04, Windows 10): * Link to your project: * ... * ... ================================================ FILE: LICENSE.md ================================================ # The MIT License (MIT) Copyright (c) 2019 Mahdi Khanzadi > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal > in the Software without restriction, including without limitation the rights > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell > copies of the Software, and to permit persons to whom the Software is > furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in > all copies or substantial portions of the Software. > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN > THE SOFTWARE. ================================================ FILE: PULL_REQUEST_TEMPLATE.md ================================================ ## Description Describe your changes in detail. ## Motivation and context Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here (if you write `fixes #num` or `closes #num`, the issue will be automatically closed when the pull is accepted.) ## How has this been tested? Please describe in detail how you tested your changes. Include details of your testing environment, and the tests you ran to see how your change affects other areas of the code, etc. ## Screenshots (if appropriate) ## Types of changes What types of changes does your code introduce? Put an `x` in all the boxes that apply: - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) ## Checklist: Go over all the following points, and put an `x` in all the boxes that apply. Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our [continuous integration](http://www.phptherightway.com/#continuous-integration) server to make sure your [tests and code style pass](https://help.github.com/articles/about-required-status-checks/). - [ ] I have read the **[CONTRIBUTING](CONTRIBUTING.md)** document. - [ ] My pull request addresses exactly one patch/feature. - [ ] I have created a branch for this patch/feature. - [ ] Each individual commit in the pull request is meaningful. - [ ] I have added tests to cover my changes. - [ ] If my change requires a change to the documentation, I have updated it accordingly. If you're unsure about any of these, don't hesitate to ask. We're here to help! ================================================ FILE: README.md ================================================

# Laravel Visitor This is a laravel package to extract and access visitors' information such as `browser`, `ip`, `device` and etc. **In this package, you can recognize online users and determine if a user is online or not** ### Install Via composer ```bash composer require shetabit/visitor ``` ### Configure If you are using Laravel 5.5 or higher then you don't need to add the provider and alias. ```php # In your providers array. 'providers' => [ ... Shetabit\Visitor\Provider\VisitorServiceProvider::class, ], # In your aliases array. 'aliases' => [ ... 'Visitor' => Shetabit\Visitor\Facade\Visitor::class, ], ``` Then, run the below commands to publish migrations and create tables ```bash php artisan vendor:publish php artisan migrate ``` ### How to use You can access to `visitor's information` using `$request->visitor()` in your controllers , and you can access to the visitor's information using `visitor()` helper function any where. We have the below methods to retrieve a visitor's information: - `device` : device's name - `platform` : platform's name - `browser` : browser's name - `languages` : language's name - `ip` : client's ip - `request` : the whole request inputs - `useragent` : the whole useragent - `isOnline` : determines if current (or given) user is online ```php $request->visitor()->browser(); // firefox $request->visitor()->visit($post); // create log for post $request->visitor()->setVisitor($user)->visit($post); // create a log which says $user has visited $post ``` #### Store Logs You can create logs using the `visit` method like the below ```php visitor()->visit(); // create a visit log ``` use `Shetabit\Visitor\Traits\Visitable` trait in your models, then you can save visit's log for your models like the below ```php // or you can save log like the below visitor()->visit($model); // or like the below $model->createVisitLog(); // you can say which user has visited the given $model $model->createVisitLog($user); // or like the below visitor()->setVisitor($user)->visit($model); ``` Model views can be loaded using `visits` relation. You can count model visits like the below ```php $model->visitLogs()->count(); ``` unique users can be counted by their IP and by model. ```php // by ip $model->visitLogs()->distinct('ip')->count('ip'); // by user's model $model->visitLogs()->visitor()->count(); ``` use `Shetabit\Visitor\Traits\Visitor` in your `User` class, then you can run below codes ```php $user->visit(); // create a visit log $user->visit($model); // create a log which says, $user has visited $model ``` #### Retrieve and Determine Online users use `Shetabit\Visitor\Traits\Visitor` in your `User` class at first. Then you can retrieve online users which are instance of `User` class and determine if a user is online. ```php visitor()->onlineVisitors(User::class); // returns collection of online users User::online()->get(); // another way visitor()->isOnline($user); // determines if the given user is online $user->isOnline(); // another way ``` #### Automatic logging Your application can store visitor's log automatically using `LogVisits` middleware. Add the `Shetabit\Visitor\Middlewares\LogVisits` middleware if you want to save logs automatically. The middleware will store logs for models which has binded in router (router model binding) and has used `Shetabit\Visitor\Traits\Visitable` trait. ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=shetabit/visitor&type=Date)](https://star-history.com/#shetabit/visitor&Date) ================================================ FILE: composer.json ================================================ { "name": "shetabit/visitor", "type": "library", "description": "Laravel visitor", "keywords": [ "shetabit", "visitor", "track laravel visitors", "trace laravel visitors", "parse laravel user agents" ], "homepage": "https://github.com/shetabit/visitor", "license": "MIT", "authors": [ { "name": "Mahdi Khanzadi", "email": "khanzadimahdi@gmail.com", "homepage": "https://github.com/khanzadimahdi", "role": "Developer" } ], "require": { "php": ">=8.0", "illuminate/support": "9.*|10.*|11.*|12.*|^13.0", "ua-parser/uap-php": "^3.9", "mobiledetect/mobiledetectlib": "^4.8", "jaybizzle/crawler-detect": "^1.2" }, "require-dev": { "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", "phpunit/phpunit": ">=7.5", "squizlabs/php_codesniffer": "^3.4|^4.0" }, "autoload": { "psr-4": { "Shetabit\\Visitor\\": "src" }, "files": [ "src/helpers.php" ] }, "autoload-dev": { "psr-4": { "Shetabit\\Visitor\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "check-style": "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests", "fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests" }, "extra": { "laravel": { "providers": [ "Shetabit\\Visitor\\Provider\\VisitorServiceProvider" ], "aliases": { "Visitor": "Shetabit\\Visitor\\Facade\\Visitor" } } }, "config": { "sort-packages": true } } ================================================ FILE: config/visitor.php ================================================ 'jenssegers', //except save request or route names 'except' => ['login', 'register'], //name of the table which visit records should save in 'table_name' => 'shetabit_visits', /* |-------------------------------------------------------------------------- | List of Drivers |-------------------------------------------------------------------------- | | This is the array of Classes that maps to Drivers above. | You can create your own driver if you like and add the | config in the drivers array and the class to use for | here with the same name. You will have to implement | Shetabit\Visitor\Contracts\UserAgentParser in your driver. | */ 'drivers' => [ 'jenssegers' => \Shetabit\Visitor\Drivers\JenssegersAgent::class, 'UAParser' => \Shetabit\Visitor\Drivers\UAParser::class, ], /* |-------------------------------------------------------------------------- | GeoIP Enrichment |-------------------------------------------------------------------------- | | When enabled, visits can be enriched with geolocation data stored | in the "geo_raw" JSON column. This package ships with a default | resolver (stevebauman/location). You may implement your own by | adding it to the drivers array below. Each driver must implement | Shetabit\Visitor\Contracts\GeoIpResolver. | */ 'geoip' => false, // disable enrichment by default 'resolver'=> 'stevebauman', // default resolver 'resolvers' => [ 'stevebauman' => \Shetabit\Visitor\Resolvers\GeoIp\SteveBaumanResolver::class, 'null' => \Shetabit\Visitor\Resolvers\GeoIp\NullResolver::class, ], ]; ================================================ FILE: database/migrations/add_geo_raw_to_visits_table.php.stub ================================================ json('geo_raw')->nullable()->after('ip'); }); } public function down() { Schema::table(config('visitor.table_name'), function (Blueprint $table) { $table->dropColumn('geo_raw'); }); } } ================================================ FILE: database/migrations/create_visits_table.php.stub ================================================ bigIncrements('id'); $table->string('method')->nullable(); $table->mediumText('request')->nullable(); $table->mediumText('url')->nullable(); $table->mediumText('referer')->nullable(); $table->text('languages')->nullable(); $table->text('useragent')->nullable(); $table->text('headers')->nullable(); $table->text('device')->nullable(); $table->text('platform')->nullable(); $table->text('browser')->nullable(); $table->ipAddress('ip')->nullable(); $table->json('geo_raw')->nullable()->comment('Optional GeoIP payload (country_code, region, city, lat/lng, …)'); $table->nullableMorphs('visitable'); // object model $table->nullableMorphs('visitor'); // subject model $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('visitor.table_name')); } } ================================================ FILE: phpunit.xml ================================================ ./src/ ./tests/ ================================================ FILE: src/Agent.php ================================================ */ protected static array $desktopDevices = [ 'Macintosh' => 'Macintosh', ]; /** * List of additional operating systems. * * @var array */ protected static array $additionalOperatingSystems = [ 'Windows' => 'Windows', 'Windows NT' => 'Windows NT', 'OS X' => 'Mac OS X', 'Debian' => 'Debian', 'Ubuntu' => 'Ubuntu', 'Macintosh' => 'PPC', 'OpenBSD' => 'OpenBSD', 'Linux' => 'Linux', 'ChromeOS' => 'CrOS', ]; /** * List of additional browsers. * * @var array */ protected static array $additionalBrowsers = [ 'Opera Mini' => 'Opera Mini', 'Opera' => 'Opera|OPR', 'Edge' => 'Edge|Edg', 'Coc Coc' => 'coc_coc_browser', 'UCBrowser' => 'UCBrowser', 'Vivaldi' => 'Vivaldi', 'Chrome' => 'Chrome', 'Firefox' => 'Firefox', 'Safari' => 'Safari', 'IE' => 'MSIE|IEMobile|MSIEMobile|Trident/[.0-9]+', 'Netscape' => 'Netscape', 'Mozilla' => 'Mozilla', 'WeChat' => 'MicroMessenger', ]; protected static CrawlerDetect $crawlerDetect; /** * Key value store for resolved strings. * * @var array */ protected array $store = []; public function getRules(): array { static $rules; if (!$rules) { $rules = array_merge( static::$browsers, static::$operatingSystems, static::$phoneDevices, static::$tabletDevices, static::$desktopDevices, // NEW static::$additionalOperatingSystems, // NEW static::$additionalBrowsers // NEW ); } return $rules; } /** * Get accept languages. * @param string|null $acceptLanguage * @return array */ public function languages(string $acceptLanguage = null): array { if ($acceptLanguage === null) { $acceptLanguage = $this->getHttpHeader('HTTP_ACCEPT_LANGUAGE'); } if (!$acceptLanguage) { return []; } $languages = []; // Parse accept language string. foreach (explode(',', $acceptLanguage) as $piece) { $parts = explode(';', $piece); $language = strtolower($parts[0]); $priority = empty($parts[1]) ? 1. : (float)str_replace('q=', '', $parts[1]); $languages[$language] = $priority; } // Sort languages by priority. arsort($languages); return array_keys($languages); } /** * Get the browser name. * @return string|bool */ public function browser(): bool|string { return $this->retrieveUsingCacheOrResolve('visitor.browser', function () { return $this->findDetectionRulesAgainstUserAgent( $this->mergeRules(static::$additionalBrowsers, MobileDetect::getBrowsers()) ); }); } /** * Retrieve from the given key from the cache or resolve the value. * * @param string $key * @param \Closure():mixed $callback * @return mixed */ protected function retrieveUsingCacheOrResolve(string $key, Closure $callback): mixed { $cacheKey = $this->createCacheKey($key); if (!is_null($cacheItem = $this->store[$cacheKey] ?? null)) { return $cacheItem; } return tap($callback(), function ($result) use ($cacheKey) { $this->store[$cacheKey] = $result; }); } /** * @throws RandomException */ protected function createCacheKey(string $key): string { $userAgentKey = $this->hasUserAgent() ? $this->userAgent : ''; $randomBytes = random_bytes(16); $randomHash = bin2hex($randomBytes); return base64_encode("$key:$userAgentKey:$randomHash"); } /** * Match a detection rule and return the matched key. * * @param array $rules * @return string|null */ protected function findDetectionRulesAgainstUserAgent(array $rules): ?string { $userAgent = $this->getUserAgent(); foreach ($rules as $key => $regex) { if (empty($regex)) { continue; } // regex is an array of "strings" if (is_array($regex)) { foreach ($regex as $regexString) { if ($this->match($regexString, $userAgent)) { return $key ?: reset($this->matchesArray); } } } else if ($this->match($regex, $userAgent)) { return $key ?: reset($this->matchesArray); } } return false; } /** * Merge multiple rules into one array. * * @param array $all * @return array */ protected function mergeRules(...$all): array { $merged = []; foreach ($all as $rules) { foreach ($rules as $key => $value) { if (empty($merged[$key])) { $merged[$key] = $value; } elseif (is_array($merged[$key])) { $merged[$key][] = $value; } else { $merged[$key] .= '|' . $value; } } } return $merged; } /** * Get the platform name. * * @return string|bool */ public function platform(): bool|string { return $this->retrieveUsingCacheOrResolve('visitor.platform', function () { return $this->findDetectionRulesAgainstUserAgent( $this->mergeRules(static::$additionalOperatingSystems, MobileDetect::getOperatingSystems()) ); }); } /** * Get the device name. * @return string|bool */ public function device(): bool|string { return $this->findDetectionRulesAgainstUserAgent( $this->mergeRules( static::getDesktopDevices(), static::getPhoneDevices(), static::getTabletDevices() ) ); } /** * Retrieve the list of known Desktop devices. * * @return array List of Desktop devices. */ public static function getDesktopDevices(): array { return static::$desktopDevices; } /** * Get the robot name. * @return string|bool */ public function robot(): bool|string { $userAgent = $this->getUserAgent(); if ($this->getCrawlerDetect()->isCrawler($userAgent ?: $this->userAgent)) { return ucfirst($this->getCrawlerDetect()->getMatches()); } return false; } /** * @return CrawlerDetect */ public function getCrawlerDetect(): CrawlerDetect { if (static::$crawlerDetect === null) { static::$crawlerDetect = new CrawlerDetect(); } return static::$crawlerDetect; } /** * Get the device type * @return string * @throws MobileDetectException */ public function deviceType(): string { if ($this->isDesktop()) { return "desktop"; } if ($this->isPhone()) { return "phone"; } if ($this->isTablet()) { return "tablet"; } if ($this->isRobot()) { return "robot"; } return "other"; } /** * Check if the device is a desktop computer. * @return bool * @throws MobileDetectException */ public function isDesktop(): bool { $userAgent = $this->getUserAgent(); return $this->retrieveUsingCacheOrResolve('visitor.desktop', function () use ($userAgent) { // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' if ($userAgent === static::$cloudFrontUA && $this->getHttpHeader('HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER') === 'true') { return true; } return !$this->isMobile() && !$this->isTablet() && !$this->isRobot($userAgent); }); } /** * Check if device is a robot. * @return bool */ public function isRobot(): bool { $userAgent = $this->getUserAgent(); return $this->getCrawlerDetect()->isCrawler($userAgent ?: $this->userAgent); } /** * Check if the device is a mobile phone. * @return bool * @throws MobileDetectException */ public function isPhone(): bool { return $this->isMobile() && !$this->isTablet(); } /** * @inheritdoc */ public function __call($name, $arguments) { // Make sure the name starts with 'is', otherwise if (!str_starts_with($name, 'is')) { throw new BadMethodCallException("No such method exists: $name"); } $key = substr($name, 2); return $this->matchUserAgentWithRule($key); } } ================================================ FILE: src/Contracts/GeoIpResolver.php ================================================ '192.168.1.1', * 'country_code' => 'FR', * 'country_name' => 'France', * 'region_name' => 'Île-de-France', * 'city_name' => 'Paris', * 'latitude' => 48.8566, * 'longitude' => 2.3522, * ] */ public function resolve(string $ip): ?array; } ================================================ FILE: src/Contracts/UserAgentParser.php ================================================ request = $request; $this->parser = $this->initParser(); } /** * Retrieve device's name. */ public function device() : string { return $this->parser->device(); } /** * Retrieve platform's name. */ public function platform() : string { return $this->parser->platform(); } /** * Retrieve browser's name. */ public function browser() : string { return $this->parser->browser(); } /** * Retrieve languages. */ public function languages() : array { return $this->parser->languages(); } /** * Initialize userAgent parser. */ protected function initParser(): Agent { $parser = new Agent(); $userAgent = $this->request->userAgent() ?? ''; $parser->setUserAgent($userAgent); $parser->setHttpHeaders((array)$this->request->headers); return $parser; } } ================================================ FILE: src/Drivers/UAParser.php ================================================ request = $request; $this->parser = $this->initParser(); } /** * Retrieve device's name. */ public function device() : string { return $this->parser->device->family; } /** * Retrieve platform's name. */ public function platform() : string { return $this->parser->os->family; } /** * Retrieve browser's name. */ public function browser() : string { return $this->parser->ua->family; } /** * Retrieve languages. */ public function languages() : array { $languages = []; if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); $languages[] = $lang; } return $languages; } /** * Initialize userAgent parser. * * @throws \UAParser\Exception\FileNotFoundException */ protected function initParser(): \UAParser\Result\Client { return Parser::create()->parse($this->request->userAgent()); } } ================================================ FILE: src/Exceptions/DriverNotFoundException.php ================================================ route()->parameters() as $parameter) { if ($parameter instanceof Model) { visitor()->visit($parameter); $logHasSaved = true; break; } } // create log for normal visits if (!$logHasSaved) { visitor()->visit(); } return $next($request); } } ================================================ FILE: src/Models/Visit.php ================================================ table)) { $this->setTable(config('visitor.table_name')); } parent::__construct($attributes); } /** * The attributes that aren't mass assignable. * * @var array */ protected $fillable = [ 'method', 'request', 'url', 'referer', 'languages', 'useragent', 'headers', 'device', 'platform', 'browser', 'ip', 'visitor_id', 'visitor_type', 'geo_raw', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'request' => 'array', 'languages' => 'array', 'headers' => 'array', 'geo_raw' => 'array', ]; /** * Get the owning visitable model. * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function visitable() { return $this->morphTo('visitable'); } /** * Get the owning user model. * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function visitor() { return $this->morphTo('visitor'); } } ================================================ FILE: src/Provider/AgentServiceProvider.php ================================================ app->singleton('agent', function ($app) { return new Agent($app['request']->server()); }); $this->app->alias('agent', Agent::class); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['agent', Agent::class]; } } ================================================ FILE: src/Provider/VisitorServiceProvider.php ================================================ publishes( [ __DIR__.'/../../config/visitor.php' => config_path('visitor.php'), ], 'config' ); $timestamp = date('Y_m_d_His', time()); if (! class_exists('CreateVisitsTable')) { $this->publishes([ __DIR__ . '/../../database/migrations/create_visits_table.php.stub' => database_path("/migrations/{$timestamp}_create_visits_table.php"), ], 'migrations'); } if (! class_exists('AddGeoRawToVisitsTable')) { $this->publishes([ __DIR__ . '/../../database/migrations/add_geo_raw_to_visits_table.php.stub' => database_path("/migrations/{$timestamp}_add_geo_raw_to_visits_table.php"), ], 'migrations'); } $this->registerMacroHelpers(); } /** * Register any package services. */ public function register(): void { /** * Load default configurations. */ $this->mergeConfigFrom(__DIR__.'/../../config/visitor.php', 'visitor'); /** * Bind to service container. */ $this->app->singleton('shetabit-visitor', function () { $request = app(Request::class); return new Visitor($request, config('visitor')); }); } /** * Register micros */ protected function registerMacroHelpers(): void { Request::macro('visitor', function () { return app('shetabit-visitor'); }); } } ================================================ FILE: src/Resolvers/GeoIp/NullResolver.php ================================================ $position->ip, 'country_code' => $position->countryCode, 'country_name' => $position->countryName, 'region_name' => $position->regionName, 'city_name' => $position->cityName, 'latitude' => $position->latitude, 'longitude' => $position->longitude, ]; } } ================================================ FILE: src/Traits/CanVisit.php ================================================ morphMany(Visit::class, 'visitor'); } /** * Retrieve online users * @param $query * @param int $seconds * @return mixed */ public function scopeOnline($query, $seconds = 180) { $time = now()->subSeconds($seconds); return $query->whereHas('visitLogs', function ($query) use ($time) { $query->where(config('visitor.table_name') . ".created_at", '>=', $time->toDateTime()); }); } /** * check if user is online * @param int $seconds * @return bool */ public function isOnline($seconds = 180) { $time = now()->subSeconds($seconds); return $this->visitLogs()->whereHasMorph('user', [static::class], function ($query) use ($time) { $query ->where('user_id', $this->id) ->where(config('visitor.table_name') . ".created_at", '>=', $time->toDateTime()); })->count() > 0; } } ================================================ FILE: src/Traits/Visitable.php ================================================ morphMany(Visit::class, 'visitable'); } /** * Create a visit log. * * @param Model|null $visitor * * @return mixed */ public function createVisitLog(?Model $visitor) { return app('shetabit-visitor')->setVisitor($visitor)->visit($this); } } ================================================ FILE: src/Traits/Visitor.php ================================================ morphMany(Visit::class, 'visitor'); } /** * Create a visit log. * @param Model|null $visitable * @return mixed */ public function visit(?Model $visitable = NULL) { return app('shetabit-visitor')->setVisitor($this)->visit($visitable); } /** * Retrieve online users * @param $query * @param int $seconds * @return mixed */ public function scopeOnline($query, $seconds = 180) { $time = now()->subSeconds($seconds); $query->whereHas('visits', function ($query) use ($time) { $query->where(config('visitor.table_name') . ".created_at", '>=', $time->toDateTime()); }); } /** * check if user is online * @param int $seconds * @return bool */ public function isOnline($seconds = 180) { $time = now()->subSeconds($seconds); return $this->visits()->whereHasMorph('visitor', [static::class], function ($query) use ($time) { $query ->where('visitor_id', $this->id) ->where(config('visitor.table_name') . ".created_at", '>=', $time->toDateTime()); })->count() > 0; } } ================================================ FILE: src/Visitor.php ================================================ request = $request; $this->config = $config; $this->except = $config['except']; $this->via($this->config['default'], $this->config['resolver']); $this->setVisitor($request->user()); } /** * Change the driver and the resolver on the fly. * * @param $driver * @param $resolver * * @return $this * * @throws \Exception */ public function via($driver, $resolver) { $this->driver = $driver; $this->validateDriver(); $this->resolver = $resolver; $this->validateResolver(); return $this; } /** * Retrieve request's data * * @return array */ public function request() : array { return $this->request->all(); } /** * Retrieve user's ip. * * @return string|null */ public function ip() : ?string { return $this->request->ip(); } /** * Retrieve request's url * * @return string */ public function url() : string { return $this->request->fullUrl(); } /** * Retrieve request's referer * * @return string|null */ public function referer() : ?string { return $_SERVER['HTTP_REFERER'] ?? null; } /** * Retrieve request's method. * * @return string */ public function method() : string { return $this->request->getMethod(); } /** * Retrieve http headers. * * @return array */ public function httpHeaders() : array { return $this->request->headers->all(); } /** * Retrieve agent. * * @return string */ public function userAgent() : string { return $this->request->userAgent() ?? ''; } /** * Retrieve device's name. * * @return string * * @throws \Exception */ public function device() : string { return $this->getDriverInstance()->device(); } /** * Retrieve platform's name. * * @return string * * @throws \Exception */ public function platform() : string { return $this->getDriverInstance()->platform(); } /** * Retrieve browser's name. * * @return string * * @throws \Exception */ public function browser() : string { return $this->getDriverInstance()->browser(); } /** * Retrieve languages. * * @return array * * @throws \Exception */ public function languages() : array { return $this->getDriverInstance()->languages(); } /** * */ public function resolve(string $ip): ?array { if(!($this->config['geoip'] ?? false)){ return null; } return $this->getResolverInstance()->resolve($ip); } /** * */ public function geolocation(): ?array { $ip = $this->ip(); return $ip ? $this->resolve($ip) : null; } /** * Set visitor (user) * * @param Model|null $user * * @return $this */ public function setVisitor(?Model $user) { $this->visitor = $user; return $this; } /** * Retrieve visitor (user) * * @return Model|null */ public function getVisitor() : ?Model { return $this->visitor; } /** * Create a visit log. * * @param Model $model|null */ public function visit(?Model $model = null) { foreach ($this->except as $path) { if ($this->request->is($path)) { return; } } $data = $this->prepareLog(); if (null !== $model && method_exists($model, 'visitLogs')) { $visit = $model->visitLogs()->create($data); } else { $visit = Visit::create($data); } return $visit; } /** * Retrieve online visitors. * * @param string $model * @param int $seconds */ public function onlineVisitors(string $model, $seconds = 180) { return app($model)->online()->get(); } /** * Determine if given visitor or current one is online. * * @param Model|null $visitor * @param int $seconds * * @return bool */ public function isOnline(?Model $visitor = null, $seconds = 180) { $time = now()->subSeconds($seconds); $visitor = $visitor ?? $this->getVisitor(); if (empty($visitor)) { return false; } return Visit::whereHasMorph('visitor', get_class($visitor), function ($query) use ($visitor, $time) { $query->where('visitor_id', $visitor->id); })->whereDate('created_at', '>=', $time)->count() > 0; } /** * Prepare log's data. * * @return array * * @throws \Exception */ protected function prepareLog() : array { $log = [ 'method' => $this->method(), 'request' => $this->request(), 'url' => $this->url(), 'referer' => $this->referer(), 'languages' => $this->languages(), 'useragent' => $this->userAgent(), 'headers' => $this->httpHeaders(), 'device' => $this->device(), 'platform' => $this->platform(), 'browser' => $this->browser(), 'ip' => $this->ip(), 'visitor_id' => $this->getVisitor()?->id, 'visitor_type' => $this->getVisitor()?->getMorphClass() ]; if(!empty($this->config['geoip'])) { $log['geo_raw'] = $this->geolocation(); } return $log; } /** * Retrieve current driver instance or generate new one. * * @return mixed|object * * @throws \Exception */ protected function getDriverInstance() { if (!empty($this->driverInstance)) { return $this->driverInstance; } return $this->getFreshDriverInstance(); } /** * Get new driver instance * * @return Driver * * @throws \Exception */ protected function getFreshDriverInstance() { $this->validateDriver(); $driverClass = $this->config['drivers'][$this->driver]; return app($driverClass); } /** * Validate driver. * * @throws \Exception */ protected function validateDriver() { if (empty($this->driver)) { throw new DriverNotFoundException('Driver not selected or default driver does not exist.'); } $driverClass = $this->config['drivers'][$this->driver]; if (empty($driverClass) || !class_exists($driverClass)) { throw new DriverNotFoundException('Driver not found in config file. Try updating the package.'); } $reflect = new \ReflectionClass($driverClass); if (!$reflect->implementsInterface(UserAgentParser::class)) { throw new \Exception("Driver must be an instance of Contracts\Driver."); } } /** * Retrieve current resolver instance or generate new one. * * @return mixed|object * * @throws \Exception */ protected function getResolverInstance() { if (!empty($this->resolverInstance)) { return $this->resolverInstance; } return $this->getFreshResolverInstance(); } /** * Get new resolver instance * * @return Resolver * * @throws \Exception */ protected function getFreshResolverInstance() { $this->validateResolver(); $resolverClass = $this->config['resolvers'][$this->resolver]; return app($resolverClass); } /** * Validate resolver. * * @throws \Exception */ protected function validateResolver() { if (empty($this->resolver)) { throw new ResolverNotFoundException('Resolver not selected or default resolver does not exist.'); } $resolverClass = $this->config['resolvers'][$this->resolver]; if (empty($resolverClass) || !class_exists($resolverClass)) { throw new ResolverNotFoundException('Resolver not found in config file. Try updating the package.'); } $reflect = new \ReflectionClass($resolverClass); if (!$reflect->implementsInterface(GeoIpResolver::class)) { throw new \Exception("Resolver must be an instance of Contracts\Resolver."); } } } ================================================ FILE: src/helpers.php ================================================ 'Shetabit\Visitor\Facade\Visitor', ]; } }