# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ApprovePage action

    This action allows you to delete a page.

    @copyright: 2005 by Robert Penz <robert.penz@outertech.com>
    @license: GNU GPL, see COPYING for details.
"""

import os
from MoinMoin import config, wikiutil
from MoinMoin.PageEditor import PageEditor


def execute(pagename, request):
    _ = request.getText
    actname = __name__.split('.')[-1]
    # Create a page editor that does not do edior backups, becuase
    # approve generate "approved" version, of the page.
    page = PageEditor(request, pagename, do_editor_backup=0)

    # be extra paranoid in dangerous actions
    if actname in request.cfg.actions_excluded \
            or not request.user.may.approve(pagename):
        return page.send_page(request,
            msg = _('You are not allowed to approve this page.'))

    # check whether page exists at all
    if not page.exists():
        return page.send_page(request,
            msg = _('This page is already deleted or was never created!'))

    # check whether the user clicked the approve button
    if request.form.has_key('button') and request.form.has_key('ticket') and request.form.has_key('revision'):
        # check whether this is a valid approve request (make outside
        # attacks harder by requiring two full HTTP transactions)
        if not wikiutil.checkTicket(request.form['ticket'][0]):
            return page.send_page(request,
                msg = _('Please use the interactive user interface to approve pages!'))

	# check if the revision changed
	if int(request.form['revision'][0]) != page.getRevList()[0]:
	    return page.send_page(request,
		msg = _('The pages has changed, cannot simply approve the new revision!'))

        # Approve the page
	# in the first colum is the revision and in the second the username
	open(os.path.abspath(os.path.join(request.page.getPagePath(), "approved")),"a").write("%08d\t%s\n" % (page.getRevList()[0], request.user.name))

        return page.send_page(request,
                msg = _('Page "%s" has been successfully approved!') % (pagename,))

    # send approval form
    ticket = wikiutil.createTicket()
    querytext = _('Really approve this page?')
    button = _('Approve')
    revision = page.getRevList()[0]
    #comment_label = _("Optional reason for the deletion")

    # TODO: this form suck, redesign like RenamePage
    formhtml = '''
<form method="post" action="">
<strong>%(querytext)s</strong>
<input type="hidden" name="action" value="%(actname)s">
<input type="hidden" name="ticket" value="%(ticket)s">
<input type="hidden" name="revision" value="%(revision)s">
<input type="submit" name="button" value="%(button)s">
<p>
</form>''' % {
    'querytext': querytext,
    'actname': actname,
    'ticket': ticket,
    'button': button,
    'revision': revision
}

    return page.send_page(request, msg=formhtml)

