<?php
/**
 * Trackback モジュール
 * 参考
 *   http://lowlife.jp/yasusii/stories/8.html
 */
require_once 'Zend/Controller/Action.php';

class TrackbackController extends Zend_Controller_Action
{
    public function indexAction()
    {
    }
    
    public function pingAction()
    {
        $request = $this->getRequest();
        $id = intval($request->getParam('id'));
        
        $mode = '';
        if (isset($_GET['__mode'])) { $mode = $_GET['__mode']; }
        
        if ($mode == 'rss') {
            $this->rss_mode($id);
        }
        else {
            $errorMessage = $this->handlePing($id);
            $this->xmlResponse($errorMessage);
        }
    }
    
    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    private function handlePing($id = 0)
    {
        global $db;
        
        $errorMessage = '';
        //$id = intval($_POST['id']);
        $title = h(e($_POST['title']));
        $excerpt = h(e($_POST['excerpt']));
        $url = h(e($_POST['url']));
        $blog_name = h(e($_POST['blog_name']));
        $created = date('Y-m-d H:i:s');
        if ($title == '') { $title = $url; }
        
        $fp = fopen(BASE_PATH . 'private/tb.txt', 'a');
        if ($fp) {
            fprintf($fp, "%s\n", $title);
            fprintf($fp, "%s\n", $excerpt);
            fprintf($fp, "%s\n", $url);
            fprintf($fp, "%s\n", $blog_name);
            fclose($fp);
        }
        
        if ($id == 0) {
            return 'Trackback ID is missing';
        }
        if (!$url) {
            return 'URL is missing (url)';
        }
        
        $sql = "SELECT id FROM Platy_Content_Base WHERE id={$id}";
        $rows = $db->fetchAll($sql);
        if (!count($rows)) {
            return 'Trackback ID is missing';
        }
        
        $sql = "SELECT url FROM Platy_CExt_Trackback WHERE id={$id} AND url='{$url}'";
        $rows = $db->fetchAll($sql);
        if (count($rows)) {
            // update
            $sql = "UPDATE Platy_CExt_Trackback "
                 . "SET title='{$title}', excerpt='{$excerpt}', blog_name='{$blog_name}', created='{$created}' "
                 . "WHERE id={$id} AND url='{$url}'";
            try {
                $db->query($sql);
            }
            catch (Exception $e) {
                $fp = fopen(BASE_PATH . 'private/tb.txt', 'a');
                if ($fp) {
                    fprintf($fp, "%s\n", $sql);
                    fclose($fp);
                }
            }
        }
        else {
            $sql = "INSERT INTO Platy_CExt_Trackback("
                 . "id, title, excerpt, url, blog_name, created) VALUES("
                 . "{$id},'{$title}', '{$excerpt}', '{$url}', '{$blog_name}','{$created}')";
            try {
                $db->query($sql);
            }
            catch (Exception $e) {
                $fp = fopen(BASE_PATH . 'private/tb.txt', 'a');
                if ($fp) {
                    fprintf($fp, "%s\n", $sql);
                    fclose($fp);
                }
            }
        }
        
    }
    
    private function xmlResponse($errorMessage = '')
    {
        header('Content-Type: text/xml');
        echo "<","?xml version='1.0' encoding='UTF-8'?",">\n";
        echo "<response>\n";
        if ($errorMessage) 
            echo "\t<error>1</error>\n\t<message>",h($errorMessage),"</message>\n";
        else
            echo "\t<error>0</error>\n";
        echo "</response>";
        exit;
    }
    
    private function rss_mode($id = 0)
    {
        global $db;
        
        header('Content-Type: text/xml');
        echo "<","?xml version='1.0' encoding='UTF-8'?",">\n";
        echo "<response>\n";
        
        $sql = "SELECT id, title, summary FROM Platy_Content_Base WHERE id={$id}";
        $row = $db->fetchRow($sql);
        if (!count($row)) {
            echo '<error>1</error>' . "\n";
            echo '</response>' . "\n";
            return;
        }
        $title = $row['title'];
        $description = $row['summary'];
        
        echo '<error>0</error>' . "\n";
        echo '<rss version="0.91"><channel>' . "\n";
        echo '<title>' . $title . '</title>' . "\n";
        
        $content = getContentFromId($id);
        echo '<link>' . BASE_FULL_URL . $content['url'] . '</link>' . "\n";
        
        echo '<description><![CDATA[' . $description . ']]></description>' . "\n";
        echo '<language>ja</language>' . "\n";
        
        $sql = "SELECT title, url, excerpt FROM Platy_CExt_Trackback WHERE id={$id} ORDER BY created DESC";
        $rows = $db->fetchAll($sql);
        foreach ($rows as $row) {
            echo '<item>' . "\n";
            echo '<title>' . $row['title'] . '</title>' . "\n";
            echo '<link>' . $row['url'] . '</link>' . "\n";
            echo '<description>' . $row['excerpt'] . '</description>' . "\n";
            echo '</item>' . "\n";
        }
        echo '</channel>' . "\n";
        echo '</rss></response>';
    }
}
?>