はてなダイアリーAtomPubを使ってダイアリー書きこみ

 はてなダイアリーAtomAPIで新規エントリーできるようになっていたので試してみる。といってもmixi日記投稿用APIを使ってPHPからmixi日記にポスト ::: creazy photographをいじっただけ。

<?php
#美乳
error_reporting(E_ALL);
require_once 'HTTP/Request.php';

//USER infomation
$id        = 'doroyamada';
$pass        = 'nanchara';
$account	= 'doroyamada';	#サブアカウントの時は変更
$title = "テストタイトル";
$body = "テストの本文";

// WSSE Authentication
$nonce       = pack('H*', sha1(md5(time().rand())));
$created     = date('Y-m-d\TH:i:s\Z');
$digest      = base64_encode(pack('H*', sha1($nonce . $created . $pass)));
$wsse_text   = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"';
$wsse_header = sprintf($wsse_text, $id, $digest, base64_encode($nonce), $created);

$url         = "http://d.hatena.ne.jp/$account/atom/blog";

//post
$post_data =
'<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://purl.org/atom/ns#">'.
"<title>$title</title>".
'<content type="text/plain">'.
"$body
</content>
<updated></updated>
</entry>";

$request = new HTTP_Request($url);
$request->setMethod(HTTP_REQUEST_METHOD_POST);
$request->addHeader('X-WSSE', $wsse_header);
$request->setBody($post_data);

if (PEAR::isError($request->sendRequest())) {
    die('request failed');
}

$res_code = $request->getResponseCode();
$res_body = $request->getResponseBody();
echo "$res_code\n";
echo $res_body;
?>

 元は

$nonce = pack('H*', sha1(md5(time().rand().posix_getpid())));

となっていたけど、posix_getpid()がWINDOWSでは使えないので削除してみた。


 文字コードUTF-8に変換するとかhtmlエスケープするとかしておいたほうがよさそうだけど、それはそのうち。
 これでmoblogプログラムをシンプルにできるかも。というか、そのうちPEAR Services_Hatenaに取りこまれるだろうから、本格的なつくりかえはそれからかな。
 北海道ツーリングにいく前にmoblogプログラムをいじっていて、「はてなダイアリーってatomで書きこめんのかいな?」とかいろいろ調べたんだけど、ツーリング中に発表されるとは。