Add YOURLS Amazon KDP Marketplace Redirect plugin
This commit is contained in:
commit
8de72714c1
6 files changed
+521
No files matched your search
@@ -0,0 +1,2 @@
|
||||
/.gitattributes export-ignore
|
||||
/tests export-ignore
|
||||
@@ -0,0 +1,57 @@
|
||||
# Amazon KDP Marketplace Redirect for YOURLS
|
||||
|
||||
## Installation
|
||||
|
||||
1. Place the `sebstr_amazon_kdp` directory in `user/plugins` on the development YOURLS installation.
|
||||
2. Activate **Amazon KDP Marketplace Redirect** in **Manage Plugins**.
|
||||
3. Open **Amazon KDP** in the administration menu. Enter an ASIN and an optional title, then select **Save ASIN**. Saving the same ASIN updates its title. Use **Remove** to unregister an edition.
|
||||
4. Shorten a standard Amazon product URL as usual. Register each edition's ASIN separately, including left-handed editions. Registration applies to existing and future short links across all source marketplaces in the table.
|
||||
|
||||
The registry uses the YOURLS option `sebstr_amazon_kdp_asins`. Short-link destination records retain the original URLs. The plugin targets YOURLS 1.10.6 and PHP 8.4 or newer.
|
||||
|
||||
## Redirect behaviour
|
||||
|
||||
The plugin recognises ten-character ASINs in Amazon `/dp/`, `/gp/product/`, and `/gp/aw/d/` product URLs. It matches only the marketplace hosts below, including their `www.` and `m.` variants. Explicit seller and offer URLs take precedence, including URLs with a merchant or seller parameter such as `smid` and URLs containing the legacy seller plugin's `cx_skuctr_share` marker.
|
||||
|
||||
For a registered edition, the same-marketplace and unavailable-country cases use the stored URL verbatim. Cross-marketplace redirects use a standard HTTPS product URL with the same ASIN and original fragment. Query parameters retain their original encoding and order, and the first occurrence of a repeated name is used for the rewritten URL. Amazon controls whether a parameter such as an affiliate tag has meaning on the destination marketplace.
|
||||
|
||||
Only eligible registered links bypass the legacy Amazon seller callback. YOURLS runs its usual click counter and detailed logging once per origin request, subject to its statistics settings, and then sends the 302. The plugin works with the seller plugin enabled or disabled.
|
||||
|
||||
## Cloudflare
|
||||
|
||||
Enable **IP Geolocation** for the dev zone. The origin's PHP `REMOTE_ADDR` must identify the Cloudflare peer for geolocation to work. If a reverse proxy or real-IP module replaces it with the visitor address, the plugin uses the original URL. Forwarded IP headers are ignored for this trust decision. The bundled IPv4 and IPv6 ranges come from Cloudflare's published lists and should be updated when those lists change. [IP Geolocation](https://developers.cloudflare.com/network/ip-geolocation/) · [Cloudflare IP ranges](https://www.cloudflare.com/ips/)
|
||||
|
||||
Eligible redirects send `Cache-Control: private, no-store, max-age=0` and `Cloudflare-CDN-Cache-Control: no-store`, including fallback redirects. If a zone rule overrides origin cache headers, set a Cache Rule to bypass caching for YOURLS short-link requests. Purge any previously cached redirects for those paths. A browser may retain a permanent redirect issued before activation until its local cache is cleared or expires. [Cloudflare default cache behaviour](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/) · [Cloudflare CDN cache-control headers](https://developers.cloudflare.com/cache/concepts/cdn-cache-control/)
|
||||
|
||||
## Marketplace mapping
|
||||
|
||||
| Country | Marketplace | Country | Marketplace |
|
||||
| --- | --- | --- | --- |
|
||||
| AU | amazon.com.au | BE | amazon.com.be |
|
||||
| BR | amazon.com.br | CA | amazon.ca |
|
||||
| DE | amazon.de | ES | amazon.es |
|
||||
| FR | amazon.fr | GB | amazon.co.uk |
|
||||
| IE | amazon.ie | IN | amazon.in |
|
||||
| IT | amazon.it | JP | amazon.co.jp |
|
||||
| MX | amazon.com.mx | NL | amazon.nl |
|
||||
| PL | amazon.pl | SE | amazon.se |
|
||||
| US | amazon.com | | |
|
||||
|
||||
The mapping includes marketplaces listed across Amazon's KDP print and Kindle documentation. Availability varies by edition, format, and distribution rights. For example, Brazil and Mexico support KDP eBooks, and Amazon has announced that Kindle eBook purchases on Amazon.in end on 26 February 2027. Review the India mapping before that transition. The plugin does no Amazon availability lookup, so a mapped marketplace may show an unavailable product if the edition is unavailable there. [KDP print distribution](https://kdp.amazon.com/en_US/help/topic/G201834280) · [KDP eBook distribution](https://kdp.amazon.com/en_US/help/topic/G200652410) · [India Kindle changes](https://kdp.amazon.com/en_US/help/topic/GK7ZLSRK7P8B9TV7)
|
||||
|
||||
## Automated tests
|
||||
|
||||
In a YOURLS installation with the existing seller plugin at `user/plugins/sebstr_amazon`, run `php user/plugins/sebstr_amazon_kdp/tests/run.php` from the YOURLS root. The suite uses PHP CLI and `php-cgi`. It loads the real YOURLS redirect and hook functions with isolated registry and statistics fixtures. It makes no database or network calls.
|
||||
|
||||
## Release package
|
||||
|
||||
Build the installable ZIP from the tagged commit:
|
||||
|
||||
```sh
|
||||
git archive --format=zip --prefix=sebstr_amazon_kdp/ \
|
||||
-o sebstr_amazon_kdp-1.0.0.zip v1.0.0
|
||||
```
|
||||
|
||||
Extract the ZIP under the target installation's `user/plugins` directory.
|
||||
The package contains the plugin PHP files and this README. Register the
|
||||
edition ASINs in YOURLS admin on the target installation.
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
/*
|
||||
Plugin Name: Amazon KDP Marketplace Redirect
|
||||
Description: Redirect registered KDP editions to the visitor's Amazon marketplace.
|
||||
Version: 1.0.0
|
||||
Author: Seb Molenaar
|
||||
Author URI: https://sebs.space
|
||||
*/
|
||||
|
||||
namespace Sebstr\AmazonKdp;
|
||||
|
||||
if (!defined('YOURLS_ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/routing.php';
|
||||
|
||||
const SETTINGS = 'sebstr_amazon_kdp_asins';
|
||||
|
||||
\yourls_add_action('plugins_loaded', __NAMESPACE__ . '\\register_settings');
|
||||
\yourls_add_action('redirect_shorturl', __NAMESPACE__ . '\\prepare_redirect');
|
||||
|
||||
function prepare_redirect(array $args): void
|
||||
{
|
||||
$original = $args[0];
|
||||
$product = product_url($original);
|
||||
if ($product === null || !array_key_exists($product['asin'], registry())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// This hook runs before core click tracking and before pre_redirect.
|
||||
\yourls_remove_action('pre_redirect', 'sebstr_amazon');
|
||||
|
||||
$country = visitor_country($_SERVER['REMOTE_ADDR'] ?? '', $_SERVER['HTTP_CF_IPCOUNTRY'] ?? '');
|
||||
$destination = marketplace_url($original, $product, $country);
|
||||
|
||||
\yourls_add_filter('redirect_location', static function ($location) use ($original, $destination) {
|
||||
if ($location !== $original) {
|
||||
return $location;
|
||||
}
|
||||
|
||||
header('Cache-Control: private, no-store, max-age=0');
|
||||
header('Cloudflare-CDN-Cache-Control: no-store');
|
||||
return $destination;
|
||||
});
|
||||
\yourls_add_filter('redirect_code', static function ($code, $location) use ($destination) {
|
||||
return $location === $destination ? 302 : $code;
|
||||
}, 10, 2);
|
||||
}
|
||||
|
||||
function registry(): array
|
||||
{
|
||||
$entries = \yourls_get_option(SETTINGS, []);
|
||||
return is_array($entries) ? $entries : [];
|
||||
}
|
||||
|
||||
function register_settings(): void
|
||||
{
|
||||
if (defined('YOURLS_ADMIN') && YOURLS_ADMIN) {
|
||||
\yourls_register_plugin_page('sebstr_amazon_kdp', 'Amazon KDP', __NAMESPACE__ . '\\settings_page');
|
||||
}
|
||||
}
|
||||
|
||||
function settings_page(): void
|
||||
{
|
||||
$entries = registry();
|
||||
$notice = '';
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
|
||||
$nonce = $_POST['nonce'] ?? '';
|
||||
\yourls_verify_nonce(SETTINGS, is_string($nonce) ? $nonce : '');
|
||||
$input = $_POST['asin'] ?? null;
|
||||
$asin = is_string($input) ? normalize_asin(trim($input)) : null;
|
||||
$operation = $_POST['operation'] ?? '';
|
||||
$title = $_POST['title'] ?? '';
|
||||
|
||||
if ($asin === null) {
|
||||
$notice = 'Enter a ten-character ASIN.';
|
||||
} elseif ($operation === 'remove' || ($operation === 'save' && is_string($title) && strlen($title) <= 1024)) {
|
||||
$updated = $entries;
|
||||
if ($operation === 'remove') {
|
||||
unset($updated[$asin]);
|
||||
} else {
|
||||
$updated[$asin] = trim($title);
|
||||
}
|
||||
if ($updated === $entries || \yourls_update_option(SETTINGS, $updated)) {
|
||||
$entries = $updated;
|
||||
$notice = $operation === 'remove' ? 'ASIN removed.' : 'ASIN saved.';
|
||||
} else {
|
||||
$notice = 'The registry could not be saved.';
|
||||
}
|
||||
} else {
|
||||
$notice = 'Enter a title of up to 1,024 bytes.';
|
||||
}
|
||||
}
|
||||
|
||||
ksort($entries, SORT_STRING);
|
||||
$nonce = \yourls_create_nonce(SETTINGS);
|
||||
?>
|
||||
<h2>Amazon KDP ASINs</h2>
|
||||
<p>Register each edition once. Registration applies to all short links for that ASIN.</p>
|
||||
<?php if ($notice !== ''): ?>
|
||||
<p role="status"><?= escape($notice) ?></p>
|
||||
<?php endif; ?>
|
||||
<form method="post">
|
||||
<input type="hidden" name="nonce" value="<?= escape($nonce) ?>">
|
||||
<label>ASIN <input name="asin" required maxlength="10" pattern="[A-Za-z0-9]{10}"></label>
|
||||
<label>Title (optional) <input name="title" maxlength="256"></label>
|
||||
<button type="submit" name="operation" value="save">Save ASIN</button>
|
||||
</form>
|
||||
<?php if ($entries !== []): ?>
|
||||
<table>
|
||||
<thead><tr><th scope="col">ASIN</th><th scope="col">Title</th><th scope="col">Action</th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($entries as $asin => $title): ?>
|
||||
<tr>
|
||||
<td><?= escape((string) $asin) ?></td>
|
||||
<td><?= escape($title) ?></td>
|
||||
<td>
|
||||
<form method="post">
|
||||
<input type="hidden" name="nonce" value="<?= escape($nonce) ?>">
|
||||
<input type="hidden" name="asin" value="<?= escape((string) $asin) ?>">
|
||||
<button type="submit" name="operation" value="remove" aria-label="Remove <?= escape((string) $asin) ?>">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif;
|
||||
}
|
||||
|
||||
function escape(string $value): string
|
||||
{
|
||||
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace Sebstr\AmazonKdp;
|
||||
|
||||
const MARKETPLACES = [
|
||||
'AU' => 'amazon.com.au', 'BE' => 'amazon.com.be', 'BR' => 'amazon.com.br',
|
||||
'CA' => 'amazon.ca', 'DE' => 'amazon.de', 'ES' => 'amazon.es',
|
||||
'FR' => 'amazon.fr', 'GB' => 'amazon.co.uk', 'IE' => 'amazon.ie',
|
||||
'IN' => 'amazon.in', 'IT' => 'amazon.it', 'JP' => 'amazon.co.jp',
|
||||
'MX' => 'amazon.com.mx', 'NL' => 'amazon.nl', 'PL' => 'amazon.pl',
|
||||
'SE' => 'amazon.se', 'US' => 'amazon.com',
|
||||
];
|
||||
|
||||
const CLOUDFLARE_NETWORKS = [
|
||||
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
|
||||
'141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
|
||||
'197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
|
||||
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
|
||||
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32',
|
||||
'2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
|
||||
];
|
||||
|
||||
function normalize_asin(string $asin): ?string
|
||||
{
|
||||
return preg_match('/\A[A-Z0-9]{10}\z/i', $asin) === 1 ? strtoupper($asin) : null;
|
||||
}
|
||||
|
||||
/** Return the components of an eligible product URL. */
|
||||
function product_url(string $url): ?array
|
||||
{
|
||||
if (preg_match('/[\x00-\x20\x7f]/', $url) || str_contains($url, '\\')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parts = parse_url($url);
|
||||
if ($parts === false || !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true)
|
||||
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$host = preg_replace('/^(?:www|m)\./', '', strtolower($parts['host'] ?? ''));
|
||||
$path = $parts['path'] ?? '';
|
||||
if (!in_array($host, MARKETPLACES, true)
|
||||
|| !preg_match('~\A/(?:[^/]+/)?dp/([a-z0-9]{10})(?:/|\z)|\A/gp/(?:product|aw/d)/([a-z0-9]{10})(?:/|\z)~i', $path, $matches)
|
||||
|| preg_match('~(?:^|/)(?:offer-listing(?:/|$)|ref=[^/]*cx_skuctr_share|[^/]*[?&](?:smid|seller|merchant|m|me)=)~i', rawurldecode($path))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parameters = [];
|
||||
foreach (explode('&', $parts['query'] ?? '') as $parameter) {
|
||||
if ($parameter === '') {
|
||||
continue;
|
||||
}
|
||||
$fields = explode('=', $parameter, 2);
|
||||
$name = urldecode($fields[0]);
|
||||
if (preg_match('/\A(?:smid|seller|sellerid|merchant|merchantid|m|me|offerlistingid)(?:\[|\z)/i', $name)
|
||||
|| (strcasecmp($name, 'ref') === 0 && str_starts_with(strtolower(urldecode($fields[1] ?? '')), 'cx_skuctr_share'))) {
|
||||
return null;
|
||||
}
|
||||
$parameters[$name] ??= $parameter;
|
||||
}
|
||||
|
||||
return [
|
||||
'host' => $host,
|
||||
'asin' => strtoupper(($matches[1] ?? '') ?: $matches[2]),
|
||||
'query' => implode('&', $parameters),
|
||||
'fragment' => $parts['fragment'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
function marketplace_url(string $original, array $product, ?string $country): string
|
||||
{
|
||||
$marketplace = MARKETPLACES[$country] ?? null;
|
||||
if ($marketplace === null || $marketplace === $product['host']) {
|
||||
return $original;
|
||||
}
|
||||
|
||||
$url = 'https://www.' . $marketplace . '/dp/' . $product['asin'];
|
||||
if ($product['query'] !== '') {
|
||||
$url .= '?' . $product['query'];
|
||||
}
|
||||
if ($product['fragment'] !== null) {
|
||||
$url .= '#' . $product['fragment'];
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
function visitor_country(string $peer, string $country): ?string
|
||||
{
|
||||
$country = strtoupper($country);
|
||||
if (!isset(MARKETPLACES[$country]) || !filter_var($peer, FILTER_VALIDATE_IP)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$address = inet_pton($peer);
|
||||
if (str_starts_with($address, str_repeat("\0", 10) . "\xff\xff")) {
|
||||
$address = substr($address, 12);
|
||||
}
|
||||
|
||||
foreach (CLOUDFLARE_NETWORKS as $cidr) {
|
||||
[$network, $prefix] = explode('/', $cidr);
|
||||
$network = inet_pton($network);
|
||||
if (strlen($address) !== strlen($network)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$bytes = intdiv((int) $prefix, 8);
|
||||
$remaining = (int) $prefix % 8;
|
||||
if (substr($address, 0, $bytes) === substr($network, 0, $bytes)
|
||||
&& ($remaining === 0 || ((ord($address[$bytes]) ^ ord($network[$bytes])) >> (8 - $remaining)) === 0)) {
|
||||
return $country;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
// Invoked by run.php in a fresh PHP CGI process for each request.
|
||||
if (getenv('SEBSTR_KDP_TEST_URL') === false || PHP_SAPI !== 'cgi-fcgi') {
|
||||
exit;
|
||||
}
|
||||
|
||||
define('YOURLS_ABSPATH', dirname(__DIR__, 4) . '/');
|
||||
require YOURLS_ABSPATH . 'includes/functions-plugins.php';
|
||||
require YOURLS_ABSPATH . 'includes/functions.php';
|
||||
|
||||
function yourls_get_option($name, $default = false)
|
||||
{
|
||||
return $name === 'sebstr_amazon_kdp_asins' ? ['TESTBOOK01' => 'Standard', '1234567890' => 'Left-handed'] : $default;
|
||||
}
|
||||
|
||||
$clicks = $logs = 0;
|
||||
yourls_add_filter('shunt_update_clicks', static function () use (&$clicks) {
|
||||
++$clicks;
|
||||
return true;
|
||||
});
|
||||
yourls_add_filter('shunt_log_redirect', static function () use (&$logs) {
|
||||
++$logs;
|
||||
return true;
|
||||
});
|
||||
yourls_add_filter('shunt_robots_tag_header', static fn () => true);
|
||||
register_shutdown_function(static function () use (&$clicks, &$logs) {
|
||||
echo "clicks=$clicks logs=$logs";
|
||||
});
|
||||
|
||||
if (getenv('SEBSTR_KDP_TEST_KDP') === '1') {
|
||||
require dirname(__DIR__) . '/plugin.php';
|
||||
}
|
||||
if (getenv('SEBSTR_KDP_TEST_SELLER') === '1') {
|
||||
require dirname(__DIR__, 2) . '/sebstr_amazon/plugin.php';
|
||||
}
|
||||
|
||||
$_SERVER['REMOTE_ADDR'] = getenv('SEBSTR_KDP_TEST_PEER');
|
||||
$country = getenv('SEBSTR_KDP_TEST_COUNTRY');
|
||||
if ($country !== '') {
|
||||
$_SERVER['HTTP_CF_IPCOUNTRY'] = $country;
|
||||
}
|
||||
yourls_redirect_shorturl(getenv('SEBSTR_KDP_TEST_URL'), 'existing-keyword');
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
exit;
|
||||
}
|
||||
|
||||
require dirname(__DIR__) . '/routing.php';
|
||||
|
||||
use function Sebstr\AmazonKdp\visitor_country;
|
||||
|
||||
function check(bool $ok, string $message): void
|
||||
{
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
check(visitor_country('2a06:98c7::1', 'GB') === 'GB', 'IPv6 prefix upper boundary');
|
||||
check(visitor_country('2a06:98c8::1', 'GB') === null, 'IPv6 outside prefix');
|
||||
check(visitor_country('104.23.255.255', 'NL') === 'NL', 'IPv4 prefix upper boundary');
|
||||
check(visitor_country('104.28.0.1', 'NL') === null, 'IPv4 outside prefix');
|
||||
check(visitor_country('::ffff:104.16.0.1', 'NL') === 'NL', 'IPv4-mapped Cloudflare address');
|
||||
|
||||
$uk = 'https://www.amazon.co.uk/dp/TESTBOOK01';
|
||||
$us = 'https://www.amazon.com/dp/TESTBOOK01';
|
||||
$de = 'https://www.amazon.de/dp/TESTBOOK01';
|
||||
$nl = 'https://www.amazon.nl/dp/TESTBOOK01';
|
||||
$left = 'https://www.amazon.com.au/gp/product/1234567890';
|
||||
$seller = $uk . '?smid=EXPLICIT';
|
||||
$legacy = $uk . '/ref=cx_skuctr_share?smid=EXPLICIT';
|
||||
$sellerTag = '/ref=cx_skuctr_share?smid={seller-id}';
|
||||
$unrelated = 'https://www.amazon.com/dp/B012345678';
|
||||
$unrelatedUk = 'https://www.amazon.co.uk/dp/B012345678';
|
||||
$nonAmazon = 'https://example.com/dp/TESTBOOK01';
|
||||
$impostor = 'https://amazon.com.example.org/dp/TESTBOOK01';
|
||||
|
||||
$cases = [
|
||||
['UK original', $uk, 'GB', $uk, 302],
|
||||
['US from same short link', $uk, 'US', $us, 302],
|
||||
['NL from same short link', $uk, 'NL', $nl, 302],
|
||||
['Germany from same short link', $uk, 'DE', $de, 302],
|
||||
['from Germany', $de, 'GB', $uk, 302],
|
||||
['from Netherlands', $nl, 'US', $us, 302],
|
||||
['Belgium', $us, 'BE', 'https://www.amazon.com.be/dp/TESTBOOK01', 302],
|
||||
['Ireland', $us, 'IE', 'https://www.amazon.ie/dp/TESTBOOK01', 302],
|
||||
['Brazil', $uk, 'BR', 'https://www.amazon.com.br/dp/TESTBOOK01', 302],
|
||||
['Mexico', $uk, 'MX', 'https://www.amazon.com.mx/dp/TESTBOOK01', 302],
|
||||
['unsupported', $uk, 'CH', $uk, 302],
|
||||
['missing', $uk, '', $uk, 302],
|
||||
['invalid', $uk, 'NL,US', $uk, 302],
|
||||
['spoofed', $uk, 'NL', $uk, 302, true, true, '203.0.113.2'],
|
||||
['queries and fragment', $uk . '?tag=foo&%74ag=bar&th=1&k=two%20words#detail', 'US',
|
||||
$us . '?tag=foo&th=1&k=two%20words#detail', 302],
|
||||
['exact fallback', $uk . '?th=1&th=2', 'XX', $uk . '?th=1&th=2', 302],
|
||||
['left-handed', $left, 'DE', 'https://www.amazon.de/dp/1234567890', 302],
|
||||
['seller parameter', $seller, 'US', $seller . '&ref=cx_skuctr_share?smid={seller-id}', 301],
|
||||
['legacy seller path alone', $legacy, 'US', $legacy, 301, true, false],
|
||||
['encoded seller selection', $us . '?%73mid=EXPLICIT', 'DE', $us . '?%73mid=EXPLICIT', 301],
|
||||
['seller via ref query', $us . '?ref=cx_skuctr_share%3Fsmid%3DEXPLICIT', 'DE',
|
||||
$us . '?ref=cx_skuctr_share%3Fsmid%3DEXPLICIT', 301],
|
||||
['other Amazon product', $unrelated, 'DE', $unrelated, 301],
|
||||
['seller plugin handles unregistered products', $unrelatedUk, 'DE', $unrelatedUk . $sellerTag, 301],
|
||||
['non-Amazon', $nonAmazon, 'DE', $nonAmazon, 301],
|
||||
['impostor host', $impostor, 'DE', $impostor, 301],
|
||||
['malformed ASIN', $us . 'X', 'DE', $us . 'X', 301],
|
||||
['KDP alone', $uk, 'US', $us, 302, true, false],
|
||||
['seller alone', $uk, 'US', $uk . $sellerTag, 301, false, true],
|
||||
];
|
||||
|
||||
foreach ($cases as $case) {
|
||||
[$label, $url, $country, $expected, $status] = $case;
|
||||
$environment = [
|
||||
'REDIRECT_STATUS' => '200',
|
||||
'GATEWAY_INTERFACE' => 'CGI/1.1',
|
||||
'REQUEST_METHOD' => 'GET',
|
||||
'SERVER_PROTOCOL' => 'HTTP/1.1',
|
||||
'SCRIPT_FILENAME' => __DIR__ . '/request.php',
|
||||
'SEBSTR_KDP_TEST_URL' => $url,
|
||||
'SEBSTR_KDP_TEST_COUNTRY' => $country,
|
||||
'SEBSTR_KDP_TEST_PEER' => $case[7] ?? '104.16.0.1',
|
||||
'SEBSTR_KDP_TEST_KDP' => ($case[5] ?? true) ? '1' : '0',
|
||||
'SEBSTR_KDP_TEST_SELLER' => ($case[6] ?? true) ? '1' : '0',
|
||||
];
|
||||
$process = proc_open(['php-cgi', '-d', 'display_errors=stderr', '-d', 'log_errors=0'], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $environment);
|
||||
check(is_resource($process), 'Start php-cgi');
|
||||
$output = stream_get_contents($pipes[1]);
|
||||
$errors = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
check(proc_close($process) === 0, "$label CGI error $errors $output");
|
||||
$locationPattern = str_replace(preg_quote('{seller-id}', '~'), '[A-Z0-9]+', preg_quote($expected, '~'));
|
||||
check(str_contains($output, "Status: $status ") && preg_match("~^Location: $locationPattern\\r?$~m", $output) === 1,
|
||||
"$label unexpected response $output $errors");
|
||||
check(str_contains($output, 'clicks=1 logs=1'), "$label tracking mismatch");
|
||||
check(str_contains($output, 'Cache-Control: private, no-store, max-age=0') === ($status === 302), "$label browser cache header mismatch");
|
||||
check(str_contains($output, 'Cloudflare-CDN-Cache-Control: no-store') === ($status === 302), "$label Cloudflare cache header mismatch");
|
||||
}
|
||||
|
||||
echo count($cases) . " CGI redirect cases and five IP checks passed.\n";
|
||||
|
||||
define('YOURLS_ABSPATH', dirname(__DIR__, 4) . '/');
|
||||
define('YOURLS_ADMIN', true);
|
||||
require YOURLS_ABSPATH . 'includes/functions-plugins.php';
|
||||
|
||||
function yourls_get_option($name, $default = false)
|
||||
{
|
||||
return $GLOBALS['test_options'][$name] ?? $default;
|
||||
}
|
||||
|
||||
function yourls_update_option($name, $value)
|
||||
{
|
||||
$GLOBALS['test_options'][$name] = $value;
|
||||
return true;
|
||||
}
|
||||
|
||||
function yourls_get_db($context)
|
||||
{
|
||||
return new class {
|
||||
public function add_plugin_page($slug, $title, $callback): void
|
||||
{
|
||||
$GLOBALS['test_pages'][$slug] = $callback;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function yourls_create_nonce($action)
|
||||
{
|
||||
return 'test-' . $action;
|
||||
}
|
||||
|
||||
function yourls_verify_nonce($action, $nonce)
|
||||
{
|
||||
if ($nonce !== yourls_create_nonce($action)) {
|
||||
throw new InvalidArgumentException('Invalid nonce');
|
||||
}
|
||||
}
|
||||
|
||||
require dirname(__DIR__) . '/plugin.php';
|
||||
yourls_do_action('plugins_loaded');
|
||||
$page = $GLOBALS['test_pages']['sebstr_amazon_kdp'] ?? null;
|
||||
check(is_callable($page), 'YOURLS admin page registration');
|
||||
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$key = Sebstr\AmazonKdp\SETTINGS;
|
||||
$_POST = ['operation' => 'save', 'asin' => 'testbook01', 'title' => '<Standard>', 'nonce' => 'invalid'];
|
||||
ob_start();
|
||||
try {
|
||||
$page();
|
||||
check(false, 'Invalid nonce accepted');
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
check(yourls_get_option($key, []) === [], 'Invalid nonce changed registry');
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
$_POST['nonce'] = yourls_create_nonce($key);
|
||||
ob_start();
|
||||
$page();
|
||||
$html = ob_get_clean();
|
||||
check(str_contains($html, '<Standard>'), 'Title is escaped');
|
||||
check(yourls_get_option($key) === ['TESTBOOK01' => '<Standard>'], 'ASIN and title saved');
|
||||
|
||||
$_POST = ['operation' => 'remove', 'asin' => 'TESTBOOK01', 'nonce' => yourls_create_nonce($key)];
|
||||
ob_start();
|
||||
$page();
|
||||
ob_end_clean();
|
||||
check(yourls_get_option($key) === [], 'ASIN removed');
|
||||
|
||||
echo "Admin registration, nonce rejection, title escaping, addition and removal passed.\n";
|
||||
Reference in New Issue
Block a user