| 1 | <?php
|
| 2 | /**
|
| 3 | * Build a posprint:// URL from a .pos document (array or JSON string).
|
| 4 | *
|
| 5 | * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
|
| 6 | *
|
| 7 | * @param array|string $pos PosFile as associative array or JSON string
|
| 8 | * @param array{noconfirm?: bool, origin?: string} $options Optional URL flags
|
| 9 | * @return string posprint://print?v=1&d=…
|
| 10 | * @throws InvalidArgumentException
|
| 11 | */
|
| 12 | function posprint_url($pos, array $options = []): string
|
| 13 | {
|
| 14 | if (is_array($pos)) {
|
| 15 | $json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
| 16 | if ($json === false) {
|
| 17 | throw new InvalidArgumentException('json_encode failed: ' . json_last_error_msg());
|
| 18 | }
|
| 19 | } elseif (is_string($pos)) {
|
| 20 | $json = $pos;
|
| 21 | } else {
|
| 22 | throw new InvalidArgumentException('pos must be array or JSON string');
|
| 23 | }
|
| 24 |
|
| 25 | $compressed = gzdeflate($json, 9);
|
| 26 | if ($compressed === false) {
|
| 27 | throw new InvalidArgumentException('gzdeflate failed');
|
| 28 | }
|
| 29 |
|
| 30 | $b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
|
| 31 | $url = 'posprint://print?v=1&d=' . $b64;
|
| 32 |
|
| 33 | if (!empty($options['noconfirm'])) {
|
| 34 | $url .= '&noconfirm=1';
|
| 35 | }
|
| 36 | if (!empty($options['origin'])) {
|
| 37 | $host = posprint_normalize_origin((string) $options['origin']);
|
| 38 | if ($host !== null) {
|
| 39 | $url .= '&origin=' . rawurlencode($host);
|
| 40 | }
|
| 41 | }
|
| 42 |
|
| 43 | return $url;
|
| 44 | }
|
| 45 |
|
| 46 | /**
|
| 47 | * @return string|null lowercase hostname
|
| 48 | */
|
| 49 | function posprint_normalize_origin(string $raw): ?string
|
| 50 | {
|
| 51 | $s = trim($raw);
|
| 52 | if ($s === '') {
|
| 53 | return null;
|
| 54 | }
|
| 55 | if (preg_match('#^https?://#i', $s) === 1) {
|
| 56 | $host = parse_url($s, PHP_URL_HOST);
|
| 57 | return is_string($host) && $host !== '' ? strtolower($host) : null;
|
| 58 | }
|
| 59 | $host = explode('/', $s, 2)[0];
|
| 60 | $host = explode(':', $host, 2)[0];
|
| 61 | $host = trim($host);
|
| 62 | return $host !== '' ? strtolower($host) : null;
|
| 63 | }
|