# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - "trackback" action
.

    @copyright: 2004 by Jos Yule <jos@theorganization.net>
    @license: GNU GPL, see COPYING for details.
"""

import sys
import os
from MoinMoin import config, util, wikiutil
from MoinMoin.Page import Page
from xml.dom.minidom import parse, Document
from time import strftime


def execute(pagename, request):

    if config.allow_trackback:
        try:
            resource = None  # so what is it?
            if os.environ["REQUEST_URI"].startswith(os.environ["SCRIPT_NAME"]):
                if os.environ.has_key("PATH_INFO"):
                    resource = os.environ["PATH_INFO"]
                else:
                    tbError("You didn't say what resource you wanted to ping.")
            else:
                resource = os.environ["REQUEST_URI"]
            if resource.endswith("index.html"): resource = resource[:-10]


            # Load existing TrackBack content.
            resourceUri = "http://%s%s" % (os.environ["SERVER_NAME"], resource)
            tbUri = "http://%s%s%s" % (os.environ["SERVER_NAME"], os.environ["SCRIPT_NAME"], resource)
            dataFilename = "%s.xml" % resource[1:].replace(os.sep, "_").replace(".", "_")
            #dataFile = join(dirname(os.environ["SCRIPT_FILENAME"]), "data", dataFilename)
            dataFile = config.data_dir + '/trackback/' + dataFilename

            tb_data = None  # so what is it?
            try:
                tb_data = parse(dataFile)
            except IOError:
                # Make a new document.
                tb_data = Document()

                rss = tb_data.createElement("rss")
                tb_data.appendChild(rss)
                rss.setAttribute("version", "0.91")

                channel = tb_data.createElement("channel")
                rss.appendChild(channel)

                chTitle = tb_data.createElement("title")
                chTitle.appendChild(tb_data.createTextNode("TrackBack for %s" % (resourceUri)))
                channel.appendChild(chTitle)

                chLink = tb_data.createElement("link")
                chLink.appendChild(tb_data.createTextNode(resourceUri))
                channel.appendChild(chLink)

                chDesc = tb_data.createElement("description")
                chDesc.appendChild(tb_data.createTextNode("What some people have pung me with."))
                channel.appendChild(chDesc)

                chLang = tb_data.createElement("language")
                chLang.appendChild(tb_data.createTextNode("en-us"))
                channel.appendChild(chLang)

            tb_channel = tb_data.documentElement.firstChild


            # Pinging or fetching?
            #if "POST" == os.environ["REQUEST_METHOD"]:
            # Pinging.	

            ping = request.form #cgi.FieldStorage()

            # Add this ping.
            pingItem = tb_data.createElement("item")

            if not ping.has_key("url"):
                raise KeyError, "You need to include the URL for this trackback"

            if ping.has_key("title"):
                itemTitle = pingItem.appendChild(tb_data.createElement("title"))
                itemTitle.appendChild(tb_data.createTextNode(ping["title"][0]))
            if ping.has_key("url"):
                itemLink = pingItem.appendChild(tb_data.createElement("link"))
                itemLink.appendChild(tb_data.createTextNode(ping["url"][0]))
            if ping.has_key("excerpt"):
                excerpt = ping["excerpt"][0]
                if 255 < len(excerpt):
                    excerpt = "%s..." % excerpt[:252]
                itemDesc = pingItem.appendChild(tb_data.createElement("description"))
                itemDesc.appendChild(tb_data.createTextNode(excerpt))
            if ping.has_key("blog_name"):
                itemBN = pingItem.appendChild(tb_data.createElement("blogName"))
                itemBN.appendChild(tb_data.createTextNode(ping["blog_name"][0]))

            itemDate = tb_data.createElementNS("http://purl.org/dc/elements/1.1/", "date")
            itemDate.appendChild(tb_data.createTextNode(strftime("%Y-%m-%dT%H:%MZ")))
            pingItem.appendChild(itemDate)

            tb_channel.appendChild(pingItem)

            # Write it back out.
            xmlout = open(dataFile, "w")
            xmlout.write(tb_data.toxml())
            xmlout.close()

            request.write( """Content-type: text/xml

<?xml version="1.0"?>
<response>
    <error>0</error>
</response>""")
        except Exception, x:
           
            request.write("""Content-type: text/xml

<?xml version="1.0"?>
<response>
    <error>1</error>
    <message>Error: %s</message>
</response>""" % (x,))
    else:
        request.write("""Content-type: text/xml

<?xml version="1.0"?>
<response>
    <error>1</error>
    <message>Error: Trackback disabled</message>
</response>""" )

    request.no_closing_html_code = 1
    return
