Beispiel #1
0
def main():
    args = sys.argv

    myusername = ''
    if (len(args) > 1) and (args[1] == '-u'):
        args.pop(1)
        myusername = args.pop(1)

    if len(args) - 1 not in (2, 3) or args[1] not in ('l', 'i'):
        print >> sys.stderr, """MoinMoin Package Installer v%(version)i

%(myname)s action packagefile [request URL]

action      - Either "l" for listing the script or "i" for installing.
packagefile - The path to the file containing the MoinMoin installer package
request URL - Just needed if you are running a wiki farm, used to differentiate
              the correct wiki.

Example:

%(myname)s i ../package.zip

""" % {
            "version": MAX_VERSION,
            "myname": os.path.basename(args[0])
        }
        raise SystemExit

    packagefile = args[2]
    if len(args) > 3:
        request_url = args[3]
    else:
        request_url = None

    # Setup MoinMoin environment
    from MoinMoin.web.contexts import ScriptContext
    request = ScriptContext(url=request_url)
    if myusername:
        request.user = user.User(request, auth_username=myusername)

    package = ZipPackage(request, packagefile)
    if not package.isPackage():
        print "The specified file %s is not a package." % packagefile
        raise SystemExit

    if args[1] == 'l':
        print package.getScript()
    elif args[1] == 'i':
        if package.installPackage():
            print "Installation was successful!"
        else:
            print "Installation failed."
        if package.msg:
            print package.msg
 def parse_wiki_markup(self, formatter, text):
     """
     Return result of parsing previously escaped text by MoinMoin wiki parser.
     Only allowed and therefore unescaped special command is '<<BR>>'.
     """
     unescaped_text = text.replace('&lt;&lt;BR&gt;&gt;', '<<BR>>')
     request = ScriptContext()
     buf = StringIO.StringIO()
     request.redirect(buf)
     wiki_parser = text_moin_wiki.Parser(unescaped_text, request)
     wiki_parser.format(formatter)
     return buf.getvalue().replace('\n', ' ')
 def parse_wiki_markup(self, formatter, text):
     """
     Return result of parsing previously escaped text by MoinMoin wiki parser.
     Only allowed and therefore unescaped special command is '<<BR>>'.
     """
     unescaped_text = text.replace('&lt;&lt;BR&gt;&gt;', '<<BR>>')
     request = ScriptContext()
     buf = StringIO.StringIO()
     request.redirect(buf)
     wiki_parser = text_moin_wiki.Parser(unescaped_text, request)
     wiki_parser.format(formatter)
     return buf.getvalue().replace('\n', ' ')
Beispiel #4
0
def execute(pagename, request):
    """                                                                         
    Handle action=IntraFarmCopy
    """

    if not request.user.may.read(pagename):
        Page(request, pagename).send_page()
        return

    # Which local farm wiki - assume team for now                               
    to_wiki_url = COPY_TO_WIKI_URL 
    # New page name                                               
    to_wiki_pagename = '%s%s' % (COPY_TO_PREFIX, pagename)

    # create page at local wiki if it doesn't exist                             
    to_request = ScriptContext(to_wiki_url)
    # login this user remotely
    to_uid = user.getUserId(to_request, request.user.name)
    to_user = user.User(to_request, id=to_uid, name=request.user.name, password=request.user.password, auth_method="moin")
    to_request.user = to_user

    try:
        page = Page(to_request, to_wiki_pagename)
    except:
        return action_error(u'Error accessing destination page')
    if not page.exists():
        pe = PageEditor(to_request, to_wiki_pagename)
        # make initial revision pointer to original                             
        try:
            pe.saveText(u'[[%s:%s]]' % (request.cfg.interwikiname, pagename), 0, comment="Automated IntraFarmCopy pointing to original page")
        except pe.Unchanged:
            return action_error(u'Could not save initial page')
	except pe.AccessDenied:
            return action_error(u'Could not acquire credentials')
        # make next revision content of this page
        try:
            pe.saveText(Page(request, pagename).get_raw_body(), 0, comment="Automated IntraFarmCopy importing contents from original page at [[%s:%s]]" % (request.cfg.interwikiname, pagename))
        except pe.Unchanged:
            return action_error(u'Could not save destination page text')
	# send attachments over
        attachments = AttachFile._get_files(request, pagename)
	for attachname in attachments:
	    filename = AttachFile.getFilename(request, pagename, attachname)
	    if not os.path.isfile(filename):
	        continue
	    to_filename = AttachFile.getFilename(to_request, to_wiki_pagename, attachname)
	    shutil.copyfile(filename, to_filename)
	    AttachFile._addLogEntry(to_request, 'ATTNEW', to_wiki_pagename, attachname) 
        # redirect user to view new page in other wiki                          
        request.http_redirect('%s%s' % (to_wiki_url, to_wiki_pagename))
	return
    else:
	return action_error(u'Destination page already exists!')
