From a09ec7f5ed183f8b56012b994772cb192305015f Mon Sep 17 00:00:00 2001 From: Yusur Princeps Date: Sun, 2 Nov 2025 19:02:01 +0100 Subject: [PATCH] 0.1.0 initial commit --- .gitignore | 29 ++++ LICENSE | 54 ++++++++ composer.json | 18 +++ src/Country.php | 328 ++++++++++++++++++++++++++++++++++++++++++++ src/IpAddress.php | 53 +++++++ src/IpLocator.php | 115 ++++++++++++++++ src/MiniMD.php | 47 +++++++ src/RegionBlock.php | 78 +++++++++++ src/UserAgent.php | 294 +++++++++++++++++++++++++++++++++++++++ 9 files changed, 1016 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 composer.json create mode 100644 src/Country.php create mode 100644 src/IpAddress.php create mode 100644 src/IpLocator.php create mode 100644 src/MiniMD.php create mode 100644 src/RegionBlock.php create mode 100644 src/UserAgent.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52dbdc0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ + +vendor/ + +node_modules/ +__pycache__/ +**.pyc +**.pyo +**.egg-info +**~ +.*.swp +\#*\# +.\#* +alembic.ini +.env +.env.* +.venv +env +venv +venv-*/ +config/ +conf/ +config.json +data/ +build/ +dist/ +/target +.err +.vscode +/run.sh diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..263e72a --- /dev/null +++ b/LICENSE @@ -0,0 +1,54 @@ + + +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: + + You must give any other recipients of the Work or Derivative Works a copy of this License; and + You must cause any modified files to carry prominent notices stating that You changed the files; and + 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 + 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 diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b28169c --- /dev/null +++ b/composer.json @@ -0,0 +1,18 @@ +{ + "name": "yusurko/useragent", + "type": "library", + "version": "0.1.0", + "license": "Apache-2.0", + "autoload": { + "psr-4": { + "Yusurko\\UserAgent\\": "src/" + } + }, + "authors": [ + { + "name": "Yusur Princeps", + "email": "sakuragasaki46@gmail.com" + } + ], + "require": {} +} diff --git a/src/Country.php b/src/Country.php new file mode 100644 index 0000000..738a7f5 --- /dev/null +++ b/src/Country.php @@ -0,0 +1,328 @@ + (registration required). + * IP2Location Lite® is a registered trademark of Hexasoft Development Sdn Bhd. + */ + +namespace Yusurko\UserAgent; + +use Yusurko\UserAgent\RegionBlock; + +class Country { + const NAMES = [ + '@' => 'Headspace', + '+' => 'Inner Space', + '-' => 'Outer Space', + 'AC' => 'Ascension (UK)', + 'AD' => 'Andorra', + 'AE' => 'United Arab Emirates', + 'AF' => 'Afghanistan', + 'AG' => 'Antigua & Barbuda', + 'AI' => 'Anguilla (UK)', + 'AL' => 'Albania', + 'AM' => 'Armenia', + 'AO' => 'Angola', + 'AQ' => 'Antarctica', + 'AR' => 'Argentina', + 'AS' => 'American Samoa', + 'AT' => 'Austria', + 'AU' => 'Australia', + 'AW' => 'Aruba (Netherlands)', + 'AX' => 'Åland (Finland)', + 'AZ' => 'Azerbaijan', + 'BA' => 'Bosnia & Herzegovina', + 'BB' => 'Barbados', + 'BD' => 'Bangladesh', + 'BE' => 'Belgium', + 'BF' => 'Burkina Faso', + 'BG' => 'Bulgaria', + 'BH' => 'Bahrain', + 'BI' => 'Burundi', + 'BJ' => 'Benin', + 'BL' => 'Saint Barthélemy (France)', + 'BM' => 'Bermuda (UK)', + 'BN' => 'Brunei', + 'BO' => 'Bolivia', + 'BQ' => 'Bonaire (Netherlands)', + 'BR' => 'Brazil', + 'BS' => 'Bahamas', + 'BT' => 'Bhutan', + 'BV' => 'Bouvet Island (Norway)', + 'BW' => 'Botswana', + 'BY' => 'Belarus', + 'BZ' => 'Belize', + 'CA' => 'Canada', + 'CC' => 'Cocos (Keeling) Islands (Australia)', + 'CD' => 'Democratic Republic of the Congo', + 'CF' => 'Central African Republic', + 'CG' => 'Republic of the Congo', + 'CH' => 'Switzerland', + 'CI' => 'Côte d\'Ivoire', + 'CK' => 'Cook Islands (UK)', + 'CL' => 'Chile', + 'CM' => 'Cameroon', + 'CN' => 'People\'s Republic of China', + 'CO' => 'Colombia', + 'CP' => 'France', + 'CQ' => 'Sark (UK)', + 'CR' => 'Costa Rica', + 'CU' => 'Cuba', + 'CV' => 'Cape Verde', + 'CW' => 'Curaçao (Netherlands)', + 'CX' => 'Christmas Island (Australia)', + 'CY' => 'Cyprus', + 'CZ' => 'Czechia', + 'DE' => 'Germany', + 'DG' => 'Chagos (Mauritius)', + 'DJ' => 'Djibouti', + 'DK' => 'Denmark', + 'DM' => 'Dominica', + 'DO' => 'Dominican Republic', + 'DZ' => 'Algeria', + 'EA' => 'Spain', + 'EC' => 'Ecuador', + 'EE' => 'Estonia', + 'EG' => 'Egypt', + 'EH' => 'Western Sahara', + 'ER' => 'Eritrea', + 'ES' => 'Spain', + 'ET' => 'Ethiopia', + 'EU' => 'European Union', + 'EZ' => 'Eurozone', + 'FI' => 'Finland', + 'FJ' => 'Fiji', + 'FK' => 'Falkland Islands (UK)', + 'FM' => 'Federated States of Micronesia', + 'FO' => 'Faroe Islands (Denmark)', + 'FR' => 'France', + 'FX' => 'France', + 'GA' => 'Gabon', + 'GB' => 'United Kingdom (wrong)', + 'GD' => 'Grenada', + 'GE' => 'Georgia', + 'GF' => 'French Guyane', + 'GG' => 'Guernsey (UK)', + 'GH' => 'Ghana', + 'GI' => 'Gibraltar (UK)', + 'GL' => 'Greenland (Denmark)', + 'GM' => 'Gambia', + 'GN' => 'Guinea', + 'GP' => 'Guadeloupe (France)', + 'GQ' => 'Equatorial Guinea', + 'GR' => 'Greece', + 'GS' => 'South Georgia & South Sandwich Islands (UK)', + 'GT' => 'Guatemala', + 'GU' => 'Guam (USA)', + 'GW' => 'Guinea-Bissau', + 'GY' => 'Guyana', + 'HK' => 'Hong Kong (PRC)', + 'HM' => 'Heard & McDonald Islands (Australia)', + 'HN' => 'Honduras', + 'HR' => 'Croatia', + 'HT' => 'Haïti', + 'HU' => 'Hungary', + 'IC' => 'Canary Islands (Spain)', + 'ID' => 'Indonesia', + 'IE' => 'Ireland', + 'IL' => 'Israel', + 'IM' => 'Isle of Man (UK)', + 'IN' => 'India (Bharat)', + 'IO' => 'Chagos (Mauritius)', + 'IQ' => 'Iraq', + 'IR' => 'Iran', + 'IS' => 'Iceland', + 'IT' => 'Italy', + 'JE' => 'Jersey (UK)', + 'JM' => 'Jamaica', + 'JO' => 'Jordan', + 'JP' => 'Japan', + 'KE' => 'Kenya', + 'KG' => 'Kyrgyzstan', + 'KH' => 'Cambodia', + 'KI' => 'Kiribati', + 'KM' => 'Comoros', + 'KN' => 'Saint Kitts & Nevis', + 'KP' => 'Democratic People\'s Republic of Korea', + 'KR' => 'Republic of Korea', + 'KW' => 'Kuwait', + 'KY' => 'Cayman Islands (UK)', + 'KZ' => 'Kazakhstan', + 'LA' => 'Laos', + 'LB' => 'Lebanon', + 'LC' => 'Saint Lucia', + 'LI' => 'Liechtenstein', + 'LK' => 'Sri Lanka', + 'LR' => 'Liberia', + 'LS' => 'Lesotho', + 'LT' => 'Lithuania', + 'LU' => 'Luxembourg', + 'LV' => 'Latvia', + 'LY' => 'Libya', + 'MA' => 'Morocco', + 'MC' => 'Monaco', + 'MD' => 'Moldova', + 'ME' => 'Montenegro', + 'MF' => 'Saint Martin (France)', + 'MG' => 'Madagascar', + 'MH' => 'Marshall Islands', + 'MK' => 'North Macedonia', + 'ML' => 'Mali', + 'MM' => 'Myanmar', + 'MN' => 'Mongolia', + 'MO' => 'Macao (PRC)', + 'MP' => 'Northern Mariana Islands (USA)', + 'MQ' => 'Martinique (France)', + 'MR' => 'Mauritania', + 'MS' => 'Montserrat (United Kingdom)', + 'MT' => 'Malta', + 'MU' => 'Mauritius', + 'MV' => 'Maldives', + 'MW' => 'Malawi', + 'MX' => 'Mexico', + 'MY' => 'Malaysia', + 'MZ' => 'Mozambique', + 'NA' => 'Namibia', + 'NC' => 'New Caledonia (France)', + 'NE' => 'Niger', + 'NF' => 'Norfolk Island (Australia)', + 'NG' => 'Nigeria', + 'NI' => 'Nicaragua', + 'NL' => 'Netherlands', + 'NO' => 'Norway', + 'NP' => 'Nepal', + 'NR' => 'Nauru', + 'NU' => 'Niue (NZ)', + 'NZ' => 'New Zealand', + 'OM' => 'Oman', + 'PA' => 'Panama', + 'PE' => 'Peru', + 'PF' => 'French Polynesia', + 'PG' => 'Papua New Guinea', + 'PH' => 'Philippines', + 'PK' => 'Pakistan', + 'PL' => 'Poland', + 'PM' => 'Saint Pierre & Miquelon (France)', + 'PN' => 'Pitcairn (UK)', + 'PR' => 'Puerto Rico (USA)', + 'PS' => 'Palestinian Authority', + 'PT' => 'Portugal', + 'PW' => 'Palau', + 'PY' => 'Paraguay', + 'QA' => 'Qatar', + 'QM' => 'Mars', + 'RE' => 'Réunion (France)', + 'RO' => 'Romania', + 'RS' => 'Serbia', + 'RU' => 'Russian Federation', + 'RW' => 'Rwanda', + 'SA' => 'Saudi Arabia', + 'SB' => 'Solomon Islands', + 'SC' => 'Seychelles', + 'SD' => 'Sudan', + 'SE' => 'Sweden', + 'SG' => 'Singapore', + 'SH' => 'Saint Helena (UK)', + 'SI' => 'Slovenia', + 'SJ' => 'Svalbard & Jan Mayen (Norway)', + 'SK' => 'Slovakia', + 'SL' => 'Sierra Leone', + 'SM' => 'San Marino', + 'SN' => 'Senegal', + 'SO' => 'Somalia', + 'SR' => 'Suriname', + 'SS' => 'South Sudan', + 'ST' => 'Sao Tome & Principe', + 'SU' => 'Soviet Union', + 'SV' => 'El Salvador', + 'SX' => 'Sint Maarten (Netherlands)', + 'SY' => 'Syria', + 'SZ' => 'eSwatini', + 'TA' => 'Tristan da Cunha (UK)', + 'TC' => 'Turks and Caicos Islands (UK)', + 'TD' => 'Chad', + 'TF' => 'French Southern Territories', + 'TG' => 'Togo', + 'TH' => 'Thailand', + 'TK' => 'Tokelau', + 'TL' => 'Timor-Leste', + 'TM' => 'Turkmenistan', + 'TN' => 'Tunisia', + 'TO' => 'Tonga', + 'TR' => 'Türkiye', + 'TT' => 'Trinidad & Tobago', + 'TV' => 'Tuvalu', + 'TW' => 'Republic of China (Taiwan)', + 'TZ' => 'Tanzania', + 'UA' => 'Ukraine', + 'UG' => 'Uganda', + 'UK' => 'United Kingdom', + 'UM' => 'USA Minor Outlying Islands', + 'UN' => 'United Nations', + 'US' => 'United States of America', + 'UY' => 'Uruguay', + 'UZ' => 'Uzbekistan', + 'VA' => 'Vatican City', + 'VC' => 'Saint Vincent & Grenadines', + 'VE' => 'Venezuela', + 'VG' => 'British Virgin Islands', + 'VI' => 'US Virgin Islands', + 'VN' => 'Vietnam', + 'VU' => 'Vanuatu', + 'WF' => 'Wallis & Futuna (France)', + 'WS' => 'Samoa', + 'XK' => 'Kosovo', + 'YE' => 'Yemen', + 'YT' => 'Mayotte (France)', + 'ZA' => 'South Africa', + 'ZM' => 'Zambia', + 'ZW' => 'Zimbabwe' + ]; + + const EUROPE = array ( + 'AD', 'AL', 'AT', 'AX', 'BA', 'BE', 'BG', 'CH', + 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FO', + 'FR', 'GE', 'GF', 'GG', 'GI', 'GL', 'GR', + 'HR', 'HU', 'IE', 'IM', 'IS', 'IT', 'LI', 'LT', + 'LU', 'LV', 'MC', 'MD', 'ME', 'MK', 'MQ', 'MT', + 'NL', 'NO', 'PL', 'PT', 'RO', 'SE', 'SI', 'SJ', + 'SK', 'SM', 'VA', '@', '+' + ); + + protected $cc; + + public function __construct ($cc) { + $this->cc = $cc; + } + + public function getCode () { + return $this->cc; + } + + public function getName() { + return self::NAMES[$this->cc] ?? $this->cc; + } + + public function isEurope() { + return in_array($this->cc, self::EUROPE, true); + } + + public function isUS() { + return in_array($this->cc, [ 'US', 'UM', 'QM' ], true); + } + + public function isBlocked() { + return (new RegionBlock($this->cc))->isBlocked(); + } + + public function isInnerSpace() { + return in_array($this->cc, [ '@', '+' ], true); + } + + public static function outerSpace() { + return new self("-"); + } +} \ No newline at end of file diff --git a/src/IpAddress.php b/src/IpAddress.php new file mode 100644 index 0000000..caf7aab --- /dev/null +++ b/src/IpAddress.php @@ -0,0 +1,53 @@ + (registration required). + * IP2Location Lite® is a registered trademark of Hexasoft Development Sdn Bhd. + */ + +namespace Yusurko\UserAgent; + +use phpseclib3\Math\BigInteger; + +class IpAddress extends BigInteger { + public function __construct ($addr) { + if (strpos($addr, ':') !== false) { + // IPv6 // + $dc = strpos($addr, '::'); + if ($dc === false) { + $addrParts = explode(':', $addr); + } else { + [ $addr1, $addr2 ] = explode('::', $addr, 2); + $addr1 = explode(':', $addr1); + $addr2 = explode(':', $addr2); + $addrParts = array_merge($addr1, array_fill(count($addr1), 8 - count($addr1) - count($addr2), '0'), $addr2); + } + + $hexAddr = ''; + foreach ($addrParts as $p) { + $hexAddr .= str_pad($p, 4, '0', STR_PAD_LEFT); + } + + //assert strlen($hexAddr) === 32; + parent::__construct($hexAddr, 16); + } elseif (strpos($addr, '.') !== false) { + // IPv4 // + $addrParts = explode('.', $addr); + + parent::__construct((65535 << 32) | ($addrParts[0] << 24) | ($addrParts[1] << 16) | ($addrParts[2] << 8) | ($addrParts[3])); + } else { + // big-ass number // + parent::__construct($addr); + } + } + + public function toFullHex () { + return str_pad($this->toHex(), 32, '0', STR_PAD_LEFT); + } + + static public function fromHex($hs) { + return new IpAddress((new BigInteger($hs, 16))->toString()); + } +} \ No newline at end of file diff --git a/src/IpLocator.php b/src/IpLocator.php new file mode 100644 index 0000000..c8ed579 --- /dev/null +++ b/src/IpLocator.php @@ -0,0 +1,115 @@ + (registration required). + * IP2Location Lite® is a registered trademark of Hexasoft Development Sdn Bhd. + */ + +namespace Yusurko\UserAgent; + + +use Yusurko\UserAgent\IpAddress; + + +class IpLocator { + protected $conn, $source_file; + + const SOURCE_FILE = '.err/data/IP2LOCATION-LITE-DB1.IPV6.CSV'; + + const LOCAL_RANGES = [ + ["0", "1", '@'], + ["281470681743360", "281470698520575", '+'], + ["281470849515520", "281470866292735", "+"], + ["281472812449792", "281472829227007", "@"], + ["281473533739008", "281473533804543", "+"], + ["281473568473088", "281473569521663", "+"], + ["281473913978880", "281473914044415", "+"], + ["338288524927261089654018896841347694592", "338288524927261089672465640915057246207", "+"] + ]; + + public function __construct($conn, $source_file = self::SOURCE_FILE) { + $this->conn = $conn; + $this->source_file = $source_file; + } + + public function locate($addr){ + $addr = new IpAddress($addr); + + if (!$this->isDbLoaded()) { + $up_to_range = $this->getDbLoadedUpto(); + $this->loadCsvIntoDb($up_to_range); + } + + $country = $this->lookupDb($addr); + + return new Country($country); + } + + private function isDbLoaded() { + $ex = $this->conn->prepare("SELECT 1 FROM af_ip2location WHERE range_end = x'ffffffffffffffffffffffffffffffff'"); + $ex->execute(); + $res = $ex->get_result(); + + return ($res->num_rows > 0); + } + + private function getDbLoadedUpto(){ + $ex = $this->conn->prepare("SELECT hex(range_end) FROM af_ip2location ORDER BY id DESC LIMIT 1"); + $ex->execute(); + $ex->store_result(); + $ex->bind_result($range_end); + $ex->fetch(); + + return IpAddress::fromHex($range_end); + } + + private function loadCsvIntoDb($start = false) { + + $f = fopen($this->source_file, 'r'); + + while (($line = fgetcsv($f)) !== false) { + $rs = new IpAddress($line[0]); + $re = new IpAddress($line[1]); + if ($rs->compare($start) <= 0) continue; + try { + $this->storeRangeIntoDb($rs, $re, $line[2]); + } catch (\mysqli_sql_exception $ee) { + return false; + } + } + + return true; + } + + private function storeRangeIntoDb($range_start, $range_end, $country) { + $range_start_x = $range_start->toFullHex(); + $range_end_x = $range_end->toFullHex(); + $ins = $this->conn->prepare('INSERT INTO af_ip2location (range_start, range_end, country) VALUES (unhex(?), unhex(?), ?)'); + $ins->bind_param('sss', $range_start_x, $range_end_x, $country); + $ins->execute(); + $ins->store_result(); + } + + private function lookupDb($addr) { + // look up forbidden ranges first + foreach (self::LOCAL_RANGES as $rang) { + [ $rs, $re, $co ] = $rang; + if ($addr->compare(new IpAddress($rs)) >= 0 && $addr->compare(new IpAddress($re)) <= 0) { + return $co; + } + } + + $addr_x = $addr->toFullHex(); + $st = $this->conn->prepare('SELECT country FROM af_ip2location WHERE range_end >= unhex(?) AND range_start <= unhex(?)'); + $st->bind_param('ss', $addr_x, $addr_x); + $st->execute(); + $res = $st->get_result(); + if ($res->num_rows < 1) { + return false; + } + + return $res->fetch_assoc()['country']; + } +} \ No newline at end of file diff --git a/src/MiniMD.php b/src/MiniMD.php new file mode 100644 index 0000000..1163183 --- /dev/null +++ b/src/MiniMD.php @@ -0,0 +1,47 @@ + block MiniMD (wrap in

