Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
luchaninov committed Oct 2, 2022
0 parents commit bdd885a
Show file tree
Hide file tree
Showing 14 changed files with 557 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/.idea/
/vendor/
/.phpunit.result.cache
/composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Volodymyr Luchaninov

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.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Cloakings Palladium
===================

Detect if user is bot or real user using palladium.expert

## Install

```bash
composer require cloakings/cloakings-palladium
```

## Usage

### Basic Usage

Register at https://palladium.expert. Create campaign:
- Link to the target page: real.php
- Link for bots: fake.php

Click "download code" for plain PHP or Wordpress and look for:
- clientId
- clientCompany
- clientSecret

```php
$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
$cloaker = \Cloakings\CloakingsPalladium\PalladiumCloaker(
clientId: $clientId,
clientCompany: $clientCompany,
clientSecret: $clientSecret,
);
$cloakerResult = $cloaker->handle($request);
```

Check if result mode is `CloakModeEnum::Fake` or `CloakModeEnum::Real` and do something with it.

If you want to render result like the original Palladium library
```php
$baseIncludeDir = __DIR__; // change to your dir with real.php and fake.php
$renderer = \Cloakings\CloakingsPalladium\PalladiumRenderer();
$response = $renderer->render($cloakerResult);
```

If your filenames differ from `real.php` and `fake.php` change params `$fakeTargetContains` and `$realTargetContains`
in `PalladiumCloaker` constructor.

Default traffic source is `PalladiumTrafficSourceEnum::Adwords` but you can change it to `Facebook` or `Tiktok`.
26 changes: 26 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "cloakings/cloakings-palladium",
"description": "Cloakings Palladium Client",
"type": "library",
"license": "MIT",
"require": {
"php": ">=8.1",
"ext-curl": "*",
"cloakings/cloakings-common": "^1.1",
"gupalo/json": "^1.0",
"psr/log": "^3.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"Cloakings\\CloakingsPalladium\\": "src/CloakingsPalladium/"
}
},
"autoload-dev": {
"psr-4": {
"Cloakings\\Tests\\CloakingsPalladium\\": "tests/CloakingsPalladium/"
}
}
}
26 changes: 26 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
>
<coverage>
<include>
<directory>src</directory>
</include>
</coverage>
<php>
<ini name="error_reporting" value="-1"/>
<server name="SHELL_VERBOSITY" value="-1"/>
<server name="SYMFONY_PHPUNIT_REMOVE" value=""/>
<server name="SYMFONY_PHPUNIT_VERSION" value="7.5"/>
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
53 changes: 53 additions & 0 deletions src/CloakingsPalladium/PalladiumApiResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Cloakings\CloakingsPalladium;

class PalladiumApiResponse
{
private function __construct(
public readonly bool $status,
public readonly string $target,
public readonly PalladiumApiResponseModeEnum $mode,
public readonly string $content,
) {
}

public function isEmpty(): bool
{
return (
$this->mode === PalladiumApiResponseModeEnum::Unknown ||
($this->target === '' && $this->content === '')
);
}

public function isValidTarget(): bool
{
return (
in_array($this->mode, [
PalladiumApiResponseModeEnum::Iframe,
PalladiumApiResponseModeEnum::Redirect,
PalladiumApiResponseModeEnum::TargetPath,
], true) &&
$this->target !== ''
);
}

public static function create(array $apiResponse): self
{
$status = (bool)($apiResponse['result'] ?: false);
$target = (string)($apiResponse['target'] ?? '');
$mode = PalladiumApiResponseModeEnum::tryFrom((int)($apiResponse['mode'] ?? 0)) ?? PalladiumApiResponseModeEnum::Unknown;
$content = (string)($apiResponse['content'] ?? '');

if ($mode === PalladiumApiResponseModeEnum::TargetPath && preg_match('#^https?:#i', $target)) {
$mode = PalladiumApiResponseModeEnum::Redirect; // fallback to mode2
}

return new self(
status: $status,
target: $target,
mode: $mode,
content: $content,
);
}
}
14 changes: 14 additions & 0 deletions src/CloakingsPalladium/PalladiumApiResponseModeEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Cloakings\CloakingsPalladium;