def main():
    args = sys.argv

    myusername=''
    if (len(args) > 1) and (args[1] == '-u'):
	args.pop(1)
	myusername = args.pop(1)

    if len(args)-1 not in (2, 3) or args[1] not in ('l', 'i'):
        print >> sys.stderr, """MoinMoin Package Installer v%(version)i

%(myname)s action packagefile [request URL]

action      - Either "l" for listing the script or "i" for installing.
packagefile - The path to the file containing the MoinMoin installer package
request URL - Just needed if you are running a wiki farm, used to differentiate
              the correct wiki.

Example:

%(myname)s i ../package.zip

""" % {"version": MAX_VERSION, "myname": os.path.basename(args[0])}
        raise SystemExit

    packagefile = args[2]
    if len(args) > 3:
        request_url = args[3]
    else:
        request_url = None

    # Setup MoinMoin environment
    from MoinMoin.web.contexts import ScriptContext
    request = ScriptContext(url=request_url)
    if myusername:
        request.user = user.User(request, auth_username=myusername)

    package = ZipPackage(request, packagefile)
    if not package.isPackage():
        print "The specified file %s is not a package." % packagefile
        raise SystemExit

    if args[1] == 'l':
        print package.getScript()
    elif args[1] == 'i':
        if package.installPackage():
            print "Installation was successful!"
        else:
            print "Installation failed."
        if package.msg:
            print package.msg
Beispiel #6
0
    def __init__(self, url = '', pybloxsom_config = None):
#{{{Init method for the MoinMoinEntryParser class
        '''
        init method for MoinMoinEntryParser Object
        '''
        self.PREFORMATTER_ID = PREFORMATTER_ID

        # New MoinMoin request
        self.request = MoinMoinScriptContext(url)
        self.logger = PyblosxomTools.get_logger()
        self.url = url
        self.entryfile=''
        self.entrytitle = ''
        self.page_name = ''

        # Initial parser configuration if config is usable
        if pybloxsom_config is not None:
            self.pybloxsom_config = pybloxsom_config
            # Use moinmoin cache
            self.request.cacheable = self.request.use_cache = self.pybloxsom_config.get('moinmoin_use_cache', '0') == '1'
            #self.request.cacheable = self.request.use_cache = False

            # moinmoin encoding 
            self.output_charset = self.pybloxsom_config.get('blog_encoding', 'utf-8')
        # We don't have the config, using default
        else:
            self.request.cacheable = False
            self.output_charset = 'utf-8'
#}}}
        self.logger.debug('Moinmoin parser Object created')
Beispiel #7
0
def createpage(groupname, groupmemberlist):

    request = ScriptContext('http://*****:*****@example.com')
    request.user = user

    # Group name added at the end
    groupname = groupname + 'Group'
    pe = PageEditor(request, groupname)

    #memberlist =['Tom','Harry','Steph','Rama']
    memberlist = groupmemberlist
    mystring = ' * '
    mynewlist = ['#acl ItGroup:read,write,delete,revert,admin Known: All:'
                 ] + [mystring + x for x in memberlist]

    mynewlist = '\n'.join(mynewlist)
    try:
        pe.saveText(mynewlist, 0)

    except pe.Unchanged:
        print "You did not change the page content, not saved!"
Beispiel #8
0
def newday (Wiki, ParentPage, TemplatePage, NewPage, Editor, UidName, GidName):

    from os import seteuid,setegid
    from pwd import getpwnam
    from grp import getgrnam

    uid = getpwnam(UidName).pw_uid
    gid = getgrnam(GidName).gr_gid

    setegid(gid)
    seteuid(uid)

    from MoinMoin.PageEditor import PageEditor
    from MoinMoin.Page import Page
    from MoinMoin.user import getUserId, User
    from MoinMoin.web.contexts import ScriptContext

    PageName = "%s/%s" % (ParentPage,NewPage)

    RequestPage = ScriptContext(Wiki, PageName)
    UserId = getUserId(RequestPage, Editor)
    RequestPage.user = User(RequestPage, UserId)

    Editor = PageEditor(RequestPage, PageName)
    Dummy, Revision, Exists = Editor.get_rev()

    if not Exists:

        RequestTemplate = ScriptContext(Wiki, TemplatePage)
        Viewer = Page(RequestTemplate, TemplatePage)

        Text = Viewer.getPageText().replace("@PAGE@", NewPage)
        Header = Viewer.getPageHeader()

        Text=Header+Text

        return Editor.saveText(Text, Revision)
