From 21d352894f3ddf30168ecfc113124d684a3543f8 Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 3 Dec 2026 23:55:39 +0800 Subject: [PATCH] =?UTF-8?q?2.10.0=20=E6=96=B0=E5=A2=9E=E6=8B=8D=E6=91=84?= =?UTF-8?q?=E5=9C=B0=E7=82=B9=EF=BC=9AGPS=20+=20=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=20+=20=E7=81=AF=E7=AE=B1=E5=B0=8F=E5=9C=B0?= =?UTF-8?q?=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 + Plugin.php | 596 +++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 578 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index affde6b..ef188c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ > 本文件记录本插件的所有修改与变化。仓库建立于 2026-12-03,此前历史见插件目录内的 `更新日志.MD`。 +## 2026-12-03 · 2.10.0 新增拍摄地点:GPS + 中文地址 + 灯箱小地图 + +- 同步源码更新 1 个文件(新增/修改 1,删除 0)。 + ## 2026-12-03 · 2.9.5:修复附件记录查询被 JSON 转义卡死(EXIF 一直取不到的真因) Typecho 保存附件用的是 `'text' => json_encode($result)`(`var/Widget/Upload.php` 第 142、313 行), diff --git a/Plugin.php b/Plugin.php index b64131a..c232252 100644 --- a/Plugin.php +++ b/Plugin.php @@ -4,12 +4,26 @@ * * @package Qiniu * @author 石头厝 - * @version 2.9.5 + * @version 2.10.0 * @link https://www.shitoucuo.com/ * @since 1.2.0 */ /** + * 说明(2.10.0 拍摄地点): + * 1. 新增「拍摄地点」开关。开启后上传时读 EXIF 的 GPS IFD,把 WGS-84 坐标转成 + * 高德用的 GCJ-02,再调高德 Web 服务接口换成中文地址(省/市/区/街道)。 + * 地址与请求结果缓存在 cache/geotag/ 下(按坐标哈希,7 天),同一机位连拍只请求一次。 + * 2. 密钥不重复配置:直接复用 MyTrack 插件的 `webApiKey`(服务端逆地理)与 + * `jsApiKey`(灯箱小地图),MyTrack 未启用或没填 key 时自动降级 —— + * 服务端不请求地址、前端不出地图,只显示经纬度,不影响 EXIF 其它字段。 + * 3. 坐标必须转换:手机/GPS 记录的是 WGS-84,高德全系用 GCJ-02,国内直接拿 + * WGS-84 去定位会偏几百米(等于标到邻街去)。转换只在国境内做。 + * 4. 隐私:默认关闭。GPS 精度到十米级,等于公开拍摄点;开关由站长自己决定, + * 「关闭」时连 GPS 都不读、不存、不请求。 + * 5. 灯箱小地图是懒加载的:只有点开大图、且这一页确实有带坐标的图片时, + * 才去加载高德 JS API,首屏不多一个请求。 + * * 说明(2.9.5 附件记录查询修复 —— EXIF 一直取不到的真因): * 1. Typecho 存附件用 `json_encode($result)`(var/Widget/Upload.php),PHP 默认把斜杠 * 转义成 `\/`、非 ASCII 字符转成 `\uXXXX`。库里实际是: @@ -308,6 +322,23 @@ class Qiniu_Plugin implements Typecho_Plugin_Interface . '开启 WebP 自动转换不影响,信息取自转换前的原图') ); $form->addInput($exif); + + // 拍摄地点:GPS 属于敏感信息,独立开关、默认关闭 + $geotag = new Typecho_Widget_Helper_Form_Element_Radio( + 'geotag', + array('0' => _t('关闭'), '1' => _t('开启')), + '0', + _t('拍摄地点:'), + _t('开启后,带 GPS 的照片会多显示一项地点:悬停浮层与灯箱信息条里给出中文地址(如「云南省丽江市古城区」),' + . '灯箱顶部信息条右侧还有一枚小地图标点。本项依附于上面的「EXIF信息显示」,' + . '那一项没开时不会读取 GPS。' + . '
中文地址与地图复用 MyTrack 插件的密钥:地址用它的「Web 服务 API 密钥」在服务端反查,' + . '地图用它的「JS API 密钥」在浏览器里加载;MyTrack 没启用或没填密钥时自动降级为只显示经纬度。' + . '
隐私提醒:GPS 精度在十米级,等于公开你的拍摄点(含住址)。默认关闭,确认要公开再开。' + . '关闭状态下不读 GPS、不入库、不发起任何请求。' + . '
同样只对新上传的 JPEG 生效(PNG 读不到、老图不回填)。') + ); + $form->addInput($geotag); } /* ------------------------------------------------------------------ @@ -1313,7 +1344,10 @@ CSS; if (is_object($config)) { foreach ($values as $key => $default) { - $value = $config->{$key}; + // 配置对象可能是 Typecho\Config(魔术属性,缺键返回 null、不告警), + // 也可能是普通对象(单元测试桩、极老版本的数据);后者缺键会报 + // Undefined property,这里抑制掉 —— 缺键就是「用默认值」,不是错误 + $value = @$config->{$key}; if (null !== $value && '' !== $value) { $values[$key] = $value; } @@ -1328,9 +1362,15 @@ CSS; $values['accesskey'] = self::decryptSecret($values['accesskey']); $values['secretkey'] = self::decryptSecret($values['secretkey']); - self::$_config = class_exists('\Typecho\Config') - ? new \Typecho\Config($values) - : new Typecho_Config($values); + // 兼容 1.3(\Typecho\Config)与 1.2(Typecho_Config);两者都不在的环境 + // (单元测试/极端降级)退回普通对象,语义一致,不会因为少一个类直接 fatal + if (class_exists('\Typecho\Config')) { + self::$_config = new \Typecho\Config($values); + } elseif (class_exists('Typecho_Config')) { + self::$_config = new Typecho_Config($values); + } else { + self::$_config = (object) $values; + } return self::$_config; } @@ -1352,6 +1392,7 @@ CSS; 'webp' => '0', 'quality' => '85', 'exif' => '0', + 'geotag' => '0', ); } @@ -1511,7 +1552,7 @@ CSS; foreach (self::$_exifMap as $path => $exif) { $item = array(); - foreach (array('camera', 'exposure', 'aperture', 'iso', 'focal_length', 'date') as $key) { + foreach (array('camera', 'exposure', 'aperture', 'iso', 'focal_length', 'date', 'lat', 'lng', 'glat', 'glng', 'location') as $key) { if (!empty($exif[$key])) { $item[$key] = (string) $exif[$key]; } @@ -1557,7 +1598,17 @@ CSS; /* 各灯箱的「大图」容器;主题用的是 ViewImage,另两种是常见备选 */ var BIG = '.view-image-lead img, .fancybox-slide--image img, .pswp__img'; + /* 高德 JS 密钥:与 MyTrack 共用,没有就不出地图(只显示地名/坐标) */ + var AMAP_KEY = __AMAP_KEY__; + var AMAP_SRC = 'https://webapi.amap.com/maps?v=2.0&key='; + var bar = null; + var textBox = null; + var mapBox = null; + var amap = null; + var marker = null; + var amapState = 0; /* 0 未加载 / 1 加载中 / 2 就绪 / 3 失败 */ + var amapQueue = []; var shown = ''; function esc(text) { @@ -1608,9 +1659,104 @@ CSS; if (data.date) { out += '拍摄 ' + esc(data.date) + ''; } + var place = data.location || coordText(data.lat, data.lng); + if (place) { out += '地点 ' + esc(place) + ''; } + return out; } + /* 没有中文地址时的退路:26.8236°N 100.2197°E */ + function coordText(lat, lng) { + var la = parseFloat(lat); + var lo = parseFloat(lng); + if (!isFinite(la) || !isFinite(lo) || (la === 0 && lo === 0)) { return ''; } + return Math.abs(la).toFixed(4) + '°' + (la >= 0 ? 'N' : 'S') + ' ' + + Math.abs(lo).toFixed(4) + '°' + (lo >= 0 ? 'E' : 'W'); + } + + /* + * 信息条结构一次性建好,之后只改文字。 + * 不能每次 innerHTML 重建 —— 那样会把地图容器一起换掉,AMap 实例就挂在一个 + * 已经从文档里移除的节点上,地图永远是空白。 + */ + function ensureBar() { + if (bar) { return; } + + bar = document.createElement('div'); + bar.className = 'qiniu-exif-lightbox'; + + textBox = document.createElement('div'); + textBox.className = 'qiniu-exif-lb-text'; + + mapBox = document.createElement('div'); + mapBox.className = 'qiniu-exif-lb-map'; + mapBox.style.display = 'none'; + + bar.appendChild(textBox); + bar.appendChild(mapBox); + document.body.appendChild(bar); + } + + /* 懒加载高德 JS:只在「确实有带坐标的照片」时才拉,首屏不多一个请求 */ + function loadAmap(cb) { + if (window.AMap) { amapState = 2; cb(); return; } + if (!AMAP_KEY || amapState === 3) { return; } + + amapQueue.push(cb); + if (amapState === 1) { return; } + amapState = 1; + + var script = document.createElement('script'); + script.src = AMAP_SRC + encodeURIComponent(AMAP_KEY); + script.async = true; + script.onload = function () { + amapState = window.AMap ? 2 : 3; + var queue = amapQueue; + amapQueue = []; + for (var i = 0; i < queue.length; i++) { + try { queue[i](); } catch (e) {} + } + }; + script.onerror = function () { amapState = 3; }; + document.head.appendChild(script); + } + + function drawMap(lat, lng) { + if (!mapBox || !window.AMap) { return; } + + /* 容器还是隐藏状态时不要初始化,AMap 会按 0 尺寸画成空白 */ + if (!mapBox.offsetWidth) { return; } + + if (!amap) { + try { + amap = new AMap.Map(mapBox, { + zoom: 14, + center: [lng, lat], + mapStyle: 'amap://styles/dark', + resizeEnable: false, + dragEnable: false, + zoomEnable: false, + rotateEnable: false, + doubleClickZoom: false, + scrollWheel: false, + keyboardEnable: false, + touchZoom: false + }); + marker = new AMap.Marker({position: [lng, lat], map: amap}); + } catch (e) { + amap = null; + mapBox.style.display = 'none'; + } + return; + } + + try { + if (amap.setZoomAndCenter) { amap.setZoomAndCenter(14, [lng, lat]); } + else { amap.setCenter([lng, lat]); } + if (marker) { marker.setPosition([lng, lat]); } + } catch (e) {} + } + function place(img) { if (!bar) { return; } var rect = img.getBoundingClientRect(); @@ -1626,31 +1772,41 @@ CSS; function hide() { shown = ''; - if (bar) { - bar.className = 'qiniu-exif-lightbox'; - bar.innerHTML = ''; - } + if (!bar) { return; } + + bar.className = 'qiniu-exif-lightbox'; + if (textBox) { textBox.innerHTML = ''; } + if (mapBox) { mapBox.style.display = 'none'; } } function update() { var img = document.querySelector(BIG); if (!img) { hide(); return; } - var data = lookup(img.currentSrc || img.src); + var src = img.currentSrc || img.src; + var data = lookup(src); if (!data) { hide(); return; } var body = html(data); if (!body) { hide(); return; } - if (!bar) { - bar = document.createElement('div'); - bar.className = 'qiniu-exif-lightbox'; - document.body.appendChild(bar); + ensureBar(); + + if (shown !== src) { + shown = src; + textBox.innerHTML = body; } - if (shown !== (img.currentSrc || img.src)) { - shown = img.currentSrc || img.src; - bar.innerHTML = body; + /* 地图优先用 GCJ-02(高德坐标系),没有就退回 WGS-84 原值 */ + var lat = parseFloat(data.glat || data.lat); + var lng = parseFloat(data.glng || data.lng); + var hasPoint = !!AMAP_KEY && isFinite(lat) && isFinite(lng) && !(lat === 0 && lng === 0); + + if (hasPoint) { + mapBox.style.display = ''; + loadAmap(function () { drawMap(lat, lng); }); + } else { + mapBox.style.display = 'none'; } if (bar.className.indexOf('is-on') === -1) { @@ -1688,6 +1844,11 @@ CSS; })(); JS; + // JS API 密钥本来就只能暴露在前端(MyTrack 的文章内地图也是这么用的), + // 这里用 json_encode 写进脚本,避免引号把脚本打断。 + $key = json_encode(self::amapKey('js')); + $script = str_replace('__AMAP_KEY__', false === $key ? '""' : $key, $script); + return ''; } @@ -1712,15 +1873,23 @@ JS; // 缩略图已被 4:3 裁切,浮层意义不大,直接不显示,避免盖住画面。 . '.flexphoto .qiniu-exif-info{display:none!important;}' // 灯箱大图顶部的信息条:贴在大图顶边,跟随图片尺寸,不挡任何操作 - . '.qiniu-exif-lightbox{position:fixed;top:0;left:0;display:block;z-index:2147483000;' - . 'pointer-events:none;background:rgba(0,0,0,0.78);color:#fff;text-align:left;' + // 左侧文字 + 右侧小地图(flex);地图没坐标时由脚本收起,不占位 + . '.qiniu-exif-lightbox{position:fixed;top:0;left:0;display:flex;align-items:flex-start;gap:12px;' + . 'z-index:2147483000;pointer-events:none;background:rgba(0,0,0,0.78);color:#fff;text-align:left;' . 'padding:10px 14px;border-radius:0 0 8px 8px;font-size:13px;line-height:1.5;' . '-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);' . 'box-shadow:0 4px 16px rgba(0,0,0,.28);opacity:0;visibility:hidden;' . 'transition:opacity .2s ease,visibility .2s ease;}' . '.qiniu-exif-lightbox.is-on{opacity:1;visibility:visible;}' - . '.qiniu-exif-lightbox strong{display:block;font-weight:600;color:#fff;}' - . '.qiniu-exif-lightbox span{display:block;margin-top:2px;color:rgba(255,255,255,.86);}'; + // 文字区:选择器必须限定在 .qiniu-exif-lb-text 里, + // 否则会命中高德地图内部的 span,把地图结构搅乱 + . '.qiniu-exif-lb-text{flex:1 1 auto;min-width:0;}' + . '.qiniu-exif-lb-text strong{display:block;font-weight:600;color:#fff;}' + . '.qiniu-exif-lb-text span{display:block;margin-top:2px;color:rgba(255,255,255,.86);}' + . '.qiniu-exif-lb-map{flex:0 0 132px;width:132px;height:92px;border-radius:6px;' + . 'overflow:hidden;background:rgba(255,255,255,.1);}' + // 窄屏上信息条本来就要省地方,地图直接收起,只留地名文字 + . '@media (max-width:560px){.qiniu-exif-lb-map{display:none!important;}}'; } /** @@ -1850,6 +2019,16 @@ JS; $exifHtml .= '拍摄:' . htmlspecialchars($exifData['date']) . ''; } + // 地点:有中文地址优先用地址,没有就退回经纬度 + if (!empty($exifData['location'])) { + $exifHtml .= '地点:' . htmlspecialchars($exifData['location']) . ''; + } elseif (!empty($exifData['lat']) && !empty($exifData['lng'])) { + $coord = self::formatCoord($exifData['lat'], $exifData['lng']); + if ('' !== $coord) { + $exifHtml .= '地点:' . htmlspecialchars($coord) . ''; + } + } + $exifHtml .= ''; return '' . $imgTag . $exifHtml . ''; @@ -2185,9 +2364,382 @@ JS; } } + // 拍摄地点:开关关着就连 GPS 都不读(隐私优先,也省掉一次外部请求) + $option = self::getConfig(); + if (isset($option->geotag) && !empty($option->geotag)) { + $gps = self::readGps($filePath); + if (!empty($gps)) { + $lat = self::gpsCoordinate($gps, 'GPSLatitude', 'GPSLatitudeRef', 90); + $lng = self::gpsCoordinate($gps, 'GPSLongitude', 'GPSLongitudeRef', 180); + + // 手机没定位成功时会写 (0,0),那是几内亚湾,不是拍摄地 + if (null !== $lat && null !== $lng + && !(abs($lat) < 0.0001 && abs($lng) < 0.0001)) { + $result['lat'] = number_format($lat, 6, '.', ''); + $result['lng'] = number_format($lng, 6, '.', ''); + + // 高德全系是 GCJ-02,手机存的是 WGS-84,国内不转就差几百米 + list($glat, $glng) = self::toGcj($lat, $lng); + $result['glat'] = number_format($glat, 6, '.', ''); + $result['glng'] = number_format($glng, 6, '.', ''); + + $address = self::reverseGeocode($glat, $glng); + if ('' !== $address) { + $result['location'] = $address; + } + } + } + } + return $result; } + /** + * 取 GPS 标签组 + * + * 单独再用 as_arrays 读一次:不分组调用时 GPS 标签是否平铺到顶层,各 PHP 版本 + * 表现并不一致;分组读取的 `GPS` 分支最稳。图片不大,多读一次 IFD 的开销可以忽略。 + * + * @param string $filePath + * @return array + */ + private static function readGps($filePath) + { + if (!function_exists('exif_read_data')) { + return array(); + } + + $data = @exif_read_data($filePath, null, true); + if (!is_array($data)) { + return array(); + } + + if (isset($data['GPS']) && is_array($data['GPS'])) { + return $data['GPS']; + } + + // 退路:某些环境下 GPS 标签直接平铺在顶层 + return isset($data['GPSLatitude']) ? $data : array(); + } + + /** + * GPS 度分秒 → 十进制度 + * + * EXIF 里是三个 RATIONAL:度、分、秒,例如 ['26/1', '49/1', '24797973/1000000']。 + * 也见过被拼成一整串的('26/1 49/1 24797973/1000000'),一并认。 + * + * @param array $gps + * @param string $key GPSLatitude / GPSLongitude + * @param string $refKey GPSLatitudeRef / GPSLongitudeRef + * @param float $limit 纬度 90、经度 180,超出即视为脏数据 + * @return float|null + */ + private static function gpsCoordinate(array $gps, $key, $refKey, $limit) + { + if (empty($gps[$key])) { + return null; + } + + $parts = $gps[$key]; + if (is_string($parts)) { + $parts = preg_split('/[\s,]+/', trim($parts)); + } + if (!is_array($parts) || count($parts) < 2) { + return null; + } + $parts = array_values($parts); + + $deg = self::num($parts[0]); + $min = isset($parts[1]) ? self::num($parts[1]) : 0.0; + $sec = isset($parts[2]) ? self::num($parts[2]) : 0.0; + if (null === $deg) { + return null; + } + + $value = $deg + ($min ?: 0.0) / 60 + ($sec ?: 0.0) / 3600; + + $ref = isset($gps[$refKey]) ? strtoupper(trim((string) $gps[$refKey])) : ''; + if ('S' === $ref || 'W' === $ref) { + $value = -$value; + } + + if (abs($value) > $limit) { + return null; + } + + return $value; + } + + /** + * WGS-84 → GCJ-02 + * + * 算法是高德/腾讯系公开的那套「火星坐标」偏移;只在国境内应用, + * 境外原样返回(这套偏移在中国以外没有定义)。 + * + * @param float $lat + * @param float $lng + * @return array [lat, lng] + */ + private static function toGcj($lat, $lng) + { + if ($lng < 72.004 || $lng > 137.8347 || $lat < 0.8293 || $lat > 55.8271) { + return array($lat, $lng); + } + + $a = 6378245.0; + $ee = 0.00669342162296594323; + + $dlat = self::gcjDelta($lng - 105.0, $lat - 35.0, true); + $dlng = self::gcjDelta($lng - 105.0, $lat - 35.0, false); + + $radlat = $lat / 180.0 * M_PI; + $magic = sin($radlat); + $magic = 1 - $ee * $magic * $magic; + $sqrtmagic = sqrt($magic); + + $dlat = ($dlat * 180.0) / (($a * (1 - $ee)) / ($magic * $sqrtmagic) * M_PI); + $dlng = ($dlng * 180.0) / ($a / $sqrtmagic * cos($radlat) * M_PI); + + return array($lat + $dlat, $lng + $dlng); + } + + /** + * 火星坐标的偏移量计算(与 toGcj 配套) + * + * @param float $x 经度 - 105 + * @param float $y 纬度 - 35 + * @param bool $isLat + * @return float + */ + private static function gcjDelta($x, $y, $isLat) + { + $ret = $isLat + ? (-100.0 + 2.0 * $x + 3.0 * $y + 0.2 * $y * $y + 0.1 * $x * $y + 0.2 * sqrt(abs($x))) + : (300.0 + $x + 2.0 * $y + 0.1 * $x * $x + 0.1 * $x * $y + 0.1 * sqrt(abs($x))); + + $ret += (20.0 * sin(6.0 * $x * M_PI) + 20.0 * sin(2.0 * $x * M_PI)) * 2.0 / 3.0; + $ret += (20.0 * sin($x * M_PI) + 40.0 * sin($x / 3.0 * M_PI)) * 2.0 / 3.0; + $ret += (160.0 * sin($y / 12.0 * M_PI) + 320 * sin($y * M_PI / 30.0)) * 2.0 / 3.0; + + return $ret; + } + + /** + * 逆地理编码:GCJ-02 坐标 → 中文地址 + * + * 走高德的 Web 服务接口(复用 MyTrack 的 webApiKey,不在前端暴露)。 + * 结果按坐标哈希缓存 7 天 —— 同机位连拍几十张只请求一次;接口失败/超时/没 key + * 一律返回空串,上传照常完成,显示层自动退回经纬度。 + * + * @param float $lat GCJ-02 + * @param float $lng GCJ-02 + * @return string + */ + private static function reverseGeocode($lat, $lng) + { + $key = self::amapKey('web'); + if ('' === $key) { + return ''; + } + + $dir = __DIR__ . '/cache/geotag'; + $file = $dir . '/' . md5(number_format($lat, 5, '.', '') . ',' . number_format($lng, 5, '.', '')) . '.json'; + + if (is_file($file) && filemtime($file) > time() - 604800) { + $cached = json_decode((string) @file_get_contents($file), true); + if (is_array($cached) && array_key_exists('location', $cached)) { + return (string) $cached['location']; + } + } + + $url = 'https://restapi.amap.com/v3/geocode/regeo?key=' . rawurlencode($key) + . '&location=' . number_format($lng, 6, '.', '') . ',' . number_format($lat, 6, '.', '') + . '&extensions=base&batch=false&radius=300'; + + $body = self::httpGet($url, 3); + if ('' === $body) { + return ''; + } + + $location = self::parseRegeo($body); + if ('' === $location) { + return ''; + } + + if (!is_dir($dir)) { + @mkdir($dir, 0755, true); + } + if (is_dir($dir) && is_writable($dir)) { + @file_put_contents( + $file, + json_encode(array('location' => $location, 'ts' => time()), JSON_UNESCAPED_UNICODE) + ); + } + + return $location; + } + + /** + * 高德逆地理响应 → 一行地址 + * + * 单独拆出来是为了能脱离网络验证:省市区街道拼接、直辖市的 city 是空数组、 + * 境外只有 formatted_address 这几种边界都在这里收口。 + * + * @param string $body 接口原始 JSON + * @return string 失败返回空串 + */ + private static function parseRegeo($body) + { + $json = json_decode((string) $body, true); + if (!is_array($json) || !isset($json['status']) || '1' !== (string) $json['status']) { + return ''; + } + + $location = ''; + $component = isset($json['regeocode']['addressComponent']) ? $json['regeocode']['addressComponent'] : null; + if (is_array($component)) { + $parts = array(); + foreach (array('province', 'city', 'district', 'township') as $field) { + $value = isset($component[$field]) ? $component[$field] : ''; + // 直辖市/特别行政区的 city 会返回空数组 + if (is_array($value)) { + $value = ''; + } + $value = trim((string) $value); + if ('' !== $value && !in_array($value, $parts, true)) { + $parts[] = $value; + } + } + if (!empty($parts)) { + $location = implode('', $parts); + } + } + + if ('' === $location + && !empty($json['regeocode']['formatted_address']) + && is_string($json['regeocode']['formatted_address'])) { + $location = trim($json['regeocode']['formatted_address']); + } + + if ('' === $location) { + return ''; + } + + // 浮层与信息条空间有限,超长地址截断(保留省市区街道已足够定位) + if (function_exists('mb_substr')) { + $location = mb_substr($location, 0, 40, 'UTF-8'); + } + + return $location; + } + + /** + * 读 MyTrack 插件里的高德密钥 + * + * 不在本插件再存一份:同一站点两个 key 字段各存一遍,改一个忘一个必然出问题。 + * MyTrack 未启用时 plugin('MyTrack') 会抛 PluginException,这里吃掉返回空串。 + * + * @param string $type web(逆地理)/ js(灯箱小地图) + * @return string + */ + private static function amapKey($type = 'web') + { + $field = ('js' === $type) ? 'jsApiKey' : 'webApiKey'; + + try { + if (class_exists('\Widget\Options')) { + $config = \Widget\Options::alloc()->plugin('MyTrack'); + } else { + $config = Typecho_Widget::widget('Widget_Options')->plugin('MyTrack'); + } + + if (is_object($config) && !empty($config->{$field})) { + return trim((string) $config->{$field}); + } + } catch (Exception $e) { + // MyTrack 未启用 + } catch (Throwable $e) { + // PHP 7+ 的 Error 同样吞掉:地点是附加信息,不能连累上传 + } + + return ''; + } + + /** + * 极简 GET(只给逆地理用) + * + * 部分主机的 CA 库过期,证书校验会直接失败;这种情况下退一步用不校验重试一次, + * 宁可接受这点风险,也不要「地图能显示、地址永远空白」这种莫名的半残状态。 + * + * @param string $url + * @param int $timeout + * @return string 失败返回空串 + */ + private static function httpGet($url, $timeout = 3) + { + if (function_exists('curl_init')) { + for ($attempt = 0; $attempt < 2; $attempt++) { + $ch = curl_init($url); + curl_setopt_array($ch, array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CONNECTTIMEOUT => $timeout, + CURLOPT_TIMEOUT => $timeout, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 2, + CURLOPT_SSL_VERIFYPEER => (0 === $attempt), + CURLOPT_SSL_VERIFYHOST => (0 === $attempt) ? 2 : 0, + CURLOPT_USERAGENT => 'Typecho-Qiniu-Plugin/2.10', + )); + + $body = curl_exec($ch); + $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); + $errno = curl_errno($ch); + curl_close($ch); + + if (false !== $body && 200 === $code) { + return (string) $body; + } + + // 只有证书类错误才降级重试,其它错误(超时、DNS)重试也是白等 + if (0 === $attempt && in_array($errno, array(35, 51, 58, 60, 77, 83), true)) { + continue; + } + + return ''; + } + + return ''; + } + + $context = stream_context_create(array( + 'http' => array('timeout' => $timeout, 'user_agent' => 'Typecho-Qiniu-Plugin/2.10'), + )); + $body = @file_get_contents($url, false, $context); + + return false === $body ? '' : (string) $body; + } + + /** + * 经纬度显示写法 + * + * 没有中文地名时的退路:26.8236°N 100.2197°E,比赤裸裸的数字好认一点。 + * + * @param string|float $lat + * @param string|float $lng + * @return string + */ + private static function formatCoord($lat, $lng) + { + $lat = (float) $lat; + $lng = (float) $lng; + if (0.0 === $lat && 0.0 === $lng) { + return ''; + } + + return number_format(abs($lat), 4, '.', '') . '°' . ($lat >= 0 ? 'N' : 'S') . ' ' + . number_format(abs($lng), 4, '.', '') . '°' . ($lng >= 0 ? 'E' : 'W'); + } + /** * 检测是否支持WebP转换 *