WordPress の更新内容を mixi へ投稿するスクリプト RSS2mixi with MagpieRSS

ブログのエントリーをmixi日記に自動投稿する「RSS2mixi」 ::: creazy photograph で配布されているスクリプト RSS2mixi をちょっと改造して本文から画像データを抜き出せるようにしてみました。
元スクリプトでは description を見ているためか、WordPress の吐く RSS では画像を使っていても、そこまでスクリプトが読んでくれないので ((これは SimpleXML の制限ぽいですね。PHP での SimpleXML 処理 )) どうにかこうにかしてみようとしたのが、MagpieRSS を用いて RSS をパースするという方法。

他ライブラリを使うのでシンプルではなくなるのですが、もともと便利なスクリプトだし、どうせ自前のサーバで動かすので、ちょっと富豪的にしてみました。

元スクリプトは PHP5 の SimpleXML を使っていますが、その部分を MagpieRSS にお任せしているので、PHP4 でも動くかもしれませんね。

MagpieRSS 導入方法

MagpieRSS のファイル群は RSS2mixi と同じ場所に magpierss というディレクトリを作成して保存してあります。

rss_fetch.inc を直接書き換え MAGPIE_OUTPUT_ENCODING の値を 'UTF-8’ にしてあります。

その他、環境に応じてキャッシュディレクトリなどの書き換えを行います。

RSS2mixi の使い方

設定はスクリプト自体を書き換え、フィードの URL や mixi へのログイン情報、ID などを記入します。

$posted_file および $img_tmp_file で指定するファイルは、予め作成しておくのが良いようです。

設定が完了したら cron で定期的にスクリプトを実行すれば、新規に投稿されたエントリの内容を mixi に複製してくれるはずです。

ソースコード

<?php
/**
 * RSS2mixi with MagpieRSS
 * 
 * RSS読み込んでmixi日記に自動投稿します。
 * 
 * original script @author  yager <yager&#91; at &#93;creazy.net>
 * http://creazy.net/2008/08/rss2mixi_php.html
 *
 * custmized by yuuichi <u1 &#91; at &#93; u-1.net>
 */
mb_language("japanese");
mb_internal_encoding("UTF-8");

require_once 'Services/MixiAPI/Diary.php';
require_once 'Services/MixiAPI/Image.php';
require_once 'Services/MixiAPI/Factory.php';
require_once './magpierss/rss_fetch.inc';
error_reporting(E_ALL);

//------------------------------------------------------------
// Settings
//------------------------------------------------------------
/**
 * RSS設定
 */
$rss  = ''; //ブログのRSS

/**
 * mixi設定
 */
$user = ''; //ログインID
$pass = ''; //パスワード
$id   = ''; //mixi ID

/**
 * 送信済みエントリーをストアしておくためのデータファイル
 * @memo 別のファイル名で設置した場合はここを修正してください。
 *       書き込み権限を与えておく事を忘れずに。
 *       chmod 666 {データファイル名}
 */
$posted_file  = './rss2mixi.link.database.txt';
$img_tmp_file = './rss2mixi_tmp_file.jpg';

//------------------------------------------------------------
// Get data
//------------------------------------------------------------
// 登校済みのURLのデータファイルを読み込み
$posted_links = explode("\n",file_get_contents($posted_file));

// MagpieRSSによるRSSの展開
$root_ = fetch_rss($rss);
$title = $root_->channel['title'];
$items_ = array();
foreach ( $root_->items as $item ) {
    $items_[] = $item;
}

rsort($items_);

//------------------------------------------------------------
// Post mixi
//------------------------------------------------------------
foreach ( $items_ as $item ) {
  // すでにポスト済みの記事はスキップ
  if ( in_array($item['link'],$posted_links) ) continue;
  $title       = $item['title'];
  $title       = "ブログを更新しました : ".$title;
  $link        = $item['link'];
  $description = $item['description'];
  $fulltext    = $item['content']['encoded'];

    // 添付画像URL取得
    $matches = array();
    if ( preg_match('/<img.*?src=&#91;\'\"&#93;(.*.jpg)&#91;\'\"&#93;.*?>/i',$fulltext,$matches) ) {
        // JPEGのIMGタグがあったら添付画像として
        $photo_url = $matches[1];
        echo $photo_url . "<br />\n";
    }

    // 本文の成形
    $description =
		preg_replace( // 画像タグはカメラアイコン+URL
			'/<img.*?src=&#91;\'\"&#93;(.*?)&#91;\'\"&#93;.*?>/ie'
			,"'([m:133]$1)'"
			,$description
		);
    $description =
		preg_replace( // リンクタグはPCアイコン+TinyURL
			'/<a.*?href=&#91;\'\"&#93;(.*?)&#91;\'\"&#93;.*?>(.*?)<\/a>/ie'
			,"'([m:196]$2:'.tinyurl('$1').')'"
			,$description
		);
    $description = strip_tags($description);
    $description = $description."\n\n".$link;

    // debug
    echo $title . "<br />\n";
    echo $link . "<br />\n";
    echo "<pre>".$description."</pre><hr />\n";

    // mixiにポスト
    $diary   = new Services_MixiAPI_Diary($title, $description);
    if ( $photo_url ) {
        if ( $fp = fopen($img_tmp_file,"w") ) {
            fwrite($fp,file_get_contents($photo_url));
            fclose($fp);
        }
        $diary->setImage(new Services_MixiAPI_Image($img_tmp_file));
    }
    $service = Services_MixiAPI_Factory::getInstance(
                   Services_MixiAPI_Factory::API_MODE_POSTDIARY,
                   $user, $pass, $id);
    $service->setDiary($diary);
    $service->execute();

    // ポスト済みに登録
    if ( $fp = fopen($posted_file,"a") ) {
        fwrite($fp,$item['link']."\n");
        fclose($fp);
    }

}

/**
 * TinyURL変換関数
 * @param  String $url 変換したいURL
 * @return String 変換後のTinyURL
 */
function tinyurl($url) {
    $tiny = file_get_contents('http://tinyurl.com/api-create.php?url='.urlencode($url));
    return $tiny;
}
?>

参考リンク

以下のURLを参考にスクリプトを改造させていただきました。感謝。