Beispiel #9
0
def MinimalMoinScript(pagename='', parse=True):
    """
    The MoinScript class does command line argument parsing, which
    might not be what is desired, as it will complain about custom
    arguments in graphingwiki-based scripts. MoinScript initialises
    the request by calling up ScriptContext, which is then assigned to
    the script.request.

    If a gwiki script uses non-MoinScript command line arguments,
    the ScriptContext is initialized with minimum sane default.
    """
    if parse:
        script = MoinScript()
        if pagename:
            script.parser.set_defaults(page=pagename)
        script.options, script.args = script.parser.parse_args()
        script.init_request()
        return script.request

    from MoinMoin.web.contexts import ScriptContext
    # Default values
    return ScriptContext(None, pagename)
Beispiel #10
0
def execute(pagename, request):
    """                                                                         
    Handle action=IntraFarmCopy
    """

    if not request.user.may.read(pagename):
        Page(request, pagename).send_page()
        return

    # Which local farm wiki - assume team for now
    to_wiki_url = COPY_TO_WIKI_URL
    # New page name
    to_wiki_pagename = '%s%s' % (COPY_TO_PREFIX, pagename)

    # create page at local wiki if it doesn't exist
    to_request = ScriptContext(to_wiki_url)
    # login this user remotely
    to_uid = user.getUserId(to_request, request.user.name)
    to_user = user.User(to_request,
                        id=to_uid,
                        name=request.user.name,
                        password=request.user.password,
                        auth_method="moin")
    to_request.user = to_user

    try:
        page = Page(to_request, to_wiki_pagename)
    except:
        return action_error(u'Error accessing destination page')
    if not page.exists():
        pe = PageEditor(to_request, to_wiki_pagename)
        # make initial revision pointer to original
        try:
            pe.saveText(
                u'[[%s:%s]]' % (request.cfg.interwikiname, pagename),
                0,
                comment="Automated IntraFarmCopy pointing to original page")
        except pe.Unchanged:
            return action_error(u'Could not save initial page')
        except pe.AccessDenied:
            return action_error(u'Could not acquire credentials')
        # make next revision content of this page
        try:
            pe.saveText(
                Page(request, pagename).get_raw_body(),
                0,
                comment=
                "Automated IntraFarmCopy importing contents from original page at [[%s:%s]]"
                % (request.cfg.interwikiname, pagename))
        except pe.Unchanged:
            return action_error(u'Could not save destination page text')

# send attachments over
        attachments = AttachFile._get_files(request, pagename)
        for attachname in attachments:
            filename = AttachFile.getFilename(request, pagename, attachname)
            if not os.path.isfile(filename):
                continue
            to_filename = AttachFile.getFilename(to_request, to_wiki_pagename,
                                                 attachname)
            shutil.copyfile(filename, to_filename)
            AttachFile._addLogEntry(to_request, 'ATTNEW', to_wiki_pagename,
                                    attachname)
        # redirect user to view new page in other wiki
        request.http_redirect('%s%s' % (to_wiki_url, to_wiki_pagename))
        return
    else:
        return action_error(u'Destination page already exists!')
Beispiel #11
0
class MoinMoinEntryParser:
#{{{MoinMoinEntryParser class object
    '''
    This class contains evrything in order to parse a file using MoinMoin
    dervied Objects
    '''

    def __init__(self, url = '', pybloxsom_config = None):
#{{{Init method for the MoinMoinEntryParser class
        '''
        init method for MoinMoinEntryParser Object
        '''
        self.PREFORMATTER_ID = PREFORMATTER_ID

        # New MoinMoin request
        self.request = MoinMoinScriptContext(url)
        self.logger = PyblosxomTools.get_logger()
        self.url = url
        self.entryfile=''
        self.entrytitle = ''
        self.page_name = ''

        # Initial parser configuration if config is usable
        if pybloxsom_config is not None:
            self.pybloxsom_config = pybloxsom_config
            # Use moinmoin cache
            self.request.cacheable = self.request.use_cache = self.pybloxsom_config.get('moinmoin_use_cache', '0') == '1'
            #self.request.cacheable = self.request.use_cache = False

            # moinmoin encoding 
            self.output_charset = self.pybloxsom_config.get('blog_encoding', 'utf-8')
        # We don't have the config, using default
        else:
            self.request.cacheable = False
            self.output_charset = 'utf-8'