tags) + * new MiniMD(true); => inline MiniMD (do not wrap in

tags) + */ + public function __construct($inline) { + $this->inline = $inline; + } + + public function transform($text) { + $text = preg_replace_callback('/\\\([!-\/:-@\[-`\{-~])/', function ($x) { return "\x05" . str_pad(dechex(ord($x[1])), 2, '0'); }, $text); + $text = htmlspecialchars($text); + $text = preg_replace('/\B\*\*(.*?)\*\*\B/u', '\1', $text); + $text = preg_replace('/\B\*(.*?)\*\B/u', '\1', $text); + $text = preg_replace('/\b__(.*?)__\b/u', '\1', $text); + $text = preg_replace('/\B~~(.*?)~~\B/u', '\1', $text); + $text = preg_replace('/\[(.*?)\]\((\/(?:[^\/\)].*?)?)\)/u', '\1', $text); + $text = preg_replace('/<(https?:\/\/[^\s]+?)>/u', '\1', $text); + $text = preg_replace('/\[(.*?)\]\((.*?)\)/u', '\1', $text); + if ($this->inline) { + $text = preg_replace_callback('/\x05([0-7][0-9a-f])/u', function ($x) { return htmlspecialchars(chr(hexdec($x[1]))); }, $text); + return $text; + } + // from now on, block only + $text = preg_replace('/ >> (.+)/u', '

\1
', $text); + $text = preg_replace('/^\* (.*)$/mu', '', $text); + $text = str_replace("\n