# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - RecommendPage Action Macro

    PURPOSE:
        This macro is used to recommend a page to an other wiki user.

    CALLING SEQUENCE:
        http://localhost:8080/WikiName?action=RecommendPage

    PROCEDURE:
       You get an input mask to enter the username of the one where you like to send the recommendation. This is then stored on a page named WikiName/RecommendedPage as an wiki itemlist with the link and the first five lines in plain text. At the end your user SIG is written.
       A new entry is always written on top of the page.

       If you don't enter a name the recommendation is done to your name

       Please remove the version number from the filename.

    MODIFICATION HISTORY:
        @copyright: 2005 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.
        Version: 1.3.4-1

        2005-04-19 : Version 1.3.4-2
                     acl line on top of recommendation is set for a valid user/RecommendedPage to
                     WikiName:admin,read,write,delete All:read,write
                     otherwise for All:read,write
                     If the page user/RecommendedPage already exist acl right given on that page are used.
                     output changed similiar to the search output.


"""

import string
from MoinMoin import config, wikiutil, user, wikiacl, search
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor

def ACLparse(request, body):
    """
      taken from wikiacl and simply changed to return acl text and body without acl definition
      renamed from parseACL to ACLparse
    """

    if not request.cfg.acl_enabled:
        return AccessControlList(request)


    acl_lines = []
    while body and body[0] == '#':
        # extract first line
        try:
            line, body = body.split('\n', 1)
        except ValueError:
            line = body
            body = ''

        # end parsing on empty (invalid) PI
        if line == "#":
            break

        # skip comments (lines with two hash marks)
        if line[1] == '#':
            continue

        tokens = line.split(None, 1)
        if tokens[0].lower() == "#acl":
            if len(tokens) == 2:
                args = tokens[1].rstrip()
            else:
                args = ""
            acl_lines.append(args)
    return acl_lines,body

def RecommendPage(request,pagename,username):
    if config.allow_subpages:
        delimiter = "/"
    else:
        delimiter = ""

    name=username + delimiter + "RecommendedPage"
    page = PageEditor(request,name)
    if request.user.may.write(name):


        thispage=Page(request,pagename)
        thisraw=thispage.get_raw_body()
        given_acl,thisraw = ACLparse(request, thisraw)



        if (len(thisraw) > 180):
           result=thisraw[0:180]+' ...'
        else:
           result=thisraw

        lines = result.split('\n')
        result='{{{'+string.join(lines,'}}} {{{')+'}}}'

        newtext=u" * %(pagename)s  '''%(about)s'''\n %(username)s\n" % {
             "pagename": '["'+pagename+'"]',
             "about":result,
             "username":"@SIG@"}

        rev = page.current_rev()
        if not page.exists() :
           if (user.getUserId(request, username) != None):
               acl="#acl %(username)s:admin,read,write,delete All:read,write\n" % {
                   "username":username}
           else:
               acl="#acl All:read,write\n"

           PageEditor.saveText(page,acl+newtext,rev)
        else:
            body = page.get_raw_body()
            given_acl,body = ACLparse(request, body)

            if len(string.join(given_acl,"")) > 0:
                acl="#acl %(given_acl)s \n" % {
                    "given_acl":string.join(given_acl,"\n")}
            else:
                acl=""

            PageEditor.saveText(page,acl+newtext+body,rev)

        msg="recommended to read %(pagename)s to %(username)s" % {
            "pagename": pagename,
            "username":username}

        Page(request, pagename).send_page(request, msg=msg)
    else:
        Page(request, pagename).send_page(request, msg="You are not allowed to recommend pages")


def execute(pagename, request):


    _ = request.getText
    actname = __name__.split('.')[-1]


    if request.user.may.read(pagename):

        thispage=Page(request,pagename)

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

            username=request.form.get('username', [u''])[0]
            if (len(username.strip()) == 0):
                username=request.user.name
            return RecommendPage(request,pagename,username)

        formhtml = '''
<form method="post" action="">
<strong>%(querytext)s</strong>
<input type="hidden" name="action" value="%(actname)s">
<input type="submit" name="button" value="%(button)s">
<input type="hidden" name="ticket" value="%(ticket)s">
<p>
Username (WikiName)<br>
<input type="text" name="username" size="30" maxlength="40">
</form>''' % {
    'querytext': 'Recommend page to',
    'actname': 'RecommendPage',
    'ticket' :wikiutil.createTicket(),
    'button': 'Recommend'}

        return thispage.send_page(request, msg=formhtml)