#}}}
        self.logger.debug('Moinmoin parser Object created')

    def create_page(self, entryfile = '', load_from_disk = True):
#{{{Here we create a moinmoin page object
        '''Creates a new MoinMoin Page Object.'''

        '''
        If load_from_disk is true, then the file is loaded from the disk using the entryfile as the filename.
        If not, we use the entryfile string as the raw file body
        '''
        # New MoinMoinPage
        if load_from_disk:
            page_dir, self.page_name = os.path.split(entryfile)
        else:
            self.page_name = str(hashlib.md5(entryfile).hexdigest())
        
        self.page = MoinMoinPage(self.request, page_name=self.page_name, formatter=None)

        # Load New page from file
        if load_from_disk:
            self.page.__body = None
            self.page._text_filename_force = entryfile
            self.logger.debug('Entry file to convert: %s' % entryfile)
        # Extracting page title
            tmp_body = self.page.get_body()
            self.entrytitle = tmp_body.split('\n')[0]
            self.page.set_raw_body(tmp_body[len(self.entrytitle)+1:])
            del tmp_body
        else:
            self.page.set_raw_body(entryfile)
            self.logger.debug('Using data got from pyblosxom')

        self.page.hilite_re = None
        self.page.output_charset = self.output_charset
        self.parser = None
        self.formatter = None
        self.default_parser = 'wiki'
        self.output_format = u'text/html'
        self.request.page = self.page
        self.page.__pi = self.page.parse_processing_instructions()
        self.logger.debug('New moinmoin page created')
#}}}

    def create_parser(self, line_anchors = False):
#{{{Here we create a moinmoin paser object
        '''Creating parser object'''
        
        Parser = MoinMoinWikiutil.searchAndImportPlugin(self.request.cfg, 'parser', self.request.getPragma('format', self.default_parser.lower()))
        self.parser = Parser(self.page.get_body(), self.request, line_anchors = line_anchors)
        self.logger.debug('New moinmoin parser created')
#}}}

    def create_formatter(self):
#{{{Here we create a moinmoin formatter object
        '''Creating formatter object'''

        Formatter = MoinMoinWikiutil.searchAndImportPlugin(self.request.cfg, 'formatter', self.request.getPragma('output-format', self.output_format).lower())

        self.formatter = Formatter(self.request)
        self.formatter.setPage(self.page)
        self.request.formatter = self.page.formatter = self.formatter
        self.logger.debug('New moinmoin formatter created')
#}}}

    def parse_entry(self, content_only = 1):
#{{{parsing the entry file return the result
        '''parse the entryfile and return the result string'''
        return self.request.redirectedOutput(self.page.send_page,content_id=self.page_name, content_only = content_only, do_cache=self.request.cacheable)
Beispiel #12
0
            if not mailaddr in wiki_addrs
        ])
        subj_col = '[[%s|%s]]' % (pagename, msg['subject'])
        date_col = msg['date']
        attach_col = " ".join(attachment_links)
        new_line = u'|| <<DateTime(%s)>> || %s || %s || %s || %s ||' % (
            date_col, from_col, to_col, subj_col, attach_col)
        if found_table is not None:
            content = "\n".join(old_content[:table_ends] + [new_line] +
                                old_content[table_ends:])
        else:
            content = "\n".join(old_content) + table_header + new_line

        page = PageEditor(request, parent_page, do_editor_backup=0)
        page.saveText(content, 0, comment=comment)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        request_url = sys.argv[1]
    else:
        request_url = None

    from MoinMoin.web.contexts import ScriptContext
    request = ScriptContext(url=request_url)

    try:
        import_mail_from_file(request, infile)
    except ProcessingError, e:
        print >> sys.stderr, "An error occurred while processing the message:", e.args
