# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - Queue changes for review

    Queue changed pages edited by unprivileged users for review by the
    ApproveChanges action.

    @copyright: 2011 Paul Boddie <paul@boddie.org.uk>
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin.PageEditor import PageEditor
from MoinMoin.events import PagePreSaveEvent, Abort
from ApproveChangesSupport import *

def handle_presave(event):
    request = event.request
    _ = request.getText

    queued_changes_page = get_queued_changes_page(request)

    pagename = event.page_editor.page_name
    body = event.new_text

    # Saving into queues has to be permitted or the mechanism will keep trying
    # to save into a queue of the specified page.

    if is_queued_changes_page(request, pagename):

        # Test the integrity of the page in order to prevent direct replacement
        # of the page. Reviewers can change the page as they please.

        if is_reviewer(request) or is_queued_changes_user(request):
            return None
        else:
            return Abort(_("Queued changes may not be edited."))

    # For normal pages, the user has to be approved. Otherwise, the page will be
    # saved into a queue. If the save operation occurs as part of an approval
    # action, however, the effective user will be able to save the page.

    elif not request.action == "ApproveChanges" and not is_approved(request):

        # Save the page in the queue.

        new_page = PageEditor(request, "%s/%s" % (pagename, queued_changes_page))

        # Add an ACL to prevent normal users from seeing the page anywhere.
        # Add a parent revision to the page.

        directives = [
            get_access_control_directive(request),
            get_parent_revision_directive(request, pagename),
            get_user_directive(request)
            ]

        body = add_directives(body, directives)

        username = request.user.name
        comment = (username or _("anonymous")) + " : " +  _("Queued page edit")

        try:
            # Switch user in order to save a page with an ACL.

            user = request.user
            request.user = get_user_for_saving(request)
            try:
                new_page.saveText(body, 0, comment=comment)
            finally:
                request.user = user
            
        except PageEditor.Unchanged:
            pass

        # Abort the page save operation.

        return Abort(_("Your changes have been queued for approval."))

    return None

def handle(event):
    if isinstance(event, PagePreSaveEvent):
        return handle_presave(event)

# vim: tabstop=4 expandtab shiftwidth=4
