<?php
function baidu_push_config($domain){
    $cfgFile = __DIR__ . '/../config/baidu_push.php';
    $cfg = is_file($cfgFile) ? include $cfgFile : array();
    return $cfg[$domain] ?? null;
}

function baidu_push_urls($domain, $urls){
    $cfg = baidu_push_config($domain);
    if(!$cfg || empty($cfg['token'])) return array(false, '未配置token');
    $site = $cfg['site'] ?: $domain;
    $api = 'http://data.zz.baidu.com/urls?site=' . urlencode($site) . '&token=' . urlencode($cfg['token']);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, implode("\n", $urls));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    $ok = $res ? true : false;
    $logDir = __DIR__ . '/../cache/push';
    if(!is_dir($logDir)) @mkdir($logDir, 0777, true);
    $line = date('Y-m-d H:i:s') . "\t" . $domain . "\t" . implode(',', $urls) . "\t" . ($res ?: $err) . "\n";
    file_put_contents($logDir . '/baidu_push.log', $line, FILE_APPEND | LOCK_EX);
    return array($ok, $res ?: $err);
}