enum PalladiumApiResponseModeEnum: int
{
case Unknown = 0;
case Iframe = 1;
case Redirect = 2;
case TargetPath = 3;
case Content = 4;
case EmptyIfEmptyStatus = 5;
case Empty = 6;
}
73 changes: 73 additions & 0 deletions src/CloakingsPalladium/PalladiumCloaker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace Cloakings\CloakingsPalladium;

use Cloakings\CloakingsCommon\CloakerInterface;
use Cloakings\CloakingsCommon\CloakerResult;
use Cloakings\CloakingsCommon\CloakModeEnum;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class PalladiumCloaker implements CloakerInterface
{
private PalladiumDataCollector $dataCollector;
private PalladiumHttpClient $httpClient;

public function __construct(
private readonly int $clientId,
private readonly string $clientCompany,
private readonly string $clientSecret,
private readonly PalladiumTrafficSourceEnum $trafficSource = PalladiumTrafficSourceEnum::Adwords,
private readonly string $fakeTargetContains = 'fake',
private readonly string $realTargetContains = 'real',
PalladiumDataCollector $dataCollector = null,
PalladiumHttpClient $httpClient = null,
) {
$this->dataCollector = $dataCollector ?? new PalladiumDataCollector();
$this->httpClient = $httpClient ?? new PalladiumHttpClient();
}

public function handle(Request $request): CloakerResult
{
if ((int)$request->query->get('dr_jsess', '') === 1) {
return new CloakerResult(CloakModeEnum::Response, new Response());
}

$params = $this->collectParams($request);
$apiResponse = $this->httpClient->curlSend($params);

$mode = match (true) {
(!$apiResponse || !$apiResponse->isValidTarget()) => CloakModeEnum::Error,
str_contains($apiResponse->target, $this->fakeTargetContains) => CloakModeEnum::Fake,
str_contains($apiResponse->target, $this->realTargetContains) => CloakModeEnum::Real,
default => CloakModeEnum::Response,
};

$response = new Response(
content: $apiResponse->content,
headers: [
'x-mode' => $apiResponse->mode->value,
'x-target' => $apiResponse->target,
],
);

return new CloakerResult($mode, $response);
}

private function collectParams(Request $request): array
{
return [
'request' => $this->dataCollector->collectRequestData($request),
'jsrequest' => $this->dataCollector->collectJsRequestData($request),
'server' => array_merge(
$this->dataCollector->collectHeaders($request),
['bannerSource' => $this->trafficSource->value],
),
'auth' => [
'clientId' => $this->clientId,
'clientCompany' => $this->clientCompany,
'clientSecret' => $this->clientSecret,
],
];
}
}
78 changes: 78 additions & 0 deletions src/CloakingsPalladium/PalladiumDataCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace Cloakings\CloakingsPalladium;

use Gupalo\Json\Json;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

class PalladiumDataCollector
{
public function collectRequestData(Request $request): array
{
$data = [];
if ($request->request->all()) {
$postData = $request->request->get('data');
if ($postData) {
try {
$data = Json::toArray($postData);
} catch (Throwable) {
$data = Json::toArray(stripslashes($postData));
}
}

$postCrossrefSessionid = $request->request->get('crossref_sessionid');
if ($postCrossrefSessionid) {
$data['cr-session-id'] = $postCrossrefSessionid;
}
}

return $data;
}

public function collectJsRequestData(Request $request): array
{
$data = [];
if ($request->request->all()) {
$postJsdata = $request->request->get('jsdata');
if ($postJsdata) {
try {
$data = Json::toArray($postJsdata);
} catch (Throwable) {
$data = Json::toArray(stripslashes($postJsdata));
}
}
}
return $data;
}

public function collectHeaders(Request $request): array
{
$userParams = [
'remote-addr' => true,
'server-protocol' => true,
'server-port' => true,
'remote-port' => true,
'query-string' => true,
'request-scheme' => true,
'request-uri' => true,
'request-time-float' => true,
'x-fb-http-engine' => true,
'x-purpose' => true,
'x-forwarded-for' => true,
'x-wap-profile' => true,
'x-forwarded-host' => true,
'x-frame-options' => true,
];

$headers = [];
foreach ($request->server->all() as $key => $value) {
$normalizedKey = str_replace('_', '-', mb_strtolower($key));
if (isset($userParams[$normalizedKey]) || str_starts_with($normalizedKey, 'http')) {
$headers[$key] = $value;
}
}

return $headers;
}
}
Loading

0 comments on commit bdd885a

Please sign in to comment.