系列最終篇:將上一篇獲取的文章永久鏈接,通過百度站長平台「主動推送(實時)」接口推送,並記錄推送結果供後台查看。
\n{"remain":4999,"success":1} 或錯誤碼/**
* 批量推送 URL 到百度
* @param string|array $urls 單個 URL 或 URL 陣列
* @param Typecho_Widget_Helper_Form $options 系統配置對象
* @return array ['success'=>int, 'remain'=>int, 'error'=>string|null]
*/
private static function pushByCurl($urls, $options) {
$api = $options->plugin('BaiduSubmit')->api;
if (empty($api)) return ['success' => 0, 'error' => 'API 未配置'];
$urls = (array)$urls;
$ch = curl_init($api);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => implode("\n", $urls),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: text/plain', 'User-Agent: Typecho-BaiduSubmit/1.0'],
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) return ['success' => 0, 'error' => "cURL $errno: $error"];
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return ['success' => 0, 'error' => '響應非合法 JSON: ' . $response];
}
return $data + ['error' => null];
}
private static function pushByHttpClient($urls, $options) {
$api = $options->plugin('BaiduSubmit')->api;
if (empty($api)) return ['success' => 0, 'error' => 'API 未配置'];
if (false === Typecho_Http_Client::get()) {
throw new Typecho_Plugin_Exception(_t('主機不支援 cURL 且未開啟 allow_url_fopen'));
}
$http = Typecho_Http_Client::get();
$http->setData(implode("\n", (array)$urls));
$http->setHeader('Content-Type', 'text/plain');
$result = $http->send($api);
return json_decode($result, true) + ['error' => null];
}
public static function send($contents, $widget) {
// ... 前置過濾、獲取 $permalink 同前文 ...
$options = Helper::options();
$urls = [$permalink]; // 亦可累積批次
// 嘗試 cURL,失敗回退 Http_Client
$result = self::pushByCurl($urls, $options);
if ($result['error'] && function_exists('curl_init') === false) {
$result = self::pushByHttpClient($urls, $options);
}
// 寫入日誌文件(生產建議寫入資料表)
$logLine = date('c') . "\t" . json_encode($result, JSON_UNESCAPED_UNICODE) . "\t" . $permalink . "\n";
@file_put_contents(__DIR__ . '/logs/push.log', $logLine, FILE_APPEND | LOCK_EX);
// 可選:拋出異常讓管理員感知,或靜默記錄
if ($result['error']) {
Typecho_Plugin::factory('Widget_Notice')->trigger($result['error']); // 假設有通知機制
}
}
plugins/BaiduSubmit/
├── Plugin.php
├── logs/
│ └── push.log # 每行:ISO8601時間\tJSON響應\tURL
└── README.md
日誌示例:
2024-05-20T14:30:01+08:00 {"remain":4998,"success":1,"error":null} https://example.com/archives/123/
2024-05-20T14:35:12+08:00 {"error":"cURL 6: Could not resolve host","success":0} https://example.com/archives/124/
在 config() 中加入「查看推送日誌」按鈕,或新增 action.php 讀取日誌文件以 JSON 輸出,配合前端 DataTables 實現分頁、篩選、匯出。
activate/deactivate/config/personalConfig。Typecho_Plugin::factory()->hook = [Class, method]。完整插件代碼已開源至 GitHub,歡迎 Star、Fork、提交 PR!