Beispiel #13
0
            differ = difflib.Differ(charjunk=lambda c:c.isspace())
            l = map(lambda s: s.strip(), page.get_body().splitlines())
            r = map(lambda s: s.strip(), output.splitlines())   
            if l != r:
                d = u'\n'.join(filter(lambda s: s and s[0] in u'+-?', differ.compare(l, r)))
                print((u'#### Diff in %s ####' % weapon_name).encode('utf-8'))
                print(d.encode('utf-8'))
    except PageEditor.Unchanged:
        pass

    if not is_sub and j.get(u'subStatusMap', {}):
        processWeapon(j, context, True, dry_run)

if __name__ == '__main__':
    from MoinMoin import config
    context = ScriptContext()
    context.remote_addr = '127.0.0.1'
    root_page = RootPage(context)

    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=file)
    parser.add_argument('--no-dry-run', dest='no_dry_run', type=bool, default=False)
    args = parser.parse_args()

    dry_run = not args.no_dry_run
    
    json_lines = args.file.readlines()

    for json_text in json_lines:
        j = json.loads(json_text)
        if not isinstance(j, list):
Beispiel #14
0
 def init_request(self):
     """ create request """
     from MoinMoin.web.contexts import ScriptContext
     url = self.options.wiki_url or None
     self.request = ScriptContext(url, self.options.page)
import argparse

from MoinMoin.PageEditor import PageEditor
from MoinMoin.web.contexts import ScriptContext
from MoinMoin.web.request import TestRequest
from MoinMoin.Page import RootPage

from macro.utils import json_printer, json_loader

COMMENTS = u"""==== コメント ====
<<AddComment>>
<<Comments>>"""

RE_COMMENTS = re.compile(ur"====\s*コメント\s*====\s*<<AddComment>>\s*<<Comments>>")

if __name__ == "__main__":
    from MoinMoin import config

    context = ScriptContext()
    context.remote_addr = "127.0.0.1"
    root_page = RootPage(context)

    for page_name in root_page.getPageList(user=""):
        page = PageEditor(context, page_name)
        data = page.get_raw_body()
        match = RE_COMMENTS.search(data)
        if match:
            data = RE_COMMENTS.sub(u"", data)
            data += COMMENTS
            page.saveText(data, page.current_rev())
Beispiel #16
0
#source http://stackoverflow.com/questions/5275856/moinmoin-1-9-programmatically-creating-page-error-moinmoin-pageeditor-accessden
#       and https://moinmo.in/MoinAPI/Examples#PageEditor.saveText.28.29

from MoinMoin.web.contexts import ScriptContext
from MoinMoin.PageEditor import PageEditor

import MoinMoin.user

request = ScriptContext('http://*****:*****@example.com')
request.user = user

pe = PageEditor(request, 'MyNewTestPageGroup')

memberlist = ['Tom', 'Harry', 'Steph', 'Rama']
mystring = ' * '
mynewlist = ['#acl ItGroup:read,write,delete,revert,admin Known: All:'
             ] + [mystring + x for x in memberlist]

mynewlist = '\n'.join(mynewlist)

try:
    pe.saveText(mynewlist, 0)

except pe.Unchanged:
    print "You did not change the page content, not saved!"

print ' t '
Beispiel #17
0
import sys
import re
import urllib2
from urllib import quote
import xmlrpclib
import csv

from MoinMoin.web.contexts import ScriptContext
from MoinMoin.Page import Page

# monkeypatch the formatter to avoid line_anchors:
from MoinMoin.formatter import text_html
text_html.line_anchors = False

request = ScriptContext(None, None)


class DataNotFoundException(Exception): pass


class Task(object):
    def __init__(self, summary, desc, label, hours, mentors, difficulty, types):
        self.summary = summary
        self.label = label
        self.hours = hours
        self.mentors = mentors
        self.difficulty = difficulty
        self.types = types

        page = Page(request, "")
Beispiel #18
0
    # this needed for macros
    request.formatter = formatter

    p = Page(request, pagename)
    formatter.setPage(p)

    output = StringIO.StringIO()

    # wrap sys.stdout as RequestCLI has no interface to say where to output
    stdout = sys.stdout
    sys.stdout = output
    parser.format(formatter)
    sys.stdout = stdout

    return unicode(output.getvalue().decode('utf-8'))


request = ScriptContext()
formatter = Formatter(request)

if __name__ == "__main__":
    # pages/playground\(2f\)SyntaxReference/revisions/00000001
    if len(sys.argv) > 1:
        inputfile = sys.argv[1]
    else:
        inputfile = 'syntaxreference.txt'

    f = open(inputfile, 'r')
    text = f.read()
    print moin2doku('test', text)