トラックバック受信
<?php
//================================================ 設定
$FILE = './dat/traba.dat'; // トラックバック保存ファイル
$FILEMAX = 50; // 保存件数
$TEXTMAX = 300; // 文字数制限(全角)
//================================================ 関数
function readLog($FILE){
$log = array();
if(!($file = fopen($FILE, "r"))) {
return;
}
flock($file, LOCK_SH);
for($i = 0 ; !feof($file) ; $i++) {
$log[$i] = rtrim(fgets($file), "\n");
}
flock($file, LOCK_UN);
fclose($file);
if($log[count($log) - 1] === "") {
array_pop($log);
}
return $log;
}
function writeLog($FILE, $log, $filemax, $textmax) {
return("Error"); //サンプルにつき受信停止
if(!($_POST["blog_name"] and $_POST["title"] and $_POST["url"] and $_POST["excerpt"])) {
return("Error");
}
foreach($_POST as $key => $value) {
$_POST[$key] = mb_convert_encoding($_POST[$key], "Shift_JIS", "auto");
$_POST[$key] = preg_replace("/</", "<", $_POST[$key]);
$_POST[$key] = preg_replace("/>/", "$gt;", $_POST[$key]);
$_POST[$key] = preg_replace("/\s*\x0D\x0A\s*/", " ", $_POST[$key]);
$_POST[$key] = preg_replace("/\s+/", " ", $_POST[$key]);
if(strlen($_POST[$key]) > $textmax * 2) {
$_POST[$key] = substr($_POST[$key], 0, $textmax * 2);
$_POST[$key] .= "...";
}
}
$tm = date("U");
$data = join("\t", array($tm, $_POST['blog_name'], $_POST['title'], $_POST['url'], $_POST['excerpt'], ""));
array_unshift($log, $data);
while(count($log) > $filemax) {
array_pop($log);
}
if(!($file = fopen($FILE, "w"))) {
return;
}
flock($file, LOCK_EX);
fputs($file, join("\n", $log));
flock($file, LOCK_UN);
fclose($file);
return;
}
function printLog($log) {
for($i = 0 ; $i < count($log) ; $i++) {
list($tm, $name, $title, $url, $excerpt) = explode("\t", $log[$i]);
$tm = getdate($tm);
$tm = sprintf("%02d月%02d日%02d時%02d分", $tm[mon], $tm[mday], $tm[hours], $tm[minutes]);
echo "<p style=\"margin:5px;padding:3px;border:1px solid #333\">";
echo "【 $tm 】 $name<br>";
echo "<a href=\"$url\">$title</a><br>";
echo "$excerpt<br>";
echo "</p>\n";
}
}
function printRes($msg) {
header("Content-Type: text/xml;charset=UTF-8");
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<response>';
if($msg) {
echo '<error>1</error>';
echo '<message>Error</message>';
}
else {
echo '<error>0</error>';
}
echo '</response>';
}
//================================================ メインプログラム
$log = readLog($FILE);
if($_SERVER["REQUEST_METHOD"] === "POST") {
printRes(writeLog($FILE, $log, $FILEMAX, $TEXTMAX));
}
else {
echo '
<html>
<head>
<title>トラックバック受信</title>
</head>
<body>
<h1>トラックバック受信</h1>
トラックバック送信先 http://', $_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME'], '<br>
';
printLog($log);
echo '
</body>
</html>
';
}
?>
〔 実行する 〕