はてなダイアリーAtomPubをPHPで使う
はてなダイアリーAtomPubを使ってみた。PEARの中にもServices_Hatenaや、Do You PHP はてなの"mixiのあしあとAPI"の使い方を参照にしつつ。
Service_Hatenaはダイアリーの対応はまだの様だったので勉強がてら、PHP5専用で一から書いてみた。
<?php require_once('HTTP/Request.php'); class HatenaDiaryStore{ private $hatenaid; private $hatenapw; public function __construct(){ } public function __set($name, $value){ switch($name){ case "hatenaid": $this->hatenaid = $value; break; case "hatenapw": $this->hatenapw = $value; break; } } public function postNewEntry($title, $body){ $reqxml = sprintf('<?xml version="1.0" encoding="utf-8"?><entry xmlns="http://purl.org/atom/ns#"><title>%s</title><content type="text/plain">%s</content></entry>', $title, $body ); $this->postNewEntryWithXml($reqxml); } public function postNewEntryWithXml($xml){ $url = sprintf("http://d.hatena.ne.jp/%s/atom/blog", $this->hatenaid); // Hatena diary collection URL $wsseval = $this->getWsseHeaderValue(); // HTTP Request start. $httpreq = new HTTP_Request($url); $httpreq->setMethod(HTTP_REQUEST_METHOD_POST); $httpreq->addHeader('X-WSSE', $wsseval); $httpreq->addRawPostData($xml); if (PEAR::isError($httpreq->sendRequest())) { throw new Exception("http request error"); } if($httpreq->getResponseCode() != 201){ throw new Exception("bad request published"); } } private function getWsseHeaderValue(){ $created = gmdate('Y-m-d\TH:i:s\Z'); $nonce = base64_encode(sha1(mt_rand())); $pwdigest = base64_encode(pack('H*', sha1($nonce.$created.$this->hatenapw))); $xwsseval = sprintf( 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->hatenaid, $pwdigest, $nonce, $created ); return $xwsseval; } } $title = "てすと"; $body = <<<EOF 気分転換でごにょごにょ中。あは。 -テスト...テスト...ただいまテスト... -RSSリーダ購読されている方、ご了承ください。 EOF; $hatena = new HatenaDiaryStore(); $hatena->hatenaid = "hideack"; $hatena->hatenapw = "*******"; $hatena->postNewEntry($title, $body); ?>
意外とあっさり書けてびっくり。
先日から投稿してる「今日のひとことたち」は、はてなハイクのフィードを一日の終わり近くに読み取って、
このスクリプトで自動的に投稿させていたり...。ま、他の方法でごにょごにょしてもできそうですが。