上一篇完成了插件接口掛載,本篇進入核心業務邏輯:在文章發布瞬間,提取文章永久鏈接並準備推送給百度站長平台。我們將逐步拆解 send() 方法的實現細節。
class BaiduSubmit_Plugin implements Typecho_Plugin_Interface {
public static function activate() { /* 掛載代碼同上 */ }
public static function deactivate() { /* 解除掛載 */ }
public static function config(Typecho_Widget_Helper_Form $form) {
$form->addInput(new Typecho_Widget_Helper_Form_Element_Text(
'api', null, null, _t('百度推送 API 接口'), '請登錄百度站長平台獲取'
));
}
public static function personalConfig(Typecho_Widget_Helper_Form $form) {}
/** 核心回調:文章/頁面發布完成時自動觸發 */
public static function send($contents, $widget) {
// 1. 過濾非公開/定時文章
if ('publish' !== $contents['visibility'] || $contents['created'] > time()) {
return;
}
// 2. 讀取插件設定
$options = Helper::options();
$api = $options->plugin('BaiduSubmit')->api;
if (empty($api)) return; // 未配置 API
// 3. 判斷內容類型並生成永久鏈接
$type = $contents['type']; // 'post' 或 'page'
$routeExists = (NULL !== Typecho_Router::get($type));
$pathInfo = $routeExists ? Typecho_Router::url($type, $contents) : '#';
$permalink = Typecho_Common::url($pathInfo, $options->index);
// 4. 此處已拿到 $permalink,下一步將發送給百度
// self::pushToBaidu($permalink, $api); // 下一篇實現
}
}
$contents['visibility']:'publish'(公開)、'hidden'(隱藏)、'private'(私密)。$contents['created']:文章發布時間戳,大於當前時間表示定時發布,暫不推送。Helper::options()->plugin('插件名')->字段名 是 Typecho 讀取插件設定的標準方式。
Typecho 採用路由系統:
Typecho_Router::get($type) 檢查路由是否存在(防止自定義路由導致 404)。Typecho_Router::url($type, $contents) 根據路由規則生成相對路徑(如 /archives/123/)。Typecho_Common::url($pathInfo, $options->index) 拼接站點根網址,得到完整 URL。此法相容各種偽靜態規則、子目錄部署、多站點等場景。
因同時掛載 Post_Edit 與 Page_Edit,$contents['type'] 會自動區分 'post'/'page',路由系統自動套用對應模板規則。
fastcgi_finish_request() 後台執行,避免阻塞用戶發布響應。下一篇將實現 pushToBaidu():使用 cURL 與 Typecho 內建 Typecho_Http_Client 兩種方式發送請求、處理響應、寫入日誌文件。並討論如何優化插件結構、加入管理後台推送記錄查看功能。