This commit is contained in:
@@ -1,5 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## 1.0.4 - 2026-10-01
|
||||
|
||||
- Expanded the README into a complete settings reference with country detection, local MaxMind setup, and visitor IP source guidance.
|
||||
- Added official GeoLite2 download and update instructions.
|
||||
- Clarified the Visitor IP source labels and Admin CP help while keeping `REMOTE_ADDR` as the recommended default.
|
||||
- Added a MaxMind status checker for the resolved path, file readability, PHP reader, and database validity.
|
||||
- Bundled MaxMind official pure-PHP DB reader 1.14.0 for local lookups without Composer, a compiled extension, or an autoloader-path setting.
|
||||
- Removed the obsolete MaxMind reader autoload setting during settings synchronization.
|
||||
|
||||
## 1.0.3 - 2026-09-20
|
||||
|
||||
- Added configurable country detection using trusted headers, a local MaxMind-compatible database, or the browser language region.
|
||||
|
||||
@@ -55,24 +55,64 @@ Image and destination fields accept full HTTP(S) URLs or site-relative paths beg
|
||||
|
||||
Country targeting is configurable. The default automatic order reads country headers supplied by Cloudflare, a server GeoIP module, App Engine, CloudFront, Fastly, or Vercel; then queries an optional local MaxMind-compatible database; and finally uses the first browser language region in `Accept-Language`, such as `en-US`. An allowlist does not deliver when no country signal is available; a blocklist does. The plugin never calls an external geolocation service.
|
||||
|
||||
Local GeoIP lookups require the official `maxmind-db/reader` PHP library and a readable GeoLite2 or GeoIP2 Country/City `.mmdb` file. Install the reader in the forum root with Composer, or provide the absolute path to its `autoload.php` file in the plugin settings. Database downloads and updates remain under the administrator's control. `REMOTE_ADDR` is the safe default IP source; select a forwarded header only when a trusted proxy overwrites it.
|
||||
## Settings reference
|
||||
|
||||
General display and timing options remain under **Configuration -> Settings -> Rotating Ads**.
|
||||
That page also displays the two supported template variables as read-only values; the plugin never inserts an ad slot into the index or another template automatically.
|
||||
Rotating Ads settings live in **Admin CP -> Configuration -> Settings -> Rotating Ads**. Individual advertisements are managed separately under **Admin CP -> Configuration -> Rotating Ads**.
|
||||
|
||||
Additional settings:
|
||||
| Setting | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| Template variables | Shows the `{$rotating_ads_square}` and `{$rotating_ads_banner}` variables to place in theme templates. This is a read-only reference. | No value |
|
||||
| Sponsor label | Text displayed above each ad. Leave blank to hide the label. | `Sponsored` |
|
||||
| Hide ads from usergroups | Comma-separated primary or additional usergroup IDs that should not see either ad slot. Leave blank to show ads to every group. | Empty |
|
||||
| Load plugin CSS | Loads the maintained responsive ad stylesheet. Disable it when the active theme supplies all ad styling. | Yes |
|
||||
| Open ads in a new tab | Adds new-tab behavior to advertisement links. | Yes |
|
||||
| Show destination in tracked links | Adds a readable `to=example.com` hostname to tracked click URLs so visitors can recognize the destination. | Yes |
|
||||
| Rotate ads while viewing a page | Uses JavaScript to cycle through eligible ads without a page reload. A slot with fewer than two ads remains static, as does the page for visitors without JavaScript. | No |
|
||||
| Minimum rotation seconds | Shortest time an ad remains visible during browser-side rotation. | `15` |
|
||||
| Maximum rotation seconds | Longest rotation delay. A value below the minimum is treated as the minimum. | `30` |
|
||||
| Country detection | Selects how the plugin resolves the two-letter country code used by ad allowlists and blocklists. See [Country detection options](#country-detection-options). | Automatic |
|
||||
| MaxMind database path | MyBB-root-relative database file or directory. The recommended `/inc/geoip` directory automatically selects `GeoLite2-Country.mmdb`. Leave blank to skip local lookups. | Empty |
|
||||
| Visitor IP source | Selects the address used only for local MaxMind lookups. See [Visitor IP source options](#visitor-ip-source-options). | `REMOTE_ADDR` |
|
||||
|
||||
- `Sponsor label`: Optional text displayed above each ad. Leave blank to hide it.
|
||||
- `Hide ads from usergroups`: Comma-separated primary or additional usergroup IDs that should not see ads.
|
||||
- `Load plugin CSS`: Disable if your theme provides its own ad styling.
|
||||
- `Open ads in a new tab`: Controls whether links include `target="_blank"`.
|
||||
- `Show destination in tracked links`: Adds a readable `to=example.com` hostname to click-tracking URLs. Disable it for shorter tracked links.
|
||||
- `Rotate ads while viewing a page`: Enables JavaScript-powered browser-side cycling when a slot has at least two enabled ads.
|
||||
- `Minimum rotation seconds` / `Maximum rotation seconds`: Controls the random delay range between ad changes. If maximum is below minimum, the plugin treats it as the minimum.
|
||||
- `Country detection`: Uses the automatic provider chain, one specific provider, or disables detection.
|
||||
- `MaxMind database path`: Absolute path to a local GeoLite2 or GeoIP2 `.mmdb` database.
|
||||
- `MaxMind reader autoload path`: Optional path to the official reader's `autoload.php`; the forum root Composer autoloader is detected automatically.
|
||||
- `Visitor IP source`: Selects the address used for local database lookups. Forwarded headers must only be trusted behind a configured proxy.
|
||||
### Country detection options
|
||||
|
||||
Country targeting controls whether an advertisement is eligible; it does not change the advertisement content. An allowlist does not deliver when no country can be resolved, while a blocklist remains eligible. No mode calls an external geolocation service.
|
||||
|
||||
| Option | Behavior |
|
||||
| --- | --- |
|
||||
| Headers, then MaxMind, then browser language | Recommended automatic chain. It first checks trusted country headers, then the configured local MaxMind database, and finally a region in `Accept-Language`. |
|
||||
| Server/proxy headers only | Checks country codes supplied by Cloudflare, a server GeoIP module, App Engine, CloudFront, Fastly, or Vercel. Use when the origin trusts and receives one of those headers. |
|
||||
| MaxMind database only | Looks up the selected visitor IP in the configured local `.mmdb` database. It requires both the database file and the official `maxmind-db/reader` PHP library. |
|
||||
| Browser language region only | Uses the first regional browser language, such as `US` from `en-US`. This is a preference signal and may not represent the visitor physical location. |
|
||||
| Disabled | Resolves no country. Country allowlisted ads do not deliver; blocklisted ads remain eligible because no blocked country was identified. |
|
||||
|
||||
### Local MaxMind setup
|
||||
|
||||
The free **GeoLite2 Country** database is sufficient for this plugin. Obtain it from the [official MaxMind GeoLite page](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/):
|
||||
|
||||
1. Create or sign in to a free MaxMind account.
|
||||
2. From the account portal, request access to GeoLite and complete any required enrollment steps. The database downloads appear after MaxMind enables GeoLite access for the account.
|
||||
3. On **Download files**, find **GeoLite Country** with edition ID `GeoLite2-Country` and format **GeoIP2 Binary (.mmdb)**, then select **Download GZIP**. Do not choose GeoLite ASN or a CSV-format download. GeoLite City also works, but it is larger and provides location detail this plugin does not use. After extracting the download, the database file should be named `GeoLite2-Country.mmdb`. Create `inc/geoip` under the MyBB board root and place the file there, producing `inc/geoip/GeoLite2-Country.mmdb`.
|
||||
4. Enter `/inc/geoip` in **MaxMind database path**. A path beginning with `/inc` is resolved from the MyBB board root, and a directory path automatically uses the filename `GeoLite2-Country.mmdb`. `/inc/geoip/GeoLite2-Country.mmdb` is also accepted.
|
||||
5. For automated downloads, generate a MaxMind license key and configure `geoipupdate`. The license key authenticates database downloads; the plugin does not use it and does not call a MaxMind lookup API.
|
||||
6. Keep the database current. MaxMind requires GeoLite users to replace old data after new releases.
|
||||
|
||||
Rotating Ads includes MaxMind official pure-PHP reader, so no Composer command, PHP extension, API service, or reader-path setting is required. The bundled reader requires PHP 7.2 or newer. If a forum-root Composer installation already provides the reader, it is detected before the bundled copy. A paid GeoIP2 Country or City `.mmdb` file can be used the same way.
|
||||
|
||||
The plugin performs only local database reads and sends no visitor address to MaxMind. If the reader, autoloader, database, IP address, or lookup is unavailable, the lookup returns no country instead of interrupting the forum page. Use **Check MaxMind setup** beside the database-path setting, or open the **MaxMind status** tab under **Configuration -> Rotating Ads**, to verify the resolved filename, file readability, PHP reader, and database format.
|
||||
|
||||
### Visitor IP source options
|
||||
|
||||
This setting supplies the address used only for the optional local MaxMind lookup. It does not affect country codes supplied directly by a CDN, proxy, hosting platform, or server GeoIP module. Most administrators should keep `REMOTE_ADDR`.
|
||||
|
||||
| Option | When to use it |
|
||||
| --- | --- |
|
||||
| `REMOTE_ADDR (recommended)` | Use for a directly hosted forum and whenever you are unsure. It reads the address connected to the web server and cannot be replaced by a visitor-supplied HTTP header. Behind a proxy, it may identify the proxy instead of the visitor. |
|
||||
| `CF-Connecting-IP (Cloudflare only)` | Use when the origin accepts traffic through Cloudflare and Cloudflare overwrites this header with the visitor address. Restrict origin access to Cloudflare so visitors cannot bypass it and supply their own value. |
|
||||
| `X-Forwarded-For (trusted proxy only)` | Use only when a trusted reverse proxy or load balancer overwrites or sanitizes this header. The plugin uses the first valid address in its comma-separated list. Do not use it when visitors can connect directly to the origin and supply the header themselves. |
|
||||
| `X-Real-IP (trusted proxy only)` | Use when a trusted reverse proxy, commonly Nginx, deliberately overwrites this header with the visitor address. Do not select it merely because the header is present. |
|
||||
|
||||
Forwarded IP headers are not trustworthy by themselves. If a visitor can supply or preserve the selected header, they can influence country targeting. Keep `REMOTE_ADDR` unless the forum is behind a proxy you control or a trusted service whose connection to the origin is enforced.
|
||||
|
||||
## Output
|
||||
|
||||
|
||||
@@ -30,11 +30,26 @@ $l['rotating_ads_country_detection_maxmind'] = 'MaxMind database only';
|
||||
$l['rotating_ads_country_detection_language'] = 'Browser language region only';
|
||||
$l['rotating_ads_country_detection_disabled'] = 'Disabled';
|
||||
$l['rotating_ads_maxmind_database_path'] = 'MaxMind database path';
|
||||
$l['rotating_ads_maxmind_database_path_description'] = 'Absolute path to a readable GeoLite2 or GeoIP2 Country/City .mmdb file. Leave blank to skip local database lookups.';
|
||||
$l['rotating_ads_maxmind_autoload_path'] = 'MaxMind reader autoload path';
|
||||
$l['rotating_ads_maxmind_autoload_path_description'] = 'Optional absolute path to the MaxMind DB Reader autoload.php file. The forum root vendor/autoload.php is also detected automatically.';
|
||||
$l['rotating_ads_maxmind_database_path_description'] = 'Place GeoLite2-Country.mmdb in the MyBB inc/geoip directory, then enter /inc/geoip here. The path is relative to the board root and the filename is added automatically. <a href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/" target="_blank" rel="noopener noreferrer">Download GeoLite2 Country (.mmdb)</a>. Leave blank to disable local lookup. <a href="index.php?module=config-rotating_ads&action=maxmind_status">Check MaxMind setup</a>.';
|
||||
$l['rotating_ads_maxmind_status'] = 'MaxMind status';
|
||||
$l['rotating_ads_maxmind_status_description'] = 'Check the configured database path and PHP reader.';
|
||||
$l['rotating_ads_maxmind_configured_path'] = 'Configured path';
|
||||
$l['rotating_ads_maxmind_resolved_path'] = 'Resolved database file';
|
||||
$l['rotating_ads_maxmind_file_status'] = 'Database file';
|
||||
$l['rotating_ads_maxmind_reader_status'] = 'PHP reader';
|
||||
$l['rotating_ads_maxmind_database_status'] = 'Database validation';
|
||||
$l['rotating_ads_maxmind_not_tested'] = 'Not tested because the file or reader is unavailable.';
|
||||
$l['rotating_ads_maxmind_valid'] = 'Valid database';
|
||||
$l['rotating_ads_maxmind_invalid'] = 'The database could not be opened: {error}';
|
||||
$l['rotating_ads_setting'] = 'Check';
|
||||
$l['rotating_ads_status'] = 'Status';
|
||||
$l['rotating_ads_not_configured'] = 'Not configured';
|
||||
$l['rotating_ads_found_readable'] = 'Found and readable';
|
||||
$l['rotating_ads_missing_unreadable'] = 'Missing or not readable';
|
||||
$l['rotating_ads_available'] = 'Available';
|
||||
$l['rotating_ads_unavailable'] = 'Not available. The bundled reader requires PHP 7.2 or newer; otherwise verify the bundled files or configure an external autoloader.';
|
||||
$l['rotating_ads_visitor_ip_source'] = 'Visitor IP source';
|
||||
$l['rotating_ads_visitor_ip_source_description'] = 'Use REMOTE_ADDR unless the forum is behind a trusted proxy that overwrites the selected header.';
|
||||
$l['rotating_ads_visitor_ip_source_description'] = 'Used only for local MaxMind lookups. Most sites should keep REMOTE_ADDR. Select another source only when a trusted proxy overwrites that header; otherwise visitors may spoof their country.';
|
||||
$l['rotating_ads_manage_ads'] = 'Rotating Ads';
|
||||
$l['rotating_ads_manage_ads_description'] = 'Manage square and banner advertisements.';
|
||||
$l['rotating_ads_can_manage_ads'] = 'Can manage rotating ads?';
|
||||
|
||||
@@ -25,7 +25,7 @@ function rotating_ads_info()
|
||||
'website' => 'https://github.com/sickprodigy/mybb_rotating-ads_plugin',
|
||||
'author' => 'SickProdigy',
|
||||
'authorsite' => 'https://www.sickgaming.net',
|
||||
'version' => '1.0.3',
|
||||
'version' => '1.0.4',
|
||||
'compatibility' => '18*',
|
||||
'license' => 'GPL-3.0-only'
|
||||
);
|
||||
@@ -311,28 +311,19 @@ function rotating_ads_ensure_settings()
|
||||
array(
|
||||
'name' => 'rotating_ads_maxmind_database_path',
|
||||
'title' => rotating_ads_lang('rotating_ads_maxmind_database_path', 'MaxMind database path'),
|
||||
'description' => rotating_ads_lang('rotating_ads_maxmind_database_path_description', 'Absolute path to a readable GeoLite2 or GeoIP2 Country/City .mmdb file. Leave blank to skip local database lookups.'),
|
||||
'description' => rotating_ads_lang('rotating_ads_maxmind_database_path_description', 'Place GeoLite2-Country.mmdb in the MyBB inc/geoip directory, then enter /inc/geoip here. The path is relative to the board root and the filename is added automatically. <a href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/" target="_blank" rel="noopener noreferrer">Download GeoLite2 Country (.mmdb)</a>. Leave blank to disable local lookup. <a href="index.php?module=config-rotating_ads&action=maxmind_status">Check MaxMind setup</a>.'),
|
||||
'optionscode' => 'text',
|
||||
'value' => '',
|
||||
'disporder' => 11,
|
||||
'gid' => $gid
|
||||
),
|
||||
array(
|
||||
'name' => 'rotating_ads_maxmind_autoload_path',
|
||||
'title' => rotating_ads_lang('rotating_ads_maxmind_autoload_path', 'MaxMind reader autoload path'),
|
||||
'description' => rotating_ads_lang('rotating_ads_maxmind_autoload_path_description', 'Optional absolute path to the MaxMind DB Reader autoload.php file. The forum root vendor/autoload.php is also detected automatically.'),
|
||||
'optionscode' => 'text',
|
||||
'value' => '',
|
||||
'disporder' => 12,
|
||||
'gid' => $gid
|
||||
),
|
||||
array(
|
||||
'name' => 'rotating_ads_visitor_ip_source',
|
||||
'title' => rotating_ads_lang('rotating_ads_visitor_ip_source', 'Visitor IP source'),
|
||||
'description' => rotating_ads_lang('rotating_ads_visitor_ip_source_description', 'Use REMOTE_ADDR unless the forum is behind a trusted proxy that overwrites the selected header.'),
|
||||
'optionscode' => "select\nremote_addr=REMOTE_ADDR\ncf_connecting_ip=CF-Connecting-IP\nx_forwarded_for=X-Forwarded-For\nx_real_ip=X-Real-IP",
|
||||
'description' => rotating_ads_lang('rotating_ads_visitor_ip_source_description', 'Used only for local MaxMind lookups. Most sites should keep REMOTE_ADDR. Select another source only when a trusted proxy overwrites that header; otherwise visitors may spoof their country.'),
|
||||
'optionscode' => "select\nremote_addr=REMOTE_ADDR (recommended)\ncf_connecting_ip=CF-Connecting-IP (Cloudflare only)\nx_forwarded_for=X-Forwarded-For (trusted proxy only)\nx_real_ip=X-Real-IP (trusted proxy only)",
|
||||
'value' => 'remote_addr',
|
||||
'disporder' => 13,
|
||||
'disporder' => 12,
|
||||
'gid' => $gid
|
||||
)
|
||||
);
|
||||
@@ -349,6 +340,7 @@ function rotating_ads_ensure_settings()
|
||||
}
|
||||
}
|
||||
|
||||
$db->delete_query('settings', "name='rotating_ads_maxmind_autoload_path'");
|
||||
rotating_ads_rebuild_settings();
|
||||
}
|
||||
|
||||
@@ -526,7 +518,7 @@ function rotating_ads_export_bundle()
|
||||
|
||||
return array(
|
||||
'generator' => 'mybb_rotating_ads',
|
||||
'version' => '1.0.3',
|
||||
'version' => '1.0.4',
|
||||
'exported_at' => gmdate('c'),
|
||||
'ads' => $ads
|
||||
);
|
||||
@@ -775,12 +767,12 @@ function rotating_ads_load_maxmind_reader()
|
||||
}
|
||||
|
||||
$paths = array();
|
||||
if (isset($mybb->settings['rotating_ads_maxmind_autoload_path'])) {
|
||||
$paths[] = trim((string)$mybb->settings['rotating_ads_maxmind_autoload_path']);
|
||||
}
|
||||
if (defined('MYBB_ROOT')) {
|
||||
$paths[] = MYBB_ROOT . 'vendor/autoload.php';
|
||||
}
|
||||
if (PHP_VERSION_ID >= 70200) {
|
||||
$paths[] = __DIR__ . '/rotating_ads/maxmind-db-reader/autoload.php';
|
||||
}
|
||||
|
||||
foreach (array_unique($paths) as $path) {
|
||||
if ($path !== '' && is_file($path) && is_readable($path)) {
|
||||
@@ -794,8 +786,27 @@ function rotating_ads_load_maxmind_reader()
|
||||
return false;
|
||||
}
|
||||
|
||||
function rotating_ads_maxmind_database_path($path)
|
||||
{
|
||||
$path = trim((string)$path);
|
||||
if ($path === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!is_file($path) && strtolower(substr($path, -5)) !== '.mmdb') {
|
||||
$path = rtrim($path, '/') . '/GeoLite2-Country.mmdb';
|
||||
}
|
||||
|
||||
if (defined('MYBB_ROOT') && ($path === '/inc' || strpos($path, '/inc/') === 0)) {
|
||||
$path = MYBB_ROOT . ltrim($path, '/');
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
function rotating_ads_maxmind_country_code($ip, $database_path, $reader_factory = null)
|
||||
{
|
||||
$database_path = rotating_ads_maxmind_database_path($database_path);
|
||||
if (filter_var($ip, FILTER_VALIDATE_IP) === false
|
||||
|| $database_path === ''
|
||||
|| !is_file($database_path)
|
||||
@@ -1244,6 +1255,11 @@ function rotating_ads_admin_page()
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($action === 'maxmind_status') {
|
||||
rotating_ads_admin_maxmind_status_page();
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
$query = $db->simple_select('rotating_ads', 'aid, alt_text', "aid='{$aid}'", array('limit' => 1));
|
||||
$ad = $db->fetch_array($query);
|
||||
@@ -1339,10 +1355,74 @@ function rotating_ads_admin_tabs()
|
||||
'title' => rotating_ads_lang('rotating_ads_backup_restore', 'Backup & restore'),
|
||||
'link' => 'index.php?module=config-rotating_ads&action=backup',
|
||||
'description' => rotating_ads_lang('rotating_ads_backup_restore_description', 'Export or import all ads as a JSON backup.')
|
||||
),
|
||||
'rotating_ads_maxmind_status' => array(
|
||||
'title' => rotating_ads_lang('rotating_ads_maxmind_status', 'MaxMind status'),
|
||||
'link' => 'index.php?module=config-rotating_ads&action=maxmind_status',
|
||||
'description' => rotating_ads_lang('rotating_ads_maxmind_status_description', 'Check the configured database path and PHP reader.')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function rotating_ads_admin_maxmind_status_page()
|
||||
{
|
||||
global $mybb, $page;
|
||||
|
||||
$configured_path = isset($mybb->settings['rotating_ads_maxmind_database_path'])
|
||||
? trim((string)$mybb->settings['rotating_ads_maxmind_database_path'])
|
||||
: '';
|
||||
$resolved_path = rotating_ads_maxmind_database_path($configured_path);
|
||||
$file_ready = $resolved_path !== '' && is_file($resolved_path) && is_readable($resolved_path);
|
||||
$reader_ready = rotating_ads_load_maxmind_reader();
|
||||
$database_detail = rotating_ads_lang('rotating_ads_maxmind_not_tested', 'Not tested because the file or reader is unavailable.');
|
||||
|
||||
if ($file_ready && $reader_ready) {
|
||||
$reader = null;
|
||||
try {
|
||||
$reader = new \MaxMind\Db\Reader($resolved_path);
|
||||
$metadata = $reader->metadata();
|
||||
$database_type = isset($metadata->databaseType) ? (string)$metadata->databaseType : '';
|
||||
$database_detail = rotating_ads_lang('rotating_ads_maxmind_valid', 'Valid database');
|
||||
if ($database_type !== '') {
|
||||
$database_detail .= ': ' . $database_type;
|
||||
}
|
||||
} catch (Exception $exception) {
|
||||
$database_detail = rotating_ads_lang('rotating_ads_maxmind_invalid', 'The database could not be opened: {error}', array(
|
||||
'{error}' => $exception->getMessage()
|
||||
));
|
||||
}
|
||||
if (is_object($reader) && method_exists($reader, 'close')) {
|
||||
$reader->close();
|
||||
}
|
||||
}
|
||||
|
||||
$page->add_breadcrumb_item(rotating_ads_lang('rotating_ads_manage_ads', 'Rotating Ads'), 'index.php?module=config-rotating_ads');
|
||||
$page->add_breadcrumb_item(rotating_ads_lang('rotating_ads_maxmind_status', 'MaxMind status'));
|
||||
$page->output_header(rotating_ads_lang('rotating_ads_maxmind_status', 'MaxMind status'));
|
||||
$page->output_nav_tabs(rotating_ads_admin_tabs(), 'rotating_ads_maxmind_status');
|
||||
|
||||
$table = new Table;
|
||||
$table->construct_header(rotating_ads_lang('rotating_ads_setting', 'Check'), array('width' => '30%'));
|
||||
$table->construct_header(rotating_ads_lang('rotating_ads_status', 'Status'));
|
||||
$table->construct_cell(rotating_ads_lang('rotating_ads_maxmind_configured_path', 'Configured path'));
|
||||
$table->construct_cell($configured_path === '' ? rotating_ads_lang('rotating_ads_not_configured', 'Not configured') : htmlspecialchars_uni($configured_path));
|
||||
$table->construct_row();
|
||||
$table->construct_cell(rotating_ads_lang('rotating_ads_maxmind_resolved_path', 'Resolved database file'));
|
||||
$table->construct_cell($resolved_path === '' ? rotating_ads_lang('rotating_ads_not_configured', 'Not configured') : htmlspecialchars_uni($resolved_path));
|
||||
$table->construct_row();
|
||||
$table->construct_cell(rotating_ads_lang('rotating_ads_maxmind_file_status', 'Database file'));
|
||||
$table->construct_cell($file_ready ? rotating_ads_lang('rotating_ads_found_readable', 'Found and readable') : rotating_ads_lang('rotating_ads_missing_unreadable', 'Missing or not readable'));
|
||||
$table->construct_row();
|
||||
$table->construct_cell(rotating_ads_lang('rotating_ads_maxmind_reader_status', 'PHP reader'));
|
||||
$table->construct_cell($reader_ready ? rotating_ads_lang('rotating_ads_available', 'Available') : rotating_ads_lang('rotating_ads_unavailable', 'Not available. The bundled reader requires PHP 7.2 or newer; otherwise verify the bundled files or configure an external autoloader.'));
|
||||
$table->construct_row();
|
||||
$table->construct_cell(rotating_ads_lang('rotating_ads_maxmind_database_status', 'Database validation'));
|
||||
$table->construct_cell(htmlspecialchars_uni($database_detail));
|
||||
$table->construct_row();
|
||||
$table->output(rotating_ads_lang('rotating_ads_maxmind_status', 'MaxMind status'));
|
||||
$page->output_footer();
|
||||
}
|
||||
|
||||
function rotating_ads_admin_backup_page()
|
||||
{
|
||||
global $mybb, $page;
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
1.14.0 (2026-09-10)
|
||||
-------------------
|
||||
|
||||
* Bounded the resources that the pure PHP decoder spends on a single lookup. A
|
||||
crafted database could nest data-section pointers to shared targets so that
|
||||
decoding one record cost exponential time and memory, or point many times at
|
||||
one large value so that the decoder copied far more data than the file holds.
|
||||
The decoder now follows the Reader Resource Limits section of the MaxMind DB
|
||||
specification. Each lookup is limited to 65,536 values, 512 levels of
|
||||
nesting, and 2 MiB of string and bytes payload.
|
||||
* Exceeding a limit throws an `InvalidDatabaseException`.
|
||||
* Opening a database whose metadata exceeds a limit throws the same
|
||||
exception.
|
||||
* A scalar that declares more than 16 bytes, the width of the widest
|
||||
fixed-width type, is rejected as invalid data.
|
||||
* The bundled libmaxminddb used by `--with-maxminddb-bundled` builds of the
|
||||
extension now applies the same decoder limits. The extension throws an
|
||||
`InvalidDatabaseException` when a lookup exceeds them.
|
||||
* The pure PHP reader is about 40% faster on City lookups. It no longer seeks
|
||||
before a read that continues where the last one ended, and it checks read
|
||||
lengths with `strlen()` instead of `ftell()`.
|
||||
* The Windows build configuration now accepts either `libmaxminddb.lib` or
|
||||
`maxminddb.lib` when building the extension. The `lib` prefix was removed
|
||||
in libmaxminddb 1.6.0, but the libmaxminddb that PHP publishes for Windows
|
||||
builds is still 1.5.0, which uses the prefixed name. Pull request by
|
||||
Jean-Baptiste Nahan. GitHub #231.
|
||||
* Replaced `XtOffsetOf()` with `offsetof()`. The `XtOffsetOf()` alias has
|
||||
been removed in PHP 8.6. Pull request by Remi Collet. GitHub #252.
|
||||
* The extension can now be built from a bundled copy of libmaxminddb, on
|
||||
both Unix-like systems and Windows, by passing `--with-maxminddb-bundled`
|
||||
to `configure` (or to `configure.bat` on Windows). This produces an
|
||||
extension that does not depend on a system libmaxminddb, which is a
|
||||
prerequisite for distributing precompiled builds; on Windows it also
|
||||
replaces the 1.5.0 import library that PHP publishes for Windows builds.
|
||||
The default is unchanged: without the flag, the extension links against a
|
||||
system libmaxminddb as before. GitHub #265.
|
||||
* The `conflict` constraint on `ext-maxminddb` in `composer.json` is again
|
||||
updated when a release is cut. The substitution that maintains it stopped
|
||||
matching in April 2024, when the constraint's separator changed from a comma
|
||||
to `||`, so the constraint has read `<1.11.1` through four releases. Users of
|
||||
the C extension should note the effect of reviving it: `ext-maxminddb` is a
|
||||
Composer platform package, so this release conflicts with an older compiled
|
||||
extension and `composer update` will require upgrading the two together.
|
||||
GitHub #266.
|
||||
|
||||
1.13.1 (2025-11-21)
|
||||
-------------------
|
||||
|
||||
* First PIE release. No other changes.
|
||||
|
||||
1.13.0 (2025-11-20)
|
||||
-------------------
|
||||
|
||||
* A redundant `filesize()` call in the reader's constructor was removed.
|
||||
Pull request by Pavel Djundik. GitHub #189.
|
||||
|
||||
1.12.1 (2025-05-05)
|
||||
-------------------
|
||||
|
||||
* The C extension now checks that the database metadata lookup was
|
||||
successful.
|
||||
|
||||
1.12.0 (2024-11-14)
|
||||
-------------------
|
||||
|
||||
* Improve the error handling when the user tries to open a directory
|
||||
with the pure PHP reader.
|
||||
* Improve the typehints on arrays in the PHPDocs.
|
||||
|
||||
1.11.1 (2023-12-01)
|
||||
-------------------
|
||||
|
||||
* Resolve warnings when compiling the C extension.
|
||||
* Fix various type issues detected by PHPStan level. Pull request by
|
||||
LauraTaylorUK. GitHub #160.
|
||||
|
||||
1.11.0 (2021-10-18)
|
||||
-------------------
|
||||
|
||||
* Replace runtime define of a constant to facilitate opcache preloading.
|
||||
Reported by vedadkajtaz. GitHub #134.
|
||||
* Resolve minor issue found by the Clang static analyzer in the C
|
||||
extension.
|
||||
|
||||
1.10.1 (2021-04-14)
|
||||
-------------------
|
||||
|
||||
* Fix a `TypeError` exception in the pure PHP reader when using large
|
||||
databases on 32-bit PHP builds with the `bcmath` extension. Reported
|
||||
by dodo1708. GitHub #124.
|
||||
|
||||
1.10.0 (2021-02-09)
|
||||
-------------------
|
||||
|
||||
* When using the pure PHP reader, unsigned integers up to PHP_MAX_INT
|
||||
will now be integers in PHP rather than strings. Previously integers
|
||||
greater than 2^24 on 32-bit platforms and 2^56 on 64-bit platforms
|
||||
would be strings due to the use of `gmp` or `bcmath` to decode them.
|
||||
Reported by Alejandro Celaya. GitHub #119.
|
||||
|
||||
1.9.0 (2021-01-07)
|
||||
------------------
|
||||
|
||||
* The `maxminddb` extension is now buildable on Windows. Pull request
|
||||
by Jan Ehrhardt. GitHub #115.
|
||||
|
||||
1.8.0 (2020-10-01)
|
||||
------------------
|
||||
|
||||
* Fixes for PHP 8.0. Pull Request by Remi Collet. GitHub #108.
|
||||
|
||||
1.7.0 (2020-08-07)
|
||||
------------------
|
||||
|
||||
* IMPORTANT: PHP 7.2 or greater is now required.
|
||||
* The extension no longer depends on the pure PHP classes in
|
||||
`maxmind-db/reader`. You can use it independently.
|
||||
* Type hints have been added to both the pure PHP implementation
|
||||
and the extension.
|
||||
* The `metadata` method on the reader now returns a new copy of the
|
||||
metadata object rather than the actual object used by the reader.
|
||||
* Work around PHP `is_readable()` bug. Reported by Ben Roberts. GitHub
|
||||
#92.
|
||||
* This is the first release of the extension as a PECL package.
|
||||
GitHub #34.
|
||||
|
||||
1.6.0 (2019-12-19)
|
||||
------------------
|
||||
|
||||
* 1.5.0 and 1.5.1 contained a possible memory corruptions when using
|
||||
`getWithPrefixLen`. This has been fixed. Reported by proton-ab.
|
||||
GitHub #96.
|
||||
* The `composer.json` file now conflicts with all versions of the
|
||||
`maxminddb` C extension less than the Composer version. This is to
|
||||
reduce the chance of having an older, conflicting version of the
|
||||
extension installed. You will need to upgrade the extension before
|
||||
running `composer update`. Pull request by Benoît Burnichon. GitHub
|
||||
#97.
|
||||
|
||||
1.5.1 (2019-12-12)
|
||||
------------------
|
||||
|
||||
* Minor performance improvements.
|
||||
* Make tests pass with older versions of libmaxminddb. PR by Remi
|
||||
Collet. GitHub #90.
|
||||
* Test enhancements. PR by Chun-Sheng, Li. GitHub #91.
|
||||
|
||||
1.5.0 (2019-09-30)
|
||||
------------------
|
||||
|
||||
* PHP 5.6 or greater is now required.
|
||||
* The C extension now supports PHP 8. Pull request by John Boehr.
|
||||
GitHub #87.
|
||||
* A new method, `getWithPrefixLen`, was added to the `Reader` class.
|
||||
This method returns an array containing the record and the prefix
|
||||
length for that record. GitHub #89.
|
||||
|
||||
1.4.1 (2019-01-04)
|
||||
------------------
|
||||
|
||||
* The `maxminddb` extension now returns a string when a `uint32`
|
||||
value is greater than `LONG_MAX`. Previously, the value would
|
||||
overflow. This generally only affects 32-bit machines. Reported
|
||||
by Remi Collet. GitHub #79.
|
||||
* For `uint64` values, the `maxminddb` extension now returns an
|
||||
integer rather than a string when the value is less than or equal
|
||||
to `LONG_MAX`. This more closely matches the behavior of the pure
|
||||
PHP reader.
|
||||
|
||||
1.4.0 (2018-11-20)
|
||||
------------------
|
||||
|
||||
* The `maxminddb` extension now has the arginfo when using reflection.
|
||||
PR by Remi Collet. GitHub #75.
|
||||
* The `maxminddb` extension now provides `MINFO()` function that
|
||||
displays the extension version and the libmaxminddb version. PR by
|
||||
Remi Collet. GitHub #74.
|
||||
* The `maxminddb` `configure` script now uses `pkg-config` when
|
||||
available to get libmaxmindb build info. PR by Remi Collet.
|
||||
GitHub #73.
|
||||
* The pure PHP reader now correctly decodes integers on 32-bit platforms.
|
||||
Previously, large integers would overflow. Reported by Remi Collet.
|
||||
GitHub #77.
|
||||
* There are small performance improvements for the pure PHP reader.
|
||||
|
||||
1.3.0 (2018-02-21)
|
||||
------------------
|
||||
|
||||
* IMPORTANT: The `maxminddb` extension now obeys `open_basedir`. If
|
||||
`open_basedir` is set, you _must_ store the database within the
|
||||
specified directory. Placing the file outside of this directory
|
||||
will result in an exception. Please test your integration before
|
||||
upgrading the extension. This does not affect the pure PHP
|
||||
implementation, which has always had this restriction. Reported
|
||||
by Benoît Burnichon. GitHub #61.
|
||||
* A custom `autoload.php` file is provided for installations without
|
||||
Composer. GitHub #56.
|
||||
|
||||
1.2.0 (2017-10-27)
|
||||
------------------
|
||||
|
||||
* PHP 5.4 or greater is now required.
|
||||
* The `Reader` class for the `maxminddb` extension is no longer final.
|
||||
This was change to match the behavior of the pure PHP class.
|
||||
Reported and fixed by venyii. GitHub #52 & #54.
|
||||
|
||||
1.1.3 (2017-01-19)
|
||||
------------------
|
||||
|
||||
* Fix incorrect version in `ext/php_maxminddb.h`. GitHub #48.
|
||||
|
||||
1.1.2 (2016-11-22)
|
||||
------------------
|
||||
|
||||
* Searching for database metadata only occurs within the last 128KB
|
||||
(128 * 1024 bytes) of the file, speeding detection of corrupt
|
||||
datafiles. Reported by Eric Teubert. GitHub #42.
|
||||
* Suggest relevant extensions when installing with Composer. GitHub #37.
|
||||
|
||||
1.1.1 (2016-09-15)
|
||||
------------------
|
||||
|
||||
* Development files were added to the `.gitattributes` as `export-ignore` so
|
||||
that they are not part of the Composer release. Pull request by Michele
|
||||
Locati. GitHub #39.
|
||||
|
||||
1.1.0 (2016-01-04)
|
||||
------------------
|
||||
|
||||
* The MaxMind DB extension now supports PHP 7. Pull request by John Boehr.
|
||||
GitHub #27.
|
||||
|
||||
1.0.3 (2015-03-13)
|
||||
------------------
|
||||
|
||||
* All uses of `strlen` were removed. This should prevent issues in situations
|
||||
where the function is overloaded or otherwise broken.
|
||||
|
||||
1.0.2 (2015-01-19)
|
||||
------------------
|
||||
|
||||
* Previously the MaxMind DB extension would cause a segfault if the Reader
|
||||
object's destructor was called without first having called the constructor.
|
||||
(Reported by Matthias Saou & Juan Peri. GitHub #20.)
|
||||
|
||||
1.0.1 (2015-01-12)
|
||||
------------------
|
||||
|
||||
* In the last several releases, the version number in the extension was
|
||||
incorrect. This release is being done to correct it. No other code changes
|
||||
are included.
|
||||
|
||||
1.0.0 (2014-09-22)
|
||||
------------------
|
||||
|
||||
* First production release.
|
||||
* In the pure PHP reader, a string length test after `fread()` was replaced
|
||||
with the difference between the start pointer and the end pointer. This
|
||||
provided a 15% speed increase.
|
||||
|
||||
0.3.3 (2014-09-15)
|
||||
------------------
|
||||
|
||||
* Clarified behavior of 128-bit type in documentation.
|
||||
* Updated phpunit and fixed some test breakage from the newer version.
|
||||
|
||||
0.3.2 (2014-09-10)
|
||||
------------------
|
||||
|
||||
* Fixed invalid reference to global class RuntimeException from namespaced
|
||||
code. Fixed by Steven Don. GitHub issue #15.
|
||||
* Additional documentation of `Metadata` class as well as misc. documentation
|
||||
cleanup.
|
||||
|
||||
0.3.1 (2014-05-01)
|
||||
------------------
|
||||
|
||||
* The API now works when `mbstring.func_overload` is set.
|
||||
* BCMath is no longer required. If the decoder encounters a big integer,
|
||||
it will try to use GMP and then BCMath. If both of those fail, it will
|
||||
throw an exception. No databases released by MaxMind currently use big
|
||||
integers.
|
||||
* The API now officially supports HHVM when using the pure PHP reader.
|
||||
|
||||
0.3.0 (2014-02-19)
|
||||
------------------
|
||||
|
||||
* This API is now licensed under the Apache License, Version 2.0.
|
||||
* The code for the C extension was cleaned up, fixing several potential
|
||||
issues.
|
||||
|
||||
0.2.0 (2013-10-21)
|
||||
------------------
|
||||
|
||||
* Added optional C extension for using libmaxminddb in place of the pure PHP
|
||||
reader.
|
||||
* Significantly improved error handling in pure PHP reader.
|
||||
* Improved performance for IPv4 lookups in an IPv6 database.
|
||||
|
||||
0.1.0 (2013-07-16)
|
||||
------------------
|
||||
|
||||
* Initial release
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,235 @@
|
||||
# MaxMind DB Reader PHP API #
|
||||
|
||||
## Description ##
|
||||
|
||||
This is the PHP API for reading MaxMind DB files. MaxMind DB is a binary file
|
||||
format that stores data indexed by IP address subnets (IPv4 or IPv6).
|
||||
|
||||
## Installation ##
|
||||
|
||||
### C Extension (Recommended for Performance) ###
|
||||
|
||||
For significantly faster IP lookups, we recommend installing the C extension via
|
||||
[PIE](https://github.com/php/pie):
|
||||
|
||||
```bash
|
||||
pie install maxmind-db/reader-ext
|
||||
```
|
||||
|
||||
The C extension requires the [libmaxminddb](https://github.com/maxmind/libmaxminddb)
|
||||
C library. See the [installation instructions](https://github.com/maxmind/MaxMind-DB-Reader-php-ext#prerequisites)
|
||||
for your platform.
|
||||
|
||||
### Pure PHP (No Compilation Required) ###
|
||||
|
||||
If you prefer not to compile a C extension or need maximum portability, you can
|
||||
install the pure PHP implementation with [Composer](https://getcomposer.org/).
|
||||
|
||||
### Download Composer ###
|
||||
|
||||
To download Composer, run in the root directory of your project:
|
||||
|
||||
```bash
|
||||
curl -sS https://getcomposer.org/installer | php
|
||||
```
|
||||
|
||||
You should now have the file `composer.phar` in your project directory.
|
||||
|
||||
### Install Dependencies ###
|
||||
|
||||
Run in your project root:
|
||||
|
||||
```
|
||||
php composer.phar require maxmind-db/reader:^1.14.0
|
||||
```
|
||||
|
||||
You should now have the files `composer.json` and `composer.lock` as well as
|
||||
the directory `vendor` in your project directory. If you use a version control
|
||||
system, `composer.json` should be added to it.
|
||||
|
||||
### Require Autoloader ###
|
||||
|
||||
After installing the dependencies, you need to require the Composer autoloader
|
||||
from your code:
|
||||
|
||||
```php
|
||||
require 'vendor/autoload.php';
|
||||
```
|
||||
|
||||
## Installation (Standalone) ##
|
||||
|
||||
If you don't want to use Composer for some reason, a custom
|
||||
`autoload.php` is provided for you in the project root. To use the
|
||||
library, simply include that file,
|
||||
|
||||
```php
|
||||
require('/path/to/MaxMind-DB-Reader-php/autoload.php');
|
||||
```
|
||||
|
||||
and then instantiate the reader class normally:
|
||||
|
||||
```php
|
||||
use MaxMind\Db\Reader;
|
||||
$reader = new Reader('example.mmdb');
|
||||
```
|
||||
|
||||
## Installation (RPM)
|
||||
|
||||
RPMs are available in the [official Fedora repository](https://packages.fedoraproject.org/pkgs/php-maxminddb/php-maxminddb/).
|
||||
|
||||
To install on Fedora, run:
|
||||
|
||||
```bash
|
||||
dnf install php-maxminddb
|
||||
```
|
||||
|
||||
To install on CentOS or RHEL 7, first [enable the EPEL repository](https://docs.fedoraproject.org/en-US/epel/)
|
||||
and then run:
|
||||
|
||||
```bash
|
||||
yum install php-maxminddb
|
||||
```
|
||||
|
||||
Please note that these packages are *not* maintained by MaxMind.
|
||||
|
||||
## Usage ##
|
||||
|
||||
## Example ##
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once 'vendor/autoload.php';
|
||||
|
||||
use MaxMind\Db\Reader;
|
||||
|
||||
$ipAddress = '24.24.24.24';
|
||||
$databaseFile = 'GeoIP2-City.mmdb';
|
||||
|
||||
$reader = new Reader($databaseFile);
|
||||
|
||||
// get returns just the record for the IP address
|
||||
print_r($reader->get($ipAddress));
|
||||
|
||||
// getWithPrefixLen returns an array containing the record and the
|
||||
// associated prefix length for that record.
|
||||
print_r($reader->getWithPrefixLen($ipAddress));
|
||||
|
||||
$reader->close();
|
||||
```
|
||||
|
||||
## Optional PHP C Extension ##
|
||||
|
||||
MaxMind provides an optional C extension that is a drop-in replacement for
|
||||
`MaxMind\Db\Reader`. In order to use this extension, you must install the
|
||||
Reader API as described above and install the extension as described below. If
|
||||
you are using an autoloader, no changes to your code should be necessary.
|
||||
|
||||
### Installing Extension via PIE (Recommended) ###
|
||||
|
||||
We recommend installing the extension via [PIE](https://github.com/php/pie):
|
||||
|
||||
```bash
|
||||
pie install maxmind-db/reader-ext
|
||||
```
|
||||
|
||||
See the [extension repository](https://github.com/maxmind/MaxMind-DB-Reader-php-ext#prerequisites)
|
||||
for prerequisites including libmaxminddb installation instructions.
|
||||
|
||||
### Installing Extension via PECL (Legacy) ###
|
||||
|
||||
First install [libmaxminddb](https://github.com/maxmind/libmaxminddb) as
|
||||
described in its [README.md
|
||||
file](https://github.com/maxmind/libmaxminddb/blob/main/README.md#from-a-named-release-tarball).
|
||||
After successfully installing libmaxmindb, you may install the extension
|
||||
from [PECL](https://pecl.php.net/package/maxminddb):
|
||||
|
||||
```
|
||||
pecl install maxminddb
|
||||
```
|
||||
|
||||
### Installing Extension from Source ###
|
||||
|
||||
Alternatively, you may install it from the source. This links against the
|
||||
libmaxminddb installed on your system, so install that first as described
|
||||
above. Run the following commands from the top-level directory of this
|
||||
distribution:
|
||||
|
||||
```
|
||||
cd ext
|
||||
phpize
|
||||
./configure --with-maxminddb
|
||||
make
|
||||
make test
|
||||
sudo make install
|
||||
```
|
||||
|
||||
#### Building without a system libmaxminddb ####
|
||||
|
||||
Passing `--with-maxminddb-bundled` compiles a bundled copy of libmaxminddb
|
||||
into the extension instead, so the result depends on nothing but the C
|
||||
runtime. This is what the precompiled builds use. The bundled sources are a
|
||||
git submodule, so they have to be checked out first:
|
||||
|
||||
```
|
||||
git submodule update --init
|
||||
cd ext
|
||||
phpize
|
||||
./configure --with-maxminddb --with-maxminddb-bundled
|
||||
make
|
||||
make test
|
||||
sudo make install
|
||||
```
|
||||
|
||||
The same flag works on Windows, passed to `configure.bat`.
|
||||
|
||||
You then must load your extension. The recommended method is to add the
|
||||
following to your `php.ini` file:
|
||||
|
||||
```
|
||||
extension=maxminddb.so
|
||||
```
|
||||
|
||||
Note: You may need to install the PHP development package on your OS such as
|
||||
php5-dev for Debian-based systems or php-devel for RedHat/Fedora-based ones.
|
||||
|
||||
## 128-bit Integer Support ##
|
||||
|
||||
The MaxMind DB format includes 128-bit unsigned integer as a type. Although
|
||||
no MaxMind-distributed database currently makes use of this type, both the
|
||||
pure PHP reader and the C extension support this type. The pure PHP reader
|
||||
requires gmp or bcmath to read databases with 128-bit unsigned integers.
|
||||
|
||||
The integer is currently returned as a hexadecimal string (prefixed with "0x")
|
||||
by the C extension and a decimal string (no prefix) by the pure PHP reader.
|
||||
Any change to make the reader implementations always return either a
|
||||
hexadecimal or decimal representation of the integer will NOT be considered a
|
||||
breaking change.
|
||||
|
||||
## Support ##
|
||||
|
||||
Please report all issues with this code using the [GitHub issue tracker](https://github.com/maxmind/MaxMind-DB-Reader-php/issues).
|
||||
|
||||
If you are having an issue with a MaxMind service that is not specific to the
|
||||
client API, please see [our support page](https://support.maxmind.com/knowledge-base).
|
||||
|
||||
## Requirements ##
|
||||
|
||||
This library requires PHP 7.2 or greater.
|
||||
|
||||
The GMP or BCMath extension may be required to read some databases
|
||||
using the pure PHP API.
|
||||
|
||||
## Contributing ##
|
||||
|
||||
Patches and pull requests are encouraged. All code should follow the PSR-1 and
|
||||
PSR-2 style guidelines. Please include unit tests whenever possible.
|
||||
|
||||
## Versioning ##
|
||||
|
||||
The MaxMind DB Reader PHP API uses [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## Copyright and License ##
|
||||
|
||||
This software is Copyright (c) 2014-2026 by MaxMind, Inc.
|
||||
|
||||
This is free software, licensed under the Apache License, Version 2.0.
|
||||
@@ -0,0 +1,10 @@
|
||||
# MaxMind DB Reader PHP
|
||||
|
||||
This directory contains the standalone pure-PHP runtime from
|
||||
`maxmind-db/reader` version 1.14.0, distributed by MaxMind, Inc.
|
||||
|
||||
Source: https://github.com/maxmind/MaxMind-DB-Reader-php/tree/v1.14.0
|
||||
|
||||
The bundled files remain licensed under the Apache License 2.0. See
|
||||
`LICENSE` in this directory. The upstream README and changelog are included
|
||||
without modification.
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* PSR-4 autoloader implementation for the MaxMind\DB namespace.
|
||||
* First we define the 'mmdb_autoload' function, and then we register
|
||||
* it with 'spl_autoload_register' so that PHP knows to use it.
|
||||
*
|
||||
* @param mixed $class
|
||||
*/
|
||||
|
||||
/**
|
||||
* Automatically include the file that defines <code>class</code>.
|
||||
*
|
||||
* @param string $class
|
||||
* the name of the class to load
|
||||
*/
|
||||
function mmdb_autoload($class): void
|
||||
{
|
||||
/*
|
||||
* A project-specific mapping between the namespaces and where
|
||||
* they're located. By convention, we include the trailing
|
||||
* slashes. The one-element array here simply makes things easy
|
||||
* to extend in the future if (for example) the test classes
|
||||
* begin to use one another.
|
||||
*/
|
||||
$namespace_map = ['MaxMind\Db\\' => __DIR__ . '/src/MaxMind/Db/'];
|
||||
|
||||
foreach ($namespace_map as $prefix => $dir) {
|
||||
// First swap out the namespace prefix with a directory...
|
||||
$path = str_replace($prefix, $dir, $class);
|
||||
|
||||
// replace the namespace separator with a directory separator...
|
||||
$path = str_replace('\\', '/', $path);
|
||||
|
||||
// and finally, add the PHP file extension to the result.
|
||||
$path .= '.php';
|
||||
|
||||
// $path should now contain the path to a PHP file defining $class
|
||||
if (file_exists($path)) {
|
||||
include $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
spl_autoload_register('mmdb_autoload');
|
||||
@@ -0,0 +1,422 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MaxMind\Db;
|
||||
|
||||
use MaxMind\Db\Reader\Decoder;
|
||||
use MaxMind\Db\Reader\InvalidDatabaseException;
|
||||
use MaxMind\Db\Reader\Metadata;
|
||||
use MaxMind\Db\Reader\Util;
|
||||
|
||||
/**
|
||||
* Instances of this class provide a reader for the MaxMind DB format. IP
|
||||
* addresses can be looked up using the get method.
|
||||
*/
|
||||
class Reader
|
||||
{
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private static $DATA_SECTION_SEPARATOR_SIZE = 16;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private static $METADATA_START_MARKER = "\xAB\xCD\xEFMaxMind.com";
|
||||
|
||||
/**
|
||||
* @var int<0, max>
|
||||
*/
|
||||
private static $METADATA_START_MARKER_LENGTH = 14;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private static $METADATA_MAX_SIZE = 131072; // 128 * 1024 = 128KiB
|
||||
|
||||
/**
|
||||
* @var Decoder
|
||||
*/
|
||||
private $decoder;
|
||||
|
||||
/**
|
||||
* @var resource
|
||||
*/
|
||||
private $fileHandle;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $lookupInProgress = false;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $fileSize;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $ipV4Start;
|
||||
|
||||
/**
|
||||
* @var Metadata
|
||||
*/
|
||||
private $metadata;
|
||||
|
||||
/**
|
||||
* Constructs a Reader for the MaxMind DB format. The file passed to it must
|
||||
* be a valid MaxMind DB file such as a GeoIP database file.
|
||||
*
|
||||
* @param string $database the MaxMind DB file to use
|
||||
*
|
||||
* @throws \InvalidArgumentException for invalid database path or unknown arguments
|
||||
* @throws InvalidDatabaseException
|
||||
* if the database is invalid or there is an error reading
|
||||
* from it
|
||||
*/
|
||||
public function __construct(string $database)
|
||||
{
|
||||
if (\func_num_args() !== 1) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
|
||||
if (is_dir($database)) {
|
||||
// This matches the error that the C extension throws.
|
||||
throw new InvalidDatabaseException(
|
||||
"Error opening database file ($database). Is this a valid MaxMind DB file?"
|
||||
);
|
||||
}
|
||||
|
||||
$fileHandle = @fopen($database, 'rb');
|
||||
if ($fileHandle === false) {
|
||||
throw new \InvalidArgumentException(
|
||||
"The file \"$database\" does not exist or is not readable."
|
||||
);
|
||||
}
|
||||
$this->fileHandle = $fileHandle;
|
||||
|
||||
$fstat = fstat($fileHandle);
|
||||
if ($fstat === false) {
|
||||
throw new \UnexpectedValueException(
|
||||
"Error determining the size of \"$database\"."
|
||||
);
|
||||
}
|
||||
$this->fileSize = $fstat['size'];
|
||||
|
||||
$start = $this->findMetadataStart($database);
|
||||
$metadataDecoder = new Decoder($this->fileHandle, $start);
|
||||
[$metadataArray] = $metadataDecoder->decode($start);
|
||||
$this->metadata = new Metadata($metadataArray);
|
||||
$this->decoder = new Decoder(
|
||||
$this->fileHandle,
|
||||
$this->metadata->searchTreeSize + self::$DATA_SECTION_SEPARATOR_SIZE
|
||||
);
|
||||
$this->ipV4Start = $this->ipV4StartNode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the record for the IP address.
|
||||
*
|
||||
* @param string $ipAddress the IP address to look up
|
||||
*
|
||||
* @throws \BadMethodCallException if the database is closed or another lookup is in progress
|
||||
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
|
||||
* @throws InvalidDatabaseException
|
||||
* if the database is invalid or there is an error reading
|
||||
* from it
|
||||
*
|
||||
* @return mixed the record for the IP address
|
||||
*/
|
||||
public function get(string $ipAddress)
|
||||
{
|
||||
if (\func_num_args() !== 1) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
[$record] = $this->getWithPrefixLen($ipAddress);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the record for the IP address and its associated network prefix length.
|
||||
*
|
||||
* @param string $ipAddress the IP address to look up
|
||||
*
|
||||
* @throws \BadMethodCallException if the database is closed or another lookup is in progress
|
||||
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
|
||||
* @throws InvalidDatabaseException
|
||||
* if the database is invalid or there is an error reading
|
||||
* from it
|
||||
*
|
||||
* @return array{0:mixed, 1:int} an array where the first element is the record and the
|
||||
* second the network prefix length for the record
|
||||
*/
|
||||
public function getWithPrefixLen(string $ipAddress): array
|
||||
{
|
||||
if (\func_num_args() !== 1) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
|
||||
if (!\is_resource($this->fileHandle)) {
|
||||
throw new \BadMethodCallException(
|
||||
'Attempt to read from a closed MaxMind DB.'
|
||||
);
|
||||
}
|
||||
|
||||
if ($this->lookupInProgress) {
|
||||
throw new \BadMethodCallException(
|
||||
'A lookup is already in progress on this reader. Use a separate reader for nested lookups.'
|
||||
);
|
||||
}
|
||||
// A stream wrapper can call back into this reader during a read.
|
||||
// Reject nested lookups before they can move the shared stream.
|
||||
$this->lookupInProgress = true;
|
||||
|
||||
try {
|
||||
[$pointer, $prefixLen] = $this->findAddressInTree($ipAddress);
|
||||
if ($pointer === 0) {
|
||||
return [null, $prefixLen];
|
||||
}
|
||||
|
||||
return [$this->resolveDataPointer($pointer), $prefixLen];
|
||||
} finally {
|
||||
$this->lookupInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:int, 1:int}
|
||||
*/
|
||||
private function findAddressInTree(string $ipAddress): array
|
||||
{
|
||||
$packedAddr = @inet_pton($ipAddress);
|
||||
if ($packedAddr === false) {
|
||||
throw new \InvalidArgumentException(
|
||||
"The value \"$ipAddress\" is not a valid IP address."
|
||||
);
|
||||
}
|
||||
|
||||
$rawAddress = unpack('C*', $packedAddr);
|
||||
if ($rawAddress === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack the unsigned char of the packed in_addr representation.'
|
||||
);
|
||||
}
|
||||
|
||||
$bitCount = \count($rawAddress) * 8;
|
||||
|
||||
// The first node of the tree is always node 0, at the beginning of the
|
||||
// value
|
||||
$node = 0;
|
||||
|
||||
$metadata = $this->metadata;
|
||||
|
||||
// Check if we are looking up an IPv4 address in an IPv6 tree. If this
|
||||
// is the case, we can skip over the first 96 nodes.
|
||||
if ($metadata->ipVersion === 6) {
|
||||
if ($bitCount === 32) {
|
||||
$node = $this->ipV4Start;
|
||||
}
|
||||
} elseif ($metadata->ipVersion === 4 && $bitCount === 128) {
|
||||
throw new \InvalidArgumentException(
|
||||
"Error looking up $ipAddress. You attempted to look up an"
|
||||
. ' IPv6 address in an IPv4-only database.'
|
||||
);
|
||||
}
|
||||
|
||||
$nodeCount = $metadata->nodeCount;
|
||||
|
||||
for ($i = 0; $i < $bitCount && $node < $nodeCount; ++$i) {
|
||||
$tempBit = 0xFF & $rawAddress[($i >> 3) + 1];
|
||||
$bit = 1 & ($tempBit >> 7 - ($i % 8));
|
||||
|
||||
$node = $this->readNode($node, $bit);
|
||||
}
|
||||
if ($node === $nodeCount) {
|
||||
// Record is empty
|
||||
return [0, $i];
|
||||
}
|
||||
if ($node > $nodeCount) {
|
||||
// Record is a data pointer
|
||||
return [$node, $i];
|
||||
}
|
||||
|
||||
throw new InvalidDatabaseException(
|
||||
'Invalid or corrupt database. Maximum search depth reached without finding a leaf node'
|
||||
);
|
||||
}
|
||||
|
||||
private function ipV4StartNode(): int
|
||||
{
|
||||
// If we have an IPv4 database, the start node is the first node
|
||||
if ($this->metadata->ipVersion === 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$node = 0;
|
||||
|
||||
for ($i = 0; $i < 96 && $node < $this->metadata->nodeCount; ++$i) {
|
||||
$node = $this->readNode($node, 0);
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
private function readNode(int $nodeNumber, int $index): int
|
||||
{
|
||||
$baseOffset = $nodeNumber * $this->metadata->nodeByteSize;
|
||||
|
||||
switch ($this->metadata->recordSize) {
|
||||
case 24:
|
||||
$bytes = Util::read($this->fileHandle, $baseOffset + $index * 3, 3);
|
||||
$rc = unpack('N', "\x00" . $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack the unsigned long of the node.'
|
||||
);
|
||||
}
|
||||
[, $node] = $rc;
|
||||
|
||||
return $node;
|
||||
|
||||
case 28:
|
||||
$bytes = Util::read($this->fileHandle, $baseOffset + 3 * $index, 4);
|
||||
if ($index === 0) {
|
||||
$middle = (0xF0 & \ord($bytes[3])) >> 4;
|
||||
} else {
|
||||
$middle = 0x0F & \ord($bytes[0]);
|
||||
}
|
||||
$rc = unpack('N', \chr($middle) . substr($bytes, $index, 3));
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack the unsigned long of the node.'
|
||||
);
|
||||
}
|
||||
[, $node] = $rc;
|
||||
|
||||
return $node;
|
||||
|
||||
case 32:
|
||||
$bytes = Util::read($this->fileHandle, $baseOffset + $index * 4, 4);
|
||||
$rc = unpack('N', $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack the unsigned long of the node.'
|
||||
);
|
||||
}
|
||||
[, $node] = $rc;
|
||||
|
||||
return $node;
|
||||
|
||||
default:
|
||||
throw new InvalidDatabaseException(
|
||||
'Unknown record size: '
|
||||
. $this->metadata->recordSize
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
private function resolveDataPointer(int $pointer)
|
||||
{
|
||||
$resolved = $pointer - $this->metadata->nodeCount
|
||||
+ $this->metadata->searchTreeSize;
|
||||
if ($resolved >= $this->fileSize) {
|
||||
throw new InvalidDatabaseException(
|
||||
"The MaxMind DB file's search tree is corrupt"
|
||||
);
|
||||
}
|
||||
|
||||
[$data] = $this->decoder->decode($resolved);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/*
|
||||
* This is an extremely naive but reasonably readable implementation. There
|
||||
* are much faster algorithms (e.g., Boyer-Moore) for this if speed is ever
|
||||
* an issue, but I suspect it won't be.
|
||||
*/
|
||||
private function findMetadataStart(string $filename): int
|
||||
{
|
||||
$handle = $this->fileHandle;
|
||||
$fileSize = $this->fileSize;
|
||||
$marker = self::$METADATA_START_MARKER;
|
||||
$markerLength = self::$METADATA_START_MARKER_LENGTH;
|
||||
|
||||
$minStart = $fileSize - min(self::$METADATA_MAX_SIZE, $fileSize);
|
||||
|
||||
for ($offset = $fileSize - $markerLength; $offset >= $minStart; --$offset) {
|
||||
if (fseek($handle, $offset) !== 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
$value = fread($handle, $markerLength);
|
||||
if ($value === $marker) {
|
||||
return $offset + $markerLength;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidDatabaseException(
|
||||
"Error opening database file ($filename). "
|
||||
. 'Is this a valid MaxMind DB file?'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \InvalidArgumentException if arguments are passed to the method
|
||||
* @throws \BadMethodCallException if the database has been closed
|
||||
*
|
||||
* @return Metadata object for the database
|
||||
*/
|
||||
public function metadata(): Metadata
|
||||
{
|
||||
if (\func_num_args()) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 0 parameters, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
|
||||
// Not technically required, but this makes it consistent with
|
||||
// C extension and it allows us to change our implementation later.
|
||||
if (!\is_resource($this->fileHandle)) {
|
||||
throw new \BadMethodCallException(
|
||||
'Attempt to read from a closed MaxMind DB.'
|
||||
);
|
||||
}
|
||||
|
||||
return clone $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the MaxMind DB and returns resources to the system.
|
||||
*
|
||||
* @throws \Exception
|
||||
* if an I/O error occurs
|
||||
*/
|
||||
public function close(): void
|
||||
{
|
||||
if (\func_num_args()) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 0 parameters, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
|
||||
if (!\is_resource($this->fileHandle)) {
|
||||
throw new \BadMethodCallException(
|
||||
'Attempt to close a closed MaxMind DB.'
|
||||
);
|
||||
}
|
||||
fclose($this->fileHandle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MaxMind\Db\Reader;
|
||||
|
||||
// @codingStandardsIgnoreLine
|
||||
|
||||
class Decoder
|
||||
{
|
||||
/**
|
||||
* @var resource
|
||||
*/
|
||||
private $fileStream;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $pointerBase;
|
||||
|
||||
/**
|
||||
* This is only used for unit testing.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $pointerTestHack;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $switchByteOrder;
|
||||
|
||||
/**
|
||||
* Remaining decoded-value allowance for the current decode() call.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $budget = 0;
|
||||
|
||||
/**
|
||||
* Remaining string and bytes payload allowance for the current decode()
|
||||
* call.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $byteBudget = 0;
|
||||
|
||||
/**
|
||||
* Stream position after the last read of the current decode() call, or -1
|
||||
* when unknown.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $position = -1;
|
||||
|
||||
private const _EXTENDED = 0;
|
||||
private const _POINTER = 1;
|
||||
private const _UTF8_STRING = 2;
|
||||
private const _DOUBLE = 3;
|
||||
private const _BYTES = 4;
|
||||
private const _UINT16 = 5;
|
||||
private const _UINT32 = 6;
|
||||
private const _MAP = 7;
|
||||
private const _INT32 = 8;
|
||||
private const _UINT64 = 9;
|
||||
private const _UINT128 = 10;
|
||||
private const _ARRAY = 11;
|
||||
// 12 is the container type
|
||||
// 13 is the end marker type
|
||||
private const _BOOLEAN = 14;
|
||||
private const _FLOAT = 15;
|
||||
|
||||
// Per-lookup decode limits recommended by the MaxMind DB specification. The
|
||||
// depth limit stops pointer cycles and over-deep data. The value limit
|
||||
// stops a pointer fan-out, where nested pointers to shared targets would
|
||||
// otherwise cost 2**depth decode operations. The count follows the
|
||||
// specification's flat rule: the root is one value, each array and map
|
||||
// charges its declared children (a map entry costs two, key and value),
|
||||
// and a pointer costs nothing beyond the value it resolves to, which its
|
||||
// container already charged.
|
||||
private const MAX_DEPTH = 512;
|
||||
private const MAX_VALUES = 1 << 16;
|
||||
|
||||
// The value limit alone does not stop payload amplification: an array of
|
||||
// pointers to one large string or bytes value keeps the value count low
|
||||
// while forcing the reader to copy the target once per pointer. This
|
||||
// second limit bounds the total string and bytes payload copied for one
|
||||
// lookup to 2 MiB. Re-decoding a shared target charges its payload again.
|
||||
private const MAX_PAYLOAD_BYTES = 1 << 21;
|
||||
|
||||
// A fixed-width scalar (a float, double, or integer) never needs more than
|
||||
// 16 bytes (the width of a uint128). A larger declared size is either
|
||||
// corrupt or an attempt to amplify the read of an oversized variable-length
|
||||
// integer, so it is rejected before the bytes are materialized.
|
||||
private const MAX_SCALAR_BYTES = 16;
|
||||
|
||||
/**
|
||||
* @param resource $fileStream
|
||||
*/
|
||||
public function __construct(
|
||||
$fileStream,
|
||||
int $pointerBase = 0,
|
||||
bool $pointerTestHack = false
|
||||
) {
|
||||
$this->fileStream = $fileStream;
|
||||
$this->pointerBase = $pointerBase;
|
||||
|
||||
$this->pointerTestHack = $pointerTestHack;
|
||||
|
||||
$this->switchByteOrder = $this->isPlatformLittleEndian();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<mixed>
|
||||
*/
|
||||
public function decode(int $offset): array
|
||||
{
|
||||
// Reset both budgets for each lookup. Charge the root value here and
|
||||
// container children when entering each container. Reader prevents
|
||||
// nested lookups from moving its stream during a decode.
|
||||
$this->budget = self::MAX_VALUES - 1;
|
||||
$this->byteBudget = self::MAX_PAYLOAD_BYTES;
|
||||
|
||||
// Other readers of the stream, such as the search tree walk, may have
|
||||
// moved it since the last call.
|
||||
$this->position = -1;
|
||||
|
||||
return $this->decodeWithBudget($offset, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function decodeWithBudget(int $offset, int $depth, bool $allowPointer = true): array
|
||||
{
|
||||
$ctrlByte = \ord($this->read($offset, 1));
|
||||
++$offset;
|
||||
|
||||
$type = $ctrlByte >> 5;
|
||||
|
||||
// Pointers are a special case, we don't read the next $size bytes, we
|
||||
// use the size to determine the length of the pointer and then follow
|
||||
// it.
|
||||
if ($type === self::_POINTER) {
|
||||
if (!$allowPointer) {
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file contains a pointer to another pointer'
|
||||
);
|
||||
}
|
||||
|
||||
[$pointer, $offset] = $this->decodePointer($ctrlByte, $offset);
|
||||
|
||||
// for unit testing
|
||||
if ($this->pointerTestHack) {
|
||||
return [$pointer];
|
||||
}
|
||||
|
||||
if ($depth >= self::MAX_DEPTH) {
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file exceeds the maximum depth'
|
||||
);
|
||||
}
|
||||
|
||||
// The value at the pointer's position was charged by its containing
|
||||
// array or map, so the target costs nothing more. Only the depth
|
||||
// grows.
|
||||
[$result] = $this->decodeWithBudget($pointer, $depth + 1, false);
|
||||
|
||||
return [$result, $offset];
|
||||
}
|
||||
|
||||
if ($type === self::_EXTENDED) {
|
||||
$nextByte = \ord($this->read($offset, 1));
|
||||
|
||||
$type = $nextByte + 7;
|
||||
|
||||
if ($type < 8) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Something went horribly wrong in the decoder. An extended type '
|
||||
. 'resolved to a type number < 8 ('
|
||||
. $type
|
||||
. ')'
|
||||
);
|
||||
}
|
||||
|
||||
++$offset;
|
||||
}
|
||||
|
||||
[$size, $offset] = $this->sizeFromCtrlByte($ctrlByte, $offset);
|
||||
|
||||
return $this->decodeByType($type, $offset, $size, $depth);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int<0, max> $size
|
||||
*
|
||||
* @return array{0:mixed, 1:int}
|
||||
*/
|
||||
private function decodeByType(int $type, int $offset, int $size, int $depth): array
|
||||
{
|
||||
switch ($type) {
|
||||
case self::_MAP:
|
||||
return $this->decodeMap($size, $offset, $depth);
|
||||
|
||||
case self::_ARRAY:
|
||||
return $this->decodeArray($size, $offset, $depth);
|
||||
|
||||
case self::_BOOLEAN:
|
||||
return [$this->decodeBoolean($size), $offset];
|
||||
|
||||
case self::_BYTES:
|
||||
case self::_UTF8_STRING:
|
||||
// A string or bytes value is copied into a native string, so N
|
||||
// pointers to one large value copy N times its length. Charge
|
||||
// the payload against the byte budget wherever it is decoded,
|
||||
// including inline inside a pointed-to container, so a shared
|
||||
// target recharges each time it is followed. Compare before
|
||||
// subtracting so an oversized declared size cannot drive the
|
||||
// budget negative. A total exactly at the limit is allowed.
|
||||
if ($size > $this->byteBudget) {
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file exceeds the maximum payload size'
|
||||
);
|
||||
}
|
||||
$this->byteBudget -= $size;
|
||||
|
||||
return [$this->read($offset, $size), $offset + $size];
|
||||
}
|
||||
|
||||
// The remaining valid types are fixed-width scalars, none wider than a
|
||||
// uint128. A few other control bytes also reach here: the container
|
||||
// (12) and end-marker (13) types, and any unknown extended type. The
|
||||
// size guard below rejects one that declares an oversized size, and the
|
||||
// default case at the end of the switch rejects the rest. Reject an
|
||||
// oversized declared size before materializing the bytes, so an
|
||||
// oversized variable-length integer cannot amplify the read.
|
||||
if ($size > self::MAX_SCALAR_BYTES) {
|
||||
throw new InvalidDatabaseException(
|
||||
"The MaxMind DB file's data section contains bad data (unknown data type or corrupt data)"
|
||||
);
|
||||
}
|
||||
|
||||
$newOffset = $offset + $size;
|
||||
$bytes = $this->read($offset, $size);
|
||||
|
||||
switch ($type) {
|
||||
case self::_DOUBLE:
|
||||
$this->verifySize(8, $size);
|
||||
|
||||
return [$this->decodeDouble($bytes), $newOffset];
|
||||
|
||||
case self::_FLOAT:
|
||||
$this->verifySize(4, $size);
|
||||
|
||||
return [$this->decodeFloat($bytes), $newOffset];
|
||||
|
||||
case self::_INT32:
|
||||
return [$this->decodeInt32($bytes, $size), $newOffset];
|
||||
|
||||
case self::_UINT16:
|
||||
case self::_UINT32:
|
||||
case self::_UINT64:
|
||||
case self::_UINT128:
|
||||
return [$this->decodeUint($bytes, $size), $newOffset];
|
||||
|
||||
default:
|
||||
throw new InvalidDatabaseException(
|
||||
'Unknown or unexpected type: ' . $type
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads from the stream, seeking only when the read does not continue where
|
||||
* the previous one ended.
|
||||
*
|
||||
* @param int<0, max> $numberOfBytes
|
||||
*/
|
||||
private function read(int $offset, int $numberOfBytes): string
|
||||
{
|
||||
if ($numberOfBytes === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$stream = $this->fileStream;
|
||||
if ($offset !== $this->position && fseek($stream, $offset) !== 0) {
|
||||
$this->position = -1;
|
||||
|
||||
throw new InvalidDatabaseException('The MaxMind DB file contains bad data');
|
||||
}
|
||||
|
||||
$value = fread($stream, $numberOfBytes);
|
||||
if ($value === false || \strlen($value) !== $numberOfBytes) {
|
||||
$this->position = -1;
|
||||
|
||||
throw new InvalidDatabaseException('The MaxMind DB file contains bad data');
|
||||
}
|
||||
$this->position = $offset + $numberOfBytes;
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function verifySize(int $expected, int $actual): void
|
||||
{
|
||||
if ($expected !== $actual) {
|
||||
throw new InvalidDatabaseException(
|
||||
"The MaxMind DB file's data section contains bad data (unknown data type or corrupt data)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Charges declared children before decoding them. An oversized container
|
||||
* fails before any child is read. Each visit to a shared container charges
|
||||
* its children again, which bounds pointer fan-out.
|
||||
*/
|
||||
private function enterContainer(
|
||||
int $size,
|
||||
int $depth,
|
||||
int $valuesPerEntry = 1
|
||||
): void {
|
||||
if ($depth >= self::MAX_DEPTH) {
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file exceeds the maximum depth'
|
||||
);
|
||||
}
|
||||
if ($size > intdiv($this->budget, $valuesPerEntry)) {
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file exceeds the maximum number of values'
|
||||
);
|
||||
}
|
||||
$this->budget -= $size * $valuesPerEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:array<mixed>, 1:int}
|
||||
*/
|
||||
private function decodeArray(int $size, int $offset, int $depth): array
|
||||
{
|
||||
$this->enterContainer($size, $depth);
|
||||
|
||||
$array = [];
|
||||
|
||||
for ($i = 0; $i < $size; ++$i) {
|
||||
[$value, $offset] = $this->decodeWithBudget($offset, $depth + 1);
|
||||
$array[] = $value;
|
||||
}
|
||||
|
||||
return [$array, $offset];
|
||||
}
|
||||
|
||||
private function decodeBoolean(int $size): bool
|
||||
{
|
||||
return $size !== 0;
|
||||
}
|
||||
|
||||
private function decodeDouble(string $bytes): float
|
||||
{
|
||||
// This assumes IEEE 754 doubles, but most (all?) modern platforms
|
||||
// use them.
|
||||
$rc = unpack('E', $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack a double value from the given bytes.'
|
||||
);
|
||||
}
|
||||
[, $double] = $rc;
|
||||
|
||||
return $double;
|
||||
}
|
||||
|
||||
private function decodeFloat(string $bytes): float
|
||||
{
|
||||
// This assumes IEEE 754 floats, but most (all?) modern platforms
|
||||
// use them.
|
||||
$rc = unpack('G', $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack a float value from the given bytes.'
|
||||
);
|
||||
}
|
||||
[, $float] = $rc;
|
||||
|
||||
return $float;
|
||||
}
|
||||
|
||||
private function decodeInt32(string $bytes, int $size): int
|
||||
{
|
||||
switch ($size) {
|
||||
case 0:
|
||||
return 0;
|
||||
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
$bytes = str_pad($bytes, 4, "\x00", \STR_PAD_LEFT);
|
||||
|
||||
break;
|
||||
|
||||
case 4:
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new InvalidDatabaseException(
|
||||
"The MaxMind DB file's data section contains bad data (unknown data type or corrupt data)"
|
||||
);
|
||||
}
|
||||
|
||||
$rc = unpack('l', $this->maybeSwitchByteOrder($bytes));
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack a 32bit integer value from the given bytes.'
|
||||
);
|
||||
}
|
||||
[, $int] = $rc;
|
||||
|
||||
return $int;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:array<string, mixed>, 1:int}
|
||||
*/
|
||||
private function decodeMap(int $size, int $offset, int $depth): array
|
||||
{
|
||||
// A map entry decodes a key and a value, so it costs two values.
|
||||
$this->enterContainer($size, $depth, 2);
|
||||
|
||||
$map = [];
|
||||
|
||||
for ($i = 0; $i < $size; ++$i) {
|
||||
[$key, $offset] = $this->decodeWithBudget($offset, $depth + 1);
|
||||
[$value, $offset] = $this->decodeWithBudget($offset, $depth + 1);
|
||||
$map[$key] = $value;
|
||||
}
|
||||
|
||||
return [$map, $offset];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:int, 1:int}
|
||||
*/
|
||||
private function decodePointer(int $ctrlByte, int $offset): array
|
||||
{
|
||||
$pointerSize = (($ctrlByte >> 3) & 0x3) + 1;
|
||||
|
||||
$buffer = $this->read($offset, $pointerSize);
|
||||
$offset += $pointerSize;
|
||||
|
||||
switch ($pointerSize) {
|
||||
case 1:
|
||||
$packed = \chr($ctrlByte & 0x7) . $buffer;
|
||||
$rc = unpack('n', $packed);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned short value from the given bytes (pointerSize is 1).'
|
||||
);
|
||||
}
|
||||
[, $pointer] = $rc;
|
||||
$pointer += $this->pointerBase;
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
$packed = "\x00" . \chr($ctrlByte & 0x7) . $buffer;
|
||||
$rc = unpack('N', $packed);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned long value from the given bytes (pointerSize is 2).'
|
||||
);
|
||||
}
|
||||
[, $pointer] = $rc;
|
||||
$pointer += $this->pointerBase + 2048;
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
$packed = \chr($ctrlByte & 0x7) . $buffer;
|
||||
|
||||
// It is safe to use 'N' here, even on 32 bit machines as the
|
||||
// first bit is 0.
|
||||
$rc = unpack('N', $packed);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned long value from the given bytes (pointerSize is 3).'
|
||||
);
|
||||
}
|
||||
[, $pointer] = $rc;
|
||||
$pointer += $this->pointerBase + 526336;
|
||||
|
||||
break;
|
||||
|
||||
case 4:
|
||||
// We cannot use unpack here as we might overflow on 32 bit
|
||||
// machines
|
||||
$pointerOffset = $this->decodeUint($buffer, $pointerSize);
|
||||
|
||||
$pointerBase = $this->pointerBase;
|
||||
|
||||
if (\PHP_INT_MAX - $pointerBase >= $pointerOffset) {
|
||||
$pointer = $pointerOffset + $pointerBase;
|
||||
} else {
|
||||
throw new \RuntimeException(
|
||||
'The database offset is too large to be represented on your platform.'
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new InvalidDatabaseException(
|
||||
'Unexpected pointer size ' . $pointerSize
|
||||
);
|
||||
}
|
||||
|
||||
return [$pointer, $offset];
|
||||
}
|
||||
|
||||
// @phpstan-ignore-next-line
|
||||
private function decodeUint(string $bytes, int $byteLength)
|
||||
{
|
||||
if ($byteLength === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// PHP integers are signed. PHP_INT_SIZE - 1 is the number of
|
||||
// complete bytes that can be converted to an integer. However,
|
||||
// we can convert another byte if the leading bit is zero.
|
||||
$useRealInts = $byteLength <= \PHP_INT_SIZE - 1
|
||||
|| ($byteLength === \PHP_INT_SIZE && (\ord($bytes[0]) & 0x80) === 0);
|
||||
|
||||
if ($useRealInts) {
|
||||
$integer = 0;
|
||||
for ($i = 0; $i < $byteLength; ++$i) {
|
||||
$part = \ord($bytes[$i]);
|
||||
$integer = ($integer << 8) + $part;
|
||||
}
|
||||
|
||||
return $integer;
|
||||
}
|
||||
|
||||
// We only use gmp or bcmath if the final value is too big
|
||||
$integerAsString = '0';
|
||||
for ($i = 0; $i < $byteLength; ++$i) {
|
||||
$part = \ord($bytes[$i]);
|
||||
|
||||
if (\extension_loaded('gmp')) {
|
||||
$integerAsString = gmp_strval(gmp_add(gmp_mul($integerAsString, '256'), $part));
|
||||
} elseif (\extension_loaded('bcmath')) {
|
||||
$integerAsString = bcadd(bcmul($integerAsString, '256'), (string) $part);
|
||||
} else {
|
||||
throw new \RuntimeException(
|
||||
'The gmp or bcmath extension must be installed to read this database.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $integerAsString;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:int, 1:int}
|
||||
*/
|
||||
private function sizeFromCtrlByte(int $ctrlByte, int $offset): array
|
||||
{
|
||||
$size = $ctrlByte & 0x1F;
|
||||
|
||||
if ($size < 29) {
|
||||
return [$size, $offset];
|
||||
}
|
||||
|
||||
$bytesToRead = $size - 28;
|
||||
$bytes = $this->read($offset, $bytesToRead);
|
||||
|
||||
if ($size === 29) {
|
||||
$size = 29 + \ord($bytes);
|
||||
} elseif ($size === 30) {
|
||||
$rc = unpack('n', $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned short value from the given bytes.'
|
||||
);
|
||||
}
|
||||
[, $adjust] = $rc;
|
||||
$size = 285 + $adjust;
|
||||
} else {
|
||||
$rc = unpack('N', "\x00" . $bytes);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned long value from the given bytes.'
|
||||
);
|
||||
}
|
||||
[, $adjust] = $rc;
|
||||
$size = $adjust + 65821;
|
||||
}
|
||||
|
||||
return [$size, $offset + $bytesToRead];
|
||||
}
|
||||
|
||||
private function maybeSwitchByteOrder(string $bytes): string
|
||||
{
|
||||
return $this->switchByteOrder ? strrev($bytes) : $bytes;
|
||||
}
|
||||
|
||||
private function isPlatformLittleEndian(): bool
|
||||
{
|
||||
$testint = 0x00FF;
|
||||
$packed = pack('S', $testint);
|
||||
$rc = unpack('v', $packed);
|
||||
if ($rc === false) {
|
||||
throw new InvalidDatabaseException(
|
||||
'Could not unpack an unsigned short value from the given bytes.'
|
||||
);
|
||||
}
|
||||
|
||||
return $testint === current($rc);
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MaxMind\Db\Reader;
|
||||
|
||||
/**
|
||||
* This class should be thrown when unexpected data is found in the database.
|
||||
*/
|
||||
// phpcs:disable
|
||||
class InvalidDatabaseException extends \Exception {}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MaxMind\Db\Reader;
|
||||
|
||||
/**
|
||||
* This class provides the metadata for the MaxMind DB file.
|
||||
*/
|
||||
class Metadata
|
||||
{
|
||||
/**
|
||||
* This is an unsigned 16-bit integer indicating the major version number
|
||||
* for the database's binary format.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $binaryFormatMajorVersion;
|
||||
|
||||
/**
|
||||
* This is an unsigned 16-bit integer indicating the minor version number
|
||||
* for the database's binary format.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $binaryFormatMinorVersion;
|
||||
|
||||
/**
|
||||
* This is an unsigned 64-bit integer that contains the database build
|
||||
* timestamp as a Unix epoch value.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $buildEpoch;
|
||||
|
||||
/**
|
||||
* This is a string that indicates the structure of each data record
|
||||
* associated with an IP address. The actual definition of these
|
||||
* structures is left up to the database creator.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $databaseType;
|
||||
|
||||
/**
|
||||
* This key will always point to a map (associative array). The keys of
|
||||
* that map will be language codes, and the values will be a description
|
||||
* in that language as a UTF-8 string. May be undefined for some
|
||||
* databases.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public $description;
|
||||
|
||||
/**
|
||||
* This is an unsigned 16-bit integer which is always 4 or 6. It indicates
|
||||
* whether the database contains IPv4 or IPv6 address data.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $ipVersion;
|
||||
|
||||
/**
|
||||
* An array of strings, each of which is a language code. A given record
|
||||
* may contain data items that have been localized to some or all of
|
||||
* these languages. This may be undefined.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
public $languages;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
public $nodeByteSize;
|
||||
|
||||
/**
|
||||
* This is an unsigned 32-bit integer indicating the number of nodes in
|
||||
* the search tree.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $nodeCount;
|
||||
|
||||
/**
|
||||
* This is an unsigned 16-bit integer. It indicates the number of bits in a
|
||||
* record in the search tree. Note that each node consists of two records.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $recordSize;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
public $searchTreeSize;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $metadata
|
||||
*/
|
||||
public function __construct(array $metadata)
|
||||
{
|
||||
if (\func_num_args() !== 1) {
|
||||
throw new \ArgumentCountError(
|
||||
\sprintf('%s() expects exactly 1 parameter, %d given', __METHOD__, \func_num_args())
|
||||
);
|
||||
}
|
||||
|
||||
$this->binaryFormatMajorVersion
|
||||
= $metadata['binary_format_major_version'];
|
||||
$this->binaryFormatMinorVersion
|
||||
= $metadata['binary_format_minor_version'];
|
||||
$this->buildEpoch = $metadata['build_epoch'];
|
||||
$this->databaseType = $metadata['database_type'];
|
||||
$this->languages = $metadata['languages'];
|
||||
$this->description = $metadata['description'];
|
||||
$this->ipVersion = $metadata['ip_version'];
|
||||
$this->nodeCount = $metadata['node_count'];
|
||||
$this->recordSize = $metadata['record_size'];
|
||||
$this->nodeByteSize = $this->recordSize / 4;
|
||||
$this->searchTreeSize = $this->nodeCount * $this->nodeByteSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace MaxMind\Db\Reader;
|
||||
|
||||
class Util
|
||||
{
|
||||
/**
|
||||
* @param resource $stream
|
||||
* @param int<0, max> $numberOfBytes
|
||||
*/
|
||||
public static function read($stream, int $offset, int $numberOfBytes): string
|
||||
{
|
||||
if ($numberOfBytes === 0) {
|
||||
return '';
|
||||
}
|
||||
if (fseek($stream, $offset) === 0) {
|
||||
$value = fread($stream, $numberOfBytes);
|
||||
|
||||
// Check that the number of bytes read is the number asked for.
|
||||
if ($value !== false && \strlen($value) === $numberOfBytes) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidDatabaseException(
|
||||
'The MaxMind DB file contains bad data'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -210,6 +210,12 @@ class RotatingAdsTestDatabase
|
||||
}
|
||||
|
||||
if ($table === 'settings') {
|
||||
if (preg_match("/name='([^']+)'/", $where, $matches)) {
|
||||
$name = isset($matches[1]) ? stripslashes($matches[1]) : '';
|
||||
unset($this->settings[$name]);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->settings = array();
|
||||
}
|
||||
|
||||
@@ -344,7 +350,6 @@ $mybb = (object)array(
|
||||
'rotating_ads_rotation_max_seconds' => '30',
|
||||
'rotating_ads_country_detection' => 'auto',
|
||||
'rotating_ads_maxmind_database_path' => '',
|
||||
'rotating_ads_maxmind_autoload_path' => '',
|
||||
'rotating_ads_visitor_ip_source' => 'remote_addr',
|
||||
),
|
||||
'user' => array(
|
||||
@@ -382,7 +387,7 @@ rotating_ads_test_assert(
|
||||
$info = rotating_ads_info();
|
||||
rotating_ads_test_assert(
|
||||
$info['name'] === 'Rotating Ads'
|
||||
&& $info['version'] === '1.0.3'
|
||||
&& $info['version'] === '1.0.4'
|
||||
&& $info['website'] === 'https://github.com/sickprodigy/mybb_rotating-ads_plugin'
|
||||
&& $info['authorsite'] === 'https://www.sickgaming.net',
|
||||
'plugin info should expose localized metadata and version'
|
||||
@@ -518,6 +523,16 @@ $maxmind_reader = new class {
|
||||
$this->closed = true;
|
||||
}
|
||||
};
|
||||
rotating_ads_test_assert(
|
||||
rotating_ads_maxmind_database_path('/inc/geoip') === MYBB_ROOT . 'inc/geoip/GeoLite2-Country.mmdb'
|
||||
&& rotating_ads_maxmind_database_path('/inc/geoip/GeoLite2-Country.mmdb') === MYBB_ROOT . 'inc/geoip/GeoLite2-Country.mmdb',
|
||||
'MaxMind database paths under inc should resolve from the MyBB board root'
|
||||
);
|
||||
rotating_ads_test_assert(
|
||||
PHP_VERSION_ID < 70200
|
||||
|| (rotating_ads_load_maxmind_reader() && class_exists('MaxMind\\Db\\Reader')),
|
||||
'the bundled MaxMind reader should load without Composer on supported PHP versions'
|
||||
);
|
||||
rotating_ads_test_assert(
|
||||
rotating_ads_maxmind_country_code('203.0.113.4', $maxmind_fixture, function ($path) use ($maxmind_reader) {
|
||||
return $maxmind_reader;
|
||||
@@ -599,6 +614,12 @@ $mybb->settings['rotating_ads_rotation_min_seconds'] = '15';
|
||||
$mybb->settings['rotating_ads_rotation_max_seconds'] = '30';
|
||||
|
||||
rotating_ads_ensure_storage();
|
||||
$db->insert_query('settings', array(
|
||||
'name' => 'rotating_ads_maxmind_autoload_path',
|
||||
'title' => 'Legacy MaxMind reader autoload path',
|
||||
'value' => '/legacy/vendor/autoload.php',
|
||||
'gid' => 12,
|
||||
));
|
||||
rotating_ads_ensure_settings();
|
||||
$db->insert_query('rotating_ads', rotating_ads_prepare_ad_for_database(array(
|
||||
'slot' => 'square',
|
||||
@@ -619,8 +640,8 @@ rotating_ads_test_assert(
|
||||
&& isset($db->settings['rotating_ads_rotation_max_seconds'])
|
||||
&& isset($db->settings['rotating_ads_country_detection'])
|
||||
&& isset($db->settings['rotating_ads_maxmind_database_path'])
|
||||
&& isset($db->settings['rotating_ads_maxmind_autoload_path'])
|
||||
&& isset($db->settings['rotating_ads_visitor_ip_source']),
|
||||
&& isset($db->settings['rotating_ads_visitor_ip_source'])
|
||||
&& !isset($db->settings['rotating_ads_maxmind_autoload_path']),
|
||||
'setting synchronization should create polish settings'
|
||||
);
|
||||
rotating_ads_test_assert(
|
||||
@@ -731,7 +752,7 @@ $export = json_decode(rotating_ads_export_json(), true);
|
||||
rotating_ads_test_assert(
|
||||
isset($export['ads'])
|
||||
&& count($export['ads']) === count($db->ads)
|
||||
&& $export['version'] === '1.0.3',
|
||||
&& $export['version'] === '1.0.4',
|
||||
'ad export should bundle all records with plugin version metadata'
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user