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
================================================
<!-- Provide a general summary of the issue in the Title above -->
## 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 <khanzadimahdi@gmail.com>
> 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
================================================
<!--- Provide a general summary of your changes in the Title above -->
## 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
================================================
<p align="center"><img width="200" src="resources/images/visitor.png?raw=true"></p>
# 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
[](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
================================================
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Driver
|--------------------------------------------------------------------------
|
| This value determines which of the following driver to use.
| You can switch to a different driver at runtime.
|
*/
'default' => '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
================================================
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddGeoRawToVisitsTable extends Migration
{
public function up()
{
Schema::table(config('visitor.table_name'), function (Blueprint $table) {
$table->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
================================================
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVisitsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(config('visitor.table_name'), function (Blueprint $table) {
$table->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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<filter>
<whitelist>
<directory>./src/</directory>
</whitelist>
</filter>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
</php>
</phpunit>
================================================
FILE: src/Agent.php
================================================
<?php
namespace Shetabit\Visitor;
use BadMethodCallException;
use Closure;
use Detection\Exception\MobileDetectException;
use Detection\MobileDetect;
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Random\RandomException;
class Agent extends MobileDetect
{
/**
* List of desktop devices.
*
* @var array<string, string>
*/
protected static array $desktopDevices = [
'Macintosh' => 'Macintosh',
];
/**
* List of additional operating systems.
*
* @var array<string, string>
*/
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<string, string>
*/
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<string, mixed>
*/
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<string, string>
*/
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
================================================
<?php
namespace Shetabit\Visitor\Contracts;
interface GeoIpResolver
{
/**
* Resolve a given IP address into a GeoIP payload.
*
* @param string $ip
* @return array|null
*
* Example return:
* [
* 'ip' => '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
================================================
<?php
namespace Shetabit\Visitor\Contracts;
interface UserAgentParser
{
/**
* Retrieve device's name.
*
* @return string
*/
public function device() : string;
/**
* Retrieve platform's name.
*
* @return string
*/
public function platform() : string;
/**
* Retrieve browser's name.
*
* @return string
*/
public function browser() : string;
/**
* Retrieve languages.
*
* @return array
*/
public function languages() : array;
}
================================================
FILE: src/Drivers/JenssegersAgent.php
================================================
<?php
namespace Shetabit\Visitor\Drivers;
use Illuminate\Http\Request;
use Shetabit\Visitor\Agent;
use Shetabit\Visitor\Contracts\UserAgentParser;
class JenssegersAgent implements UserAgentParser
{
/**
* Request container.
*/
protected Request $request;
/**
* Agent parser.
*/
protected Agent $parser;
/**
* Parser constructor.
*
* @param Request $request
*/
public function __construct(Request $request)
{
$this->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
================================================
<?php
namespace Shetabit\Visitor\Drivers;
use UAParser\Parser;
use Illuminate\Http\Request;
use Shetabit\Visitor\Contracts\UserAgentParser;
class UAParser implements UserAgentParser
{
/**
* Request container.
*/
protected Request $request;
/**
* Agent parser.
*/
protected \UAParser\Result\Client $parser;
/**
* UAParser constructor.
*
* @param Request $request
*
* @throws \UAParser\Exception\FileNotFoundException
*/
public function __construct(Request $request)
{
$this->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
================================================
<?php
namespace Shetabit\Visitor\Exceptions;
class DriverNotFoundException extends \Exception
{
//
}
================================================
FILE: src/Exceptions/ResolverNotFoundException.php
================================================
<?php
namespace Shetabit\Visitor\Exceptions;
class ResolverNotFoundException extends \Exception
{
//
}
================================================
FILE: src/Facade/Agent.php
================================================
<?php
namespace Shetabit\Agent\Facades;
use Illuminate\Support\Facades\Facade;
class Agent extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor(): string
{
return 'agent';
}
}
================================================
FILE: src/Facade/Visitor.php
================================================
<?php
namespace Shetabit\Visitor\Facade;
use Illuminate\Support\Facades\Facade;
/**
* Class viewer
*
* @package Shetabit\Visitor\Facade
*/
class Visitor extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
public static function getFacadeAccessor(): string
{
return 'shetabit-visitor';
}
}
================================================
FILE: src/Middlewares/LogVisits.php
================================================
<?php
namespace Shetabit\Visitor\Middlewares;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class LogVisits
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$logHasSaved = false;
// create log for first binded model
foreach ($request->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
================================================
<?php
namespace Shetabit\Visitor\Models;
use Illuminate\Database\Eloquent\Model;
class Visit extends Model
{
public function __construct(array $attributes = [])
{
if (!isset($this->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
================================================
<?php
namespace Shetabit\Visitor\Provider;
use Illuminate\Support\ServiceProvider;
use Shetabit\Agent\Agent;
class AgentServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*/
public function register()
{
$this->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
================================================
<?php
namespace Shetabit\Visitor\Provider;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use Shetabit\Visitor\Visitor;
class VisitorServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot(): void
{
/**
* Configurations that needs to be done by user.
*/
$this->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
================================================
<?php
namespace Shetabit\Visitor\Resolvers\GeoIp;
use Shetabit\Visitor\Contracts\GeoIpResolver;
class NullResolver implements GeoIpResolver
{
public function resolve(string $ip): ?array
{
return null;
}
}
================================================
FILE: src/Resolvers/GeoIp/SteveBaumanResolver.php
================================================
<?php
namespace Shetabit\Visitor\Resolvers\GeoIp;
use Shetabit\Visitor\Contracts\GeoIpResolver;
use Stevebauman\Location\Facades\Location;
class SteveBaumanResolver implements GeoIpResolver
{
public function resolve(string $ip): ?array
{
$position = Location::get($ip);
if (!$position) {
return null;
}
return [
'ip' => $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
================================================
<?php
namespace Shetabit\Visitor\Traits;
use Illuminate\Support\Facades\Auth;
use Shetabit\Visitor\Models\Visit;
use Illuminate\Database\Eloquent\Builder;
trait CanVisit
{
/**
* Get all of the post's comments.
* @return mixed
*/
public function visitLogs()
{
return $this->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
================================================
<?php
namespace Shetabit\Visitor\Traits;
use Illuminate\Support\Facades\Auth;
use Shetabit\Visitor\Models\Visit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
trait Visitable
{
/**
* Get all of the model visit logs.
*
* @return mixed
*/
public function visitLogs()
{
return $this->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
================================================
<?php
namespace Shetabit\Visitor\Traits;
use Illuminate\Support\Facades\Auth;
use Shetabit\Visitor\Models\Visit;
use Illuminate\Database\Eloquent\Builder;
trait Visitor
{
/**
* Get all of the post's comments.
* @return mixed
*/
public function visits()
{
return $this->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
================================================
<?php
namespace Shetabit\Visitor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Shetabit\Visitor\Contracts\{UserAgentParser,GeoIpResolver};
use Shetabit\Visitor\Exceptions\DriverNotFoundException;
use Shetabit\Visitor\Models\Visit;
class Visitor implements UserAgentParser, GeoIpResolver
{
/**
* except.
*
* @var array
*/
protected $except;
/**
* Configuration.
*
* @var array
*/
protected $config;
/**
* Driver name.
*
* @var string
*/
protected $driver;
/**
* Driver instance.
*
* @var object
*/
protected $driverInstance;
/**
* Resolver name.
*
* @var string
*/
protected $resolver;
/**
* Resolver instance.
*
* @var object
*/
protected $resolverInstance;
/**
* Request instance.
*
* @var Request
*/
protected $request;
/**
* Visitor (user) instance.
*
* @var Model|null
*/
protected $visitor;
/**
* Visitor constructor.
*
* @param $config
*
* @throws \Exception
*/
public function __construct(Request $request, $config)
{
$this->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
================================================
<?php
if (!function_exists('visitor')) {
/**
* Access visitor through helper.
*
* @return \Shetabit\Visitor\Visitor
*/
function visitor()
{
return app('shetabit-visitor');
}
}
================================================
FILE: tests/TestCase.php
================================================
<?php
namespace Shetabit\Visitor\Tests;
use Orchestra\Testbench\TestCase as BaseTestCase;
use Shetabit\Visitor\Tests\Mocks\Drivers\BarDriver;
class TestCase extends BaseTestCase
{
protected function getPackageProviders($app)
{
return ['Shetabit\Visitor\Provider\VisitorServiceProvider'];
}
protected function getPackageAliases($app)
{
return [
'Visitor' => 'Shetabit\Visitor\Facade\Visitor',
];
}
}
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
SYMBOL INDEX (106 symbols across 21 files)
FILE: src/Agent.php
class Agent (line 12) | class Agent extends MobileDetect
method getRules (line 69) | public function getRules(): array
method languages (line 93) | public function languages(string $acceptLanguage = null): array
method browser (line 124) | public function browser(): bool|string
method retrieveUsingCacheOrResolve (line 140) | protected function retrieveUsingCacheOrResolve(string $key, Closure $c...
method createCacheKey (line 156) | protected function createCacheKey(string $key): string
method findDetectionRulesAgainstUserAgent (line 171) | protected function findDetectionRulesAgainstUserAgent(array $rules): ?...
method mergeRules (line 202) | protected function mergeRules(...$all): array
method platform (line 226) | public function platform(): bool|string
method device (line 239) | public function device(): bool|string
method getDesktopDevices (line 255) | public static function getDesktopDevices(): array
method robot (line 264) | public function robot(): bool|string
method getCrawlerDetect (line 278) | public function getCrawlerDetect(): CrawlerDetect
method deviceType (line 292) | public function deviceType(): string
method isDesktop (line 318) | public function isDesktop(): bool
method isRobot (line 338) | public function isRobot(): bool
method isPhone (line 350) | public function isPhone(): bool
method __call (line 358) | public function __call($name, $arguments)
FILE: src/Contracts/GeoIpResolver.php
type GeoIpResolver (line 5) | interface GeoIpResolver
method resolve (line 24) | public function resolve(string $ip): ?array;
FILE: src/Contracts/UserAgentParser.php
type UserAgentParser (line 5) | interface UserAgentParser
method device (line 12) | public function device() : string;
method platform (line 19) | public function platform() : string;
method browser (line 26) | public function browser() : string;
method languages (line 33) | public function languages() : array;
FILE: src/Drivers/JenssegersAgent.php
class JenssegersAgent (line 9) | class JenssegersAgent implements UserAgentParser
method __construct (line 26) | public function __construct(Request $request)
method device (line 35) | public function device() : string
method platform (line 43) | public function platform() : string
method browser (line 51) | public function browser() : string
method languages (line 59) | public function languages() : array
method initParser (line 67) | protected function initParser(): Agent
FILE: src/Drivers/UAParser.php
class UAParser (line 9) | class UAParser implements UserAgentParser
method __construct (line 28) | public function __construct(Request $request)
method device (line 37) | public function device() : string
method platform (line 45) | public function platform() : string
method browser (line 53) | public function browser() : string
method languages (line 61) | public function languages() : array
method initParser (line 78) | protected function initParser(): \UAParser\Result\Client
FILE: src/Exceptions/DriverNotFoundException.php
class DriverNotFoundException (line 5) | class DriverNotFoundException extends \Exception
FILE: src/Exceptions/ResolverNotFoundException.php
class ResolverNotFoundException (line 5) | class ResolverNotFoundException extends \Exception
FILE: src/Facade/Agent.php
class Agent (line 7) | class Agent extends Facade
method getFacadeAccessor (line 14) | protected static function getFacadeAccessor(): string
FILE: src/Facade/Visitor.php
class Visitor (line 12) | class Visitor extends Facade
method getFacadeAccessor (line 19) | public static function getFacadeAccessor(): string
FILE: src/Middlewares/LogVisits.php
class LogVisits (line 9) | class LogVisits
method handle (line 19) | public function handle($request, Closure $next)
FILE: src/Models/Visit.php
class Visit (line 7) | class Visit extends Model
method __construct (line 9) | public function __construct(array $attributes = [])
method visitable (line 45) | public function visitable()
method visitor (line 55) | public function visitor()
FILE: src/Provider/AgentServiceProvider.php
class AgentServiceProvider (line 8) | class AgentServiceProvider extends ServiceProvider
method register (line 20) | public function register()
method provides (line 34) | public function provides()
FILE: src/Provider/VisitorServiceProvider.php
class VisitorServiceProvider (line 9) | class VisitorServiceProvider extends ServiceProvider
method boot (line 16) | public function boot(): void
method register (line 48) | public function register(): void
method registerMacroHelpers (line 68) | protected function registerMacroHelpers(): void
FILE: src/Resolvers/GeoIp/NullResolver.php
class NullResolver (line 7) | class NullResolver implements GeoIpResolver
method resolve (line 9) | public function resolve(string $ip): ?array
FILE: src/Resolvers/GeoIp/SteveBaumanResolver.php
class SteveBaumanResolver (line 8) | class SteveBaumanResolver implements GeoIpResolver
method resolve (line 10) | public function resolve(string $ip): ?array
FILE: src/Traits/CanVisit.php
type CanVisit (line 9) | trait CanVisit
method visitLogs (line 15) | public function visitLogs()
method scopeOnline (line 26) | public function scopeOnline($query, $seconds = 180)
method isOnline (line 40) | public function isOnline($seconds = 180)
FILE: src/Traits/Visitable.php
type Visitable (line 10) | trait Visitable
method visitLogs (line 17) | public function visitLogs()
method createVisitLog (line 29) | public function createVisitLog(?Model $visitor)
FILE: src/Traits/Visitor.php
type Visitor (line 9) | trait Visitor
method visits (line 15) | public function visits()
method visit (line 25) | public function visit(?Model $visitable = NULL)
method scopeOnline (line 36) | public function scopeOnline($query, $seconds = 180)
method isOnline (line 51) | public function isOnline($seconds = 180)
FILE: src/Visitor.php
class Visitor (line 11) | class Visitor implements UserAgentParser, GeoIpResolver
method __construct (line 75) | public function __construct(Request $request, $config)
method via (line 94) | public function via($driver, $resolver)
method request (line 110) | public function request() : array
method ip (line 120) | public function ip() : ?string
method url (line 130) | public function url() : string
method referer (line 140) | public function referer() : ?string
method method (line 150) | public function method() : string
method httpHeaders (line 160) | public function httpHeaders() : array
method userAgent (line 170) | public function userAgent() : string
method device (line 182) | public function device() : string
method platform (line 194) | public function platform() : string
method browser (line 206) | public function browser() : string
method languages (line 218) | public function languages() : array
method resolve (line 226) | public function resolve(string $ip): ?array
method geolocation (line 238) | public function geolocation(): ?array
method setVisitor (line 251) | public function setVisitor(?Model $user)
method getVisitor (line 263) | public function getVisitor() : ?Model
method visit (line 273) | public function visit(?Model $model = null)
method onlineVisitors (line 299) | public function onlineVisitors(string $model, $seconds = 180)
method isOnline (line 312) | public function isOnline(?Model $visitor = null, $seconds = 180)
method prepareLog (line 334) | protected function prepareLog() : array
method getDriverInstance (line 366) | protected function getDriverInstance()
method getFreshDriverInstance (line 382) | protected function getFreshDriverInstance()
method validateDriver (line 396) | protected function validateDriver()
method getResolverInstance (line 422) | protected function getResolverInstance()
method getFreshResolverInstance (line 438) | protected function getFreshResolverInstance()
method validateResolver (line 452) | protected function validateResolver()
FILE: src/helpers.php
function visitor (line 8) | function visitor()
FILE: tests/TestCase.php
class TestCase (line 8) | class TestCase extends BaseTestCase
method getPackageProviders (line 10) | protected function getPackageProviders($app)
method getPackageAliases (line 15) | protected function getPackageAliases($app)
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (58K chars).
[
{
"path": ".gitattributes",
"chars": 204,
"preview": "/.gitattributes export-ignore\n/phpunit.xml export-ignore\n/tests export-igno"
},
{
"path": ".gitignore",
"chars": 28,
"preview": ".idea\nvendor/\n/composer.lock"
},
{
"path": "CHANGELOG.md",
"chars": 323,
"preview": "# Changelog\n\nAll Notable changes to `visitor` will be documented in this file.\n\nUpdates should follow the [Keep a CHANGE"
},
{
"path": "CONDUCT.md",
"chars": 3224,
"preview": "# Contributor Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncont"
},
{
"path": "CONTRIBUTING.md",
"chars": 1256,
"preview": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nWe accept contributions via Pull Requests"
},
{
"path": "ISSUE_TEMPLATE.md",
"chars": 718,
"preview": "<!-- Provide a general summary of the issue in the Title above -->\n\n## Detailed description\n\nProvide a detailed descript"
},
{
"path": "LICENSE.md",
"chars": 1141,
"preview": "# The MIT License (MIT)\n\nCopyright (c) 2019 Mahdi Khanzadi <khanzadimahdi@gmail.com>\n\n> Permission is hereby granted, fr"
},
{
"path": "PULL_REQUEST_TEMPLATE.md",
"chars": 1855,
"preview": "<!--- Provide a general summary of your changes in the Title above -->\n\n## Description\n\nDescribe your changes in detail."
},
{
"path": "README.md",
"chars": 3666,
"preview": "<p align=\"center\"><img width=\"200\" src=\"resources/images/visitor.png?raw=true\"></p>\n\n# Laravel Visitor\n\nThis is a larave"
},
{
"path": "composer.json",
"chars": 1897,
"preview": "{\n \"name\": \"shetabit/visitor\",\n \"type\": \"library\",\n \"description\": \"Laravel visitor\",\n \"keywords\": [\n "
},
{
"path": "config/visitor.php",
"chars": 2038,
"preview": "<?php\nreturn [\n /*\n |--------------------------------------------------------------------------\n | Default Driv"
},
{
"path": "database/migrations/add_geo_raw_to_visits_table.php.stub",
"chars": 556,
"preview": "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Fa"
},
{
"path": "database/migrations/create_visits_table.php.stub",
"chars": 1435,
"preview": "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Fa"
},
{
"path": "phpunit.xml",
"chars": 705,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit backupGlobals=\"false\"\n backupStaticAttributes=\"false\"\n boo"
},
{
"path": "src/Agent.php",
"chars": 9494,
"preview": "<?php\n\nnamespace Shetabit\\Visitor;\n\nuse BadMethodCallException;\nuse Closure;\nuse Detection\\Exception\\MobileDetectExcepti"
},
{
"path": "src/Contracts/GeoIpResolver.php",
"chars": 564,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Contracts;\n\ninterface GeoIpResolver\n{\n /**\n * Resolve a given IP address into a"
},
{
"path": "src/Contracts/UserAgentParser.php",
"chars": 542,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Contracts;\n\ninterface UserAgentParser\n{\n /**\n * Retrieve device's name.\n *\n"
},
{
"path": "src/Drivers/JenssegersAgent.php",
"chars": 1479,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Drivers;\n\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Visitor\\Agent;\nuse Shetabit\\Visito"
},
{
"path": "src/Drivers/UAParser.php",
"chars": 1645,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Drivers;\n\nuse UAParser\\Parser;\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Visitor\\Contr"
},
{
"path": "src/Exceptions/DriverNotFoundException.php",
"chars": 107,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Exceptions;\n\nclass DriverNotFoundException extends \\Exception\n{\n //\n}\n"
},
{
"path": "src/Exceptions/ResolverNotFoundException.php",
"chars": 109,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Exceptions;\n\nclass ResolverNotFoundException extends \\Exception\n{\n //\n}\n"
},
{
"path": "src/Facade/Agent.php",
"chars": 301,
"preview": "<?php\n\nnamespace Shetabit\\Agent\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\nclass Agent extends Facade\n{\n /**\n "
},
{
"path": "src/Facade/Visitor.php",
"chars": 375,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Facade;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\n/**\n * Class viewer\n *\n * @package Sh"
},
{
"path": "src/Middlewares/LogVisits.php",
"chars": 856,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Middlewares;\n\nuse Closure;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Supp"
},
{
"path": "src/Models/Visit.php",
"chars": 1316,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Visit extends Model\n{\n publ"
},
{
"path": "src/Provider/AgentServiceProvider.php",
"chars": 746,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Provider;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Shetabit\\Agent\\Agent;\n\nclass Ag"
},
{
"path": "src/Provider/VisitorServiceProvider.php",
"chars": 1960,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Provider;\n\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\ServiceProvider;\nuse Sh"
},
{
"path": "src/Resolvers/GeoIp/NullResolver.php",
"chars": 228,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Resolvers\\GeoIp;\n\nuse Shetabit\\Visitor\\Contracts\\GeoIpResolver;\n\nclass NullResolver im"
},
{
"path": "src/Resolvers/GeoIp/SteveBaumanResolver.php",
"chars": 748,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Resolvers\\GeoIp;\n\nuse Shetabit\\Visitor\\Contracts\\GeoIpResolver;\nuse Stevebauman\\Locati"
},
{
"path": "src/Traits/CanVisit.php",
"chars": 1281,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse I"
},
{
"path": "src/Traits/Visitable.php",
"chars": 659,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse I"
},
{
"path": "src/Traits/Visitor.php",
"chars": 1514,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse I"
},
{
"path": "src/Visitor.php",
"chars": 9766,
"preview": "<?php\n\nnamespace Shetabit\\Visitor;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Vi"
},
{
"path": "src/helpers.php",
"chars": 220,
"preview": "<?php\nif (!function_exists('visitor')) {\n /**\n * Access visitor through helper.\n *\n * @return \\Shetabit\\V"
},
{
"path": "tests/TestCase.php",
"chars": 463,
"preview": "<?php\n\nnamespace Shetabit\\Visitor\\Tests;\n\nuse Orchestra\\Testbench\\TestCase as BaseTestCase;\nuse Shetabit\\Visitor\\Tests\\M"
}
]
About this extraction
This page contains the full source code of the shetabit/visitor GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (52.2 KB), approximately 13.4k tokens, and a symbol index with 106 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.