本文整理汇总了Python中MoinMoin.action.AttachFile.exists方法的典型用法代码示例。如果您正苦于以下问题:Python AttachFile.exists方法的具体用法?Python AttachFile.exists怎么用?Python AttachFile.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MoinMoin.action.AttachFile
的用法示例。
在下文中一共展示了AttachFile.exists方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_image
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def visit_image(self, node):
"""
Need to intervene in the case of inline images. We need MoinMoin to
give us the actual src line to the image and then we can feed this
to the default html4css1 writer. NOTE: Since the writer can't "open"
this image the scale attribute doesn't work without directly
specifying the height or width (or both).
TODO: Need to handle figures similarly.
"""
uri = node['uri'].lstrip()
prefix = '' # assume no prefix
attach_name = uri
if ':' in uri:
prefix = uri.split(':', 1)[0]
attach_name = uri.split(':', 1)[1]
# if prefix isn't URL, try to display in page
if not prefix.lower() in ('file', 'http', 'https', 'ftp'):
if not AttachFile.exists(self.request, self.request.page.page_name, attach_name):
# Attachment doesn't exist, MoinMoin should process it
if prefix == '':
prefix = 'attachment:'
self.process_wiki_text("{{%s%s}}" % (prefix, attach_name))
self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
self.add_wiki_markup()
# Attachment exists, get a link to it.
# create the url
node['uri'] = AttachFile.getAttachUrl(self.request.page.page_name, attach_name, self.request, addts=1)
if not node.hasattr('alt'):
node['alt'] = node.get('name', uri)
html4css1.HTMLTranslator.visit_image(self, node)
示例2: test_add_attachment
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def test_add_attachment(self):
"""Test if add_attachment() works"""
become_trusted(self.request)
filename = "AutoCreatedSillyAttachment"
create_page(self.request, self.pagename, u"Foo!")
AttachFile.add_attachment(self.request, self.pagename, filename, "Test content", True)
exists = AttachFile.exists(self.request, self.pagename, filename)
nuke_page(self.request, self.pagename)
assert exists
示例3: testAttachments_without_page_creation
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def testAttachments_without_page_creation(self):
become_trusted(self.request)
pagename = u"PackageAttachmentAttachWithoutPageCreation"
script = u"""MoinMoinPackage|1
AddAttachment|1_attachment|my_test.txt|%(pagename)s
Print|Thank you for using PackagePages!
""" % {"pagename": pagename}
zip_file = self.create_package(script)
package = ZipPackage(self.request, zip_file)
package.installPackage()
assert not Page(self.request, pagename).exists()
assert AttachFile.exists(self.request, pagename, "my_test.txt")
nuke_page(self.request, pagename)
os.unlink(zip_file)
示例4: testAttachments_after_page_creation
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def testAttachments_after_page_creation(self):
become_trusted(self.request)
pagename = u'PackageTestPageCreatedFirst'
page = create_page(self.request, pagename, u"This page has not yet an attachments dir")
script = u"""MoinMoinPackage|1
AddRevision|1|%(pagename)s
AddAttachment|1_attachment|my_test.txt|%(pagename)s
Print|Thank you for using PackagePages!
""" % {"pagename": pagename}
zip_file = self.create_package(script, page)
package = ZipPackage(self.request, zip_file)
package.installPackage()
assert Page(self.request, pagename).exists()
assert AttachFile.exists(self.request, pagename, "my_test.txt")
nuke_page(self.request, pagename)
os.unlink(zip_file)
示例5: test_add_attachment_for_file_object
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def test_add_attachment_for_file_object(self):
"""Test if add_attachment() works with file like object"""
become_trusted(self.request)
filename = "AutoCreatedSillyAttachment.png"
create_page(self.request, self.pagename, u"FooBar!")
data = "Test content"
filecontent = StringIO.StringIO(data)
AttachFile.add_attachment(self.request, self.pagename, filename, filecontent, True)
exists = AttachFile.exists(self.request, self.pagename, filename)
path = AttachFile.getAttachDir(self.request, self.pagename)
imagef = os.path.join(path, filename)
file_size = os.path.getsize(imagef)
nuke_page(self.request, self.pagename)
assert exists and file_size == len(data)
示例6: visit_reference
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def visit_reference(self, node):
"""
Pass links to MoinMoin to get the correct wiki space url. Extract
the url and pass it on to the html4css1 writer to handle. Inline
images are also handled by visit_image. Not sure what the "drawing:"
link scheme is used for, so for now it is handled here.
Also included here is a hack to allow MoinMoin macros. This routine
checks for a link which starts with "<<". This link is passed to the
MoinMoin formatter and the resulting markup is inserted into the
document in the place of the original link reference.
"""
if 'refuri' in node.attributes:
refuri = node['refuri']
prefix = ''
link = refuri
if ':' in refuri:
prefix, link = refuri.lstrip().split(':', 1)
# First see if MoinMoin should handle completely. Exits through add_wiki_markup.
if refuri.startswith('<<') and refuri.endswith('>>'): # moin macro
self.process_wiki_text(refuri)
self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
self.add_wiki_markup()
if prefix == 'drawing':
self.process_wiki_text("[[%s]]" % refuri)
self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
self.add_wiki_markup()
# From here down, all links are handled by docutils (except
# missing attachments), just fixup node['refuri'].
if prefix == 'attachment':
if not AttachFile.exists(self.request, self.request.page.page_name, link):
# Attachment doesn't exist, give to MoinMoin to insert upload text.
self.process_wiki_text("[[%s]]" % refuri)
self.wiki_text = self.fixup_wiki_formatting(self.wiki_text)
self.add_wiki_markup()
# Attachment exists, just get a link to it.
node['refuri'] = AttachFile.getAttachUrl(self.request.page.page_name, link, self.request)
if not [i for i in node.children if i.__class__ == docutils.nodes.image]:
node['classes'].append(prefix)
elif prefix == 'wiki':
wiki_name, page_name = wikiutil.split_interwiki(link)
wikitag, wikiurl, wikitail, err = wikiutil.resolve_interwiki(self.request, wiki_name, page_name)
wikiurl = wikiutil.mapURL(self.request, wikiurl)
node['refuri'] = wikiutil.join_wiki(wikiurl, wikitail)
# Only add additional class information if the reference does
# not have a child image (don't want to add additional markup
# for images with targets).
if not [i for i in node.children if i.__class__ == docutils.nodes.image]:
node['classes'].append('interwiki')
elif prefix != '':
# Some link scheme (http, file, https, mailto, etc.), add class
# information if the reference doesn't have a child image (don't
# want additional markup for images with targets).
# Don't touch the refuri.
if not [i for i in node.children if i.__class__ == docutils.nodes.image]:
node['classes'].append(prefix)
else:
# Default case - make a link to a wiki page.
pagename, anchor = wikiutil.split_anchor(refuri)
page = Page(self.request, wikiutil.AbsPageName(self.formatter.page.page_name, pagename))
node['refuri'] = page.url(self.request, anchor=anchor)
if not page.exists():
node['classes'].append('nonexistent')
html4css1.HTMLTranslator.visit_reference(self, node)
示例7: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def execute(pagename, request):
_ = request.getText
if not request.user or not request.user.isSuperUser():
msg = _('Only superuser is allowed to use this action.')
request.theme.add_msg(msg, "error")
request.page.send_page()
return ''
fmt = request.html_formatter
language_setup_page = 'LanguageSetup'
not_translated_system_pages = 'not_translated_system_pages.zip'
files = AttachFile._get_files(request, language_setup_page)
if not files:
msg = _('No page packages found.')
request.theme.add_msg(msg, "error")
request.page.send_page()
return ''
wiki_languages = list(set([lang_file.split('--')[0] for lang_file in files]) - set(['00_needs_fixing.zip']))
wiki_languages.sort()
lang = request.values.get('language') or 'English'
target = request.values.get('target') or ''
msg = ''
# if target is given it tries to install the package.
if target:
dummy_pagename, dummy_target, targetpath = AttachFile._access_file(language_setup_page, request)
package = packages.ZipPackage(request, targetpath)
if package.isPackage():
if package.installPackage():
msg = _("Attachment '%(filename)s' installed.") % {'filename': target}
else:
msg = _("Installation of '%(filename)s' failed.") % {'filename': target}
else:
msg = _('The file %s is not a MoinMoin package file.') % target
data = TupleDataset()
data.columns = [
Column('page package', label=_('page package')),
Column('action', label=_('install')),
]
label_install = _("install")
for pageset_name in i18n.strings.pagesets:
attachment = "%s--%s.zip" % (lang, pageset_name)
# not_translated_system_pages are in english
if attachment.endswith(not_translated_system_pages):
attachment = 'English_not_translated_system_pages.zip'
install_link = ''
querystr = {'action': 'language_setup', 'target': attachment, 'language': lang}
if AttachFile.exists(request, language_setup_page, attachment):
install_link = request.page.link_to(request, label_install, querystr=querystr)
data.addRow((pageset_name, install_link))
table = DataBrowserWidget(request)
table.setData(data)
page_table = ''.join(table.format(method='GET'))
fmt = request.formatter
lang_links = [request.page.link_to_raw(request, _lang,
querystr={'action': 'language_setup',
'language': _lang,
'pageset': pageset_name, })
for _lang in wiki_languages]
lang_selector = u''.join([fmt.paragraph(1), _("Choose:"), ' ', ' '.join(lang_links), fmt.paragraph(0)])
title = _("Install language packs for '%s'") % wikiutil.escape(lang)
request.theme.add_msg(msg, "info")
request.theme.send_title(title, page=request.page, pagename=pagename)
request.write(request.formatter.startContent("content"))
request.write(lang_selector)
request.write(page_table)
request.write(request.formatter.endContent())
request.theme.send_footer(pagename)
request.theme.send_closing_html()
示例8: macro_EmbedObject
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def macro_EmbedObject(macro, target=wikiutil.required_arg(unicode), pagename=None,
width=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px'),
height=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px'),
alt=u'',
play=False, stop=True, loop=False, quality=(u'high', u'low', u'medium'),
op=True, repeat=False, autostart=False, align=(u'middle', u'top', u'bottom'), hidden=False,
menu=True, wmode=u'transparent', url_mimetype=None):
""" This macro is used to embed an object into a wiki page """
# Join unit arguments with their units
if width:
if width[1] == 'px':
width = '%dpx' % int(width[0])
else:
width = '%g%s' % width
if height:
if height[1] == 'px':
height = '%dpx' % int(height[0])
else:
height = '%g%s' % height
request = macro.request
_ = macro.request.getText
fmt = macro.formatter
# AttachFile calls always with pagename. Users can call the macro from a different page as the attachment is saved.
if not pagename:
pagename = fmt.page.page_name
if not wikiutil.is_URL(target):
pagename, fname = AttachFile.absoluteName(target, pagename)
if not AttachFile.exists(request, pagename, fname):
linktext = _('Upload new attachment "%(filename)s"') % {'filename': fname}
target = AttachFile.getAttachUrl(pagename, fname, request, do='upload_form')
return (fmt.url(1, target) +
fmt.text(linktext) +
fmt.url(0))
url = AttachFile.getAttachUrl(pagename, fname, request)
mt = wikiutil.MimeType(filename=fname)
else:
if not url_mimetype:
return fmt.text(_('%(extension_name)s %(extension_type)s: Required argument %(argument_name)s missing.') % {
"extension_name": extension_name,
"extension_type": extension_type,
"argument_name": "url_mimetype",
})
else:
url = target
mt = wikiutil.MimeType() # initialize dict
try:
mt.major, mt.minor = url_mimetype.split('/')
except ValueError:
return fmt.text(_('%(extension_name)s %(extension_type)s: Invalid %(argument_name)s=%(argument_value)s!') % {
"extension_name": extension_name,
"extension_type": extension_type,
"argument_name": "url_mimetype",
"argument_value": str(url_mimetype),
})
mime_type = "%s/%s" % (mt.major, mt.minor, )
dangerous = mime_type in request.cfg.mimetypes_xss_protect
if not mime_type in request.cfg.mimetypes_embed or dangerous:
return "%s: %s%s%s" % (fmt.text(
_("Current configuration does not allow embedding of the file %(file)s because of its mimetype %(mimetype)s.") % {
"mimetype": mime_type,
"file": target}),
fmt.url(1, url),
fmt.text(target),
fmt.url(0))
if not alt:
alt = "%(text)s %(mime_type)s" % {'text': _("Embedded"), 'mime_type': mime_type}
embed_src = ''
if mt.major == 'video':
if not width and not height:
width = '400px'
height = '400px'
embed_src = '''
<object %(ob_data)s %(ob_type)s %(ob_width)s %(ob_height)s %(ob_align)s %(ob_standby)s %(ob_stop)s>
%(wmode)s%(movie)s%(play)s%(stop)s%(repeat)s%(autostart)s%(op)s%(menu)s
<p>%(alt)s</p>
</object>''' % {
"ob_data": _check_object_value("data", url),
"ob_type": _check_object_value("type", mime_type),
"ob_width": _check_object_value("width", width),
"ob_height": _check_object_value("height", height),
"ob_align": _check_object_value("align", align),
"ob_standby": _check_object_value("standby", alt),
"ob_stop": _check_object_value("stop", stop),
"wmode": _check_param_value("wmode", wmode, "data"),
"movie": _check_param_value("movie", url, "data"),
"play": _check_param_value("play", play, "data"),
"stop": _check_param_value("stop", stop, "data"),
"repeat": _check_param_value("repeat", repeat, "data"),
"autostart": _check_param_value("autostart", autostart, "data"),
#.........这里部分代码省略.........
示例9: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
#.........这里部分代码省略.........
# emit logo data
if logo:
handler.startNode("image", attr={(handler.xmlns["rdf"], "about"): logo})
handler.simpleNode("title", cfg.sitename)
handler.simpleNode("link", baseurl)
handler.simpleNode("url", logo)
handler.endNode("image")
# Mapping { oldname: curname } for maintaining page renames
pagename_map = {}
# emit items
for item in logdata:
if item.pagename in pagename_map:
cur_pagename = pagename_map[item.pagename]
else:
cur_pagename = item.pagename
page = Page(request, cur_pagename)
action = item.action
comment = item.comment
anchor = "%04d%02d%02d%02d%02d%02d" % item.time[:6]
rdflink = full_url(request, page, anchor=anchor)
handler.startNode("item", attr={(handler.xmlns["rdf"], "about"): rdflink})
# general attributes
handler.simpleNode("title", item.pagename)
handler.simpleNode(("dc", "date"), timefuncs.W3CDate(item.time))
show_diff = diffs
if action.startswith("ATT"): # Attachment
show_diff = 0
filename = wikiutil.url_unquote(item.extra)
att_exists = AttachFile.exists(request, cur_pagename, filename)
if action == "ATTNEW":
# Once attachment deleted this link becomes invalid but we
# preserve it to prevent appearance of new RSS entries in
# RSS readers.
if ddiffs:
handler.simpleNode("link", attach_url(request, cur_pagename, filename, do="view"))
comment = _(u"Upload of attachment '%(filename)s'.") % {"filename": filename}
elif action == "ATTDEL":
if ddiffs:
handler.simpleNode("link", full_url(request, page, querystr={"action": "AttachFile"}))
comment = _(u"Attachment '%(filename)s' deleted.") % {"filename": filename}
elif action == "ATTDRW":
if ddiffs:
handler.simpleNode("link", attach_url(request, cur_pagename, filename, do="view"))
comment = _(u"Drawing '%(filename)s' saved.") % {"filename": filename}
elif action.startswith("SAVE"):
if action == "SAVE/REVERT":
to_rev = int(item.extra)
comment = (
(_(u"Revert to revision %(rev)d.") % {"rev": to_rev}) + "<br />" + _("Comment:") + " " + comment
)
elif action == "SAVE/RENAME":
show_diff = 0
comment = (
示例10: history
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def history(page, pagename, request):
# show history as default
_ = request.getText
default_count, limit_max_count = request.cfg.history_count
try:
max_count = int(request.form.get('max_count', [default_count])[0])
except:
max_count = default_count
max_count = min(max_count, limit_max_count)
# open log for this page
from MoinMoin.util.dataset import TupleDataset, Column
history = TupleDataset()
history.columns = [
Column('rev', label='#', align='right'),
Column('mtime', label=_('Date'), align='right'),
Column('size', label=_('Size'), align='right'),
Column('diff', label='<input type="submit" value="%s">' % (_("Diff"))),
Column('editor', label=_('Editor'), hidden=not request.cfg.show_names),
Column('comment', label=_('Comment')),
Column('action', label=_('Action')),
]
# generate history list
def render_action(text, query, **kw):
kw.update(dict(rel='nofollow'))
return page.link_to(request, text, querystr=query, **kw)
# read in the complete log of this page
log = editlog.EditLog(request, rootpagename=pagename)
count = 0
pgactioncount = 0
for line in log.reverse():
rev = int(line.rev)
actions = []
if line.action in ('SAVE', 'SAVENEW', 'SAVE/REVERT', 'SAVE/RENAME', ):
size = page.size(rev=rev)
actions.append(render_action(_('view'), {'action': 'recall', 'rev': '%d' % rev}))
if pgactioncount == 0:
rchecked = ' checked="checked"'
lchecked = ''
elif pgactioncount == 1:
lchecked = ' checked="checked"'
rchecked = ''
else:
lchecked = rchecked = ''
diff = '<input type="radio" name="rev1" value="%d"%s><input type="radio" name="rev2" value="%d"%s>' % (rev, lchecked, rev, rchecked)
if rev > 1:
diff += render_action(' ' + _('to previous'), {'action': 'diff', 'rev1': rev-1, 'rev2': rev})
comment = line.comment
if not comment:
if '/REVERT' in line.action:
comment = _("Revert to revision %(rev)d.") % {'rev': int(line.extra)}
elif '/RENAME' in line.action:
comment = _("Renamed from '%(oldpagename)s'.") % {'oldpagename': line.extra}
pgactioncount += 1
else: # ATT*
rev = '-'
diff = '-'
filename = wikiutil.url_unquote(line.extra)
comment = "%s: %s %s" % (line.action, filename, line.comment)
size = 0
if line.action != 'ATTDEL':
from MoinMoin.action import AttachFile
if AttachFile.exists(request, pagename, filename):
size = AttachFile.size(request, pagename, filename)
if line.action == 'ATTNEW':
actions.append(render_action(_('view'), {'action': 'AttachFile', 'do': 'view', 'target': '%s' % filename}))
elif line.action == 'ATTDRW':
actions.append(render_action(_('edit'), {'action': 'AttachFile', 'drawing': '%s' % filename.replace(".draw", "")}))
actions.append(render_action(_('get'), {'action': 'AttachFile', 'do': 'get', 'target': '%s' % filename}))
if request.user.may.delete(pagename):
actions.append(render_action(_('del'), {'action': 'AttachFile', 'do': 'del', 'target': '%s' % filename}))
history.addRow((
rev,
request.user.getFormattedDateTime(wikiutil.version2timestamp(line.ed_time_usecs)),
str(size),
diff,
line.getEditor(request) or _("N/A"),
wikiutil.escape(comment) or ' ',
" ".join(actions),
))
count += 1
if count >= max_count:
break
# print version history
from MoinMoin.widget.browser import DataBrowserWidget
request.write(unicode(html.H2().append(_('Revision History'))))
if not count: # there was no entry in logfile
request.write(_('No log entries found.'))
return
#.........这里部分代码省略.........
示例11: _do_diff
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def _do_diff(pagename, request):
# return attachment list
_ = request.getText
form = values_to_form(request.values)
att1 = form.get('att1', [''])[0]
att2 = form.get('att2', [''])[0]
sort = form.get('sort', ['normal'])[0]
if (not (att1 and att2) or not
(AttachFile.exists(request, pagename, att1) and
AttachFile.exists(request, pagename, att2))):
AttachFile.error_msg(pagename, request,
_('Could not diff, attachments not selected or nonexisting'))
return
form['target'] = [att1]
request.values = CombinedMultiDict([MultiDict(form)])
pagename, filename, fpath = AttachFile._access_file(pagename, request)
att1data = open(fpath, 'r').read()
form['target'] = [att2]
request.values = CombinedMultiDict([MultiDict(form)])
pagename, filename, fpath = AttachFile._access_file(pagename, request)
att2data = open(fpath, 'r').read()
if sort == 'sort':
att1data = '\n'.join(sorted(att1data.split('\n')))
att2data = '\n'.join(sorted(att2data.split('\n')))
elif sort == 'uniq':
att1data = '\n'.join(sorted(set(att1data.split('\n'))))
att2data = '\n'.join(sorted(set(att2data.split('\n'))))
elif sort == 'cnt':
att1tmp = list()
for line in sorted(set(att1data.split('\n'))):
if not line:
continue
att1tmp.append("%s %s" % (att1data.count(line), line))
att2tmp = list()
for line in sorted(set(att2data.split('\n'))):
if not line:
continue
att2tmp.append("%s %s" % (att2data.count(line), line))
att1data = '\n'.join(att1tmp)
att2data = '\n'.join(att2tmp)
# Use user interface language for this generated page
request.setContentLanguage(request.lang)
request.theme.send_title(_('Diff of %s and %s') % (att1, att2),
pagename=pagename)
request.write('<div id="content">\n') # start content div
if request.user.show_fancy_diff:
from MoinMoin.util import diff_html
request.write(request.formatter.rawHTML(diff_html.diff(request,
att1data,
att2data)))
else:
from MoinMoin.util import diff_text
lines = diff_text.diff(att1data.split("\n"), att2data.split("\n"))
request.write(request.formatter.preformatted(1))
for line in lines:
if line[0] == "@":
request.write(request.formatter.rule(1))
request.write(request.formatter.text(line + '\n'))
request.write(request.formatter.preformatted(0))
AttachFile.send_uploadform(pagename, request)
request.write('</div>\n') # end content div
request.theme.send_footer(pagename)
request.theme.send_closing_html()
示例12: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def execute(macro, args):
request = macro.request
_ = request.getText
formatter = macro.formatter
kwAllowed = ['width', 'height', 'alt']
pp, pp_count, kw, kw_count = explore_args(args, kwAllowed)
if not pp_count or pp_count and not pp[0]:
msg = 'Not enough arguments given to ImageLink macro! Try <<ImageLink(example.png, WikiName, width=200)>>.'
return "%s%s%s" % (formatter.sysmsg(1), formatter.text(msg), formatter.sysmsg(0))
image = pp[0]
if pp_count >= 2 and pp[1]:
target = pp[1]
if target.startswith('attachment:') or target.startswith('inline:'):
if target.startswith('attachment:'):
target = (target.split('attachment:'))[1]
pagename, attname = AttachFile.absoluteName(target, formatter.page.page_name)
target = AttachFile.getAttachUrl(pagename, target, request)
elif target.startswith('inline:'):
target = (target.split('inline:'))[1]
pagename, attname = AttachFile.absoluteName(target, formatter.page.page_name)
target = AttachFile.getAttachUrl(pagename, target, request, do='view')
if not AttachFile.exists(request, pagename, attname):
linktext = _('Upload new attachment "%(filename)s"', formatted=False)
return wikiutil.link_tag(request,
('%s?action=AttachFile&rename=%s' % (
wikiutil.quoteWikinameURL(pagename),
wikiutil.url_quote_plus(attname))),
linktext % {'filename': attname})
kw['src'] = AttachFile.getAttachUrl(pagename, image, request)
elif pp_count == 1:
pagename, attname = AttachFile.absoluteName(image, formatter.page.page_name)
target = AttachFile.getAttachUrl(pagename, image, request)
else:
target = None
if _is_URL(image):
kw['src'] = image
else:
pagename, attname = AttachFile.absoluteName(image, formatter.page.page_name)
kw['src'] = AttachFile.getAttachUrl(pagename, attname, request)
if not AttachFile.exists(request, pagename, attname):
linktext = _('Upload new attachment "%(filename)s"', formatted=False)
return wikiutil.link_tag(request,
('%s?action=AttachFile&rename=%s' % (
wikiutil.quoteWikinameURL(pagename),
wikiutil.url_quote_plus(attname))),
linktext % {'filename': attname})
if 'alt' not in kw:
if target is None or _is_URL(target):
if _is_URL(image):
# Get image name http://here.com/dir/image.png -> image.png
kw['alt'] = wikiutil.taintfilename(formatter.text(image.split('/')[-1]))
else:
kw['alt'] = attname
else:
kw['alt'] = target
if target is None:
target = kw['src']
if pp_count == 1:
return "%s%s%s" % (formatter.url(1, kw['src']),
formatter.image(**kw),
formatter.url(0))
if _is_URL(target) or 'action=AttachFile&do=get&target=' in target or 'action=AttachFile&do=view&target=' in target:
return "%s%s%s" % (formatter.url(1, target),
formatter.image(**kw),
formatter.url(0))
else:
if ":" in target:
if target.startswith('wiki:'):
target = target[5:]
wikitag, wikiurl, wikitail, error = wikiutil.resolve_wiki(request, target)
url = wikiurl + wikiutil.quoteWikinameURL(wikitail)
return "%s%s%s" % (formatter.url(1, url),
formatter.image(**kw),
formatter.url(0))
else:
return "%s%s%s" % (formatter.pagelink(1, target),
formatter.image(**kw),
formatter.pagelink(0))
示例13: handle_request
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
def handle_request(self):
wiki_page_base = Page(self.request, _wiki_base)
wiki_page_config = Page(self.request, _wiki_base+'/Config')
form = self.request.form
#=== Sanity checks: Create required pages if not exist, check if oauth config works ===
#create _wiki_base page, if not exists
if not Page(self.request, _wiki_base).exists():
try:
self.create_default_wikibase_page()
except Exception as e:
self.request.theme.add_msg('Could not create page "'+_wiki_base+'": '+pformat(e), 'error')
Page(self.request, self.pagename).send_page()
return
#create Template page, if not exists
if not Page(self.request, _wiki_base+'/Template').exists():
try:
self.create_default_wikitemplate_page()
except Exception as e:
self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Template'+'": '+pformat(e), 'error')
Page(self.request, self.pagename).send_page()
return
if wiki_page_config.exists():
#parse config page and put as dict into self.config
self.read_config(wiki_page_config)
else:
#create Log page, if not exists
try:
if not Page(self.request, _wiki_base+'/Log').exists():
self.create_default_wikilog_page()
except Exception as e:
self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Log": '+pformat(e), 'error')
Page(self.request, self.pagename).send_page()
return
#create Config page, if not exists
try:
self.create_default_config_page()
except Exception as e:
self.request.theme.add_msg('Could not create page "'+_wiki_base+'/Config'+'": '+pformat(e), 'error')
Page(self.request, self.pagename).send_page()
return
self.request.theme.add_msg('Welcome to Mendeley2Moin. Pages needed for this plugin have been created.', 'info')
Page(self.request, _wiki_base+'/Log').send_page()
return
#Create MendeleyImporter instance and try to login using consumer/secret key and the file with authenticated tokens
self.mendeley_importer = MendeleyImporter(self.config['consumer_key'], self.config['secret_key'])
#Check if the user submitted the OAuth verifier
if self.request.values.has_key('submitVerifier'):
#parse serialized token and verifier
try:
self.mendeley_importer.set_verified_token(self.request.values['token'], self.request.values['verifier'])
except ValueError as e:
self.request.theme.add_msg('Could not authenticate tokens: '+pformat(e), 'error')
Page(self.request, _wiki_base+'/Log').send_page()
return
#save tokens as pickled file as attachment to Config page
self.mendeley_importer.save_keys(AttachFile.getAttachDir(self.request, _wiki_base+'/Config'))
self.prepend_to_wiki_page(_wiki_base+'/Log', 'OAuth configuration completed', \
'Access tokens have been saved [[attachment:%s/Config/mendeley_api_keys.pkl | here]]. Click here to run the plugin: [[/|Mendeley2Moin|&action=Mendeley2Moin]]\n'+\
'\n(Or go to Mendeley2Moin overview page.)\n' % (_wiki_base))
self.request.theme.add_msg('Tokens verified.' % (wikiutil.escape(self.mendeley_importer.mendeley.request_token)), 'info')
Page(self.request, _wiki_base+'/Log').send_page()
return
#Try to read file with authenticated tokens. They are supposed to be an attachment of the Config page
attachment = u'mendeley_api_keys.pkl'
if not AttachFile.exists(self.request, _wiki_base+'/Config', attachment):
#If file with authenticated tokens does not exist, request URL and write it as Log message to the user
try:
auth_url = self.mendeley_importer.get_auth_url()
except Exception as e:
self.request.theme.add_msg('Could not request OAuth URL: '+pformat(e), 'error')
wiki_page_base.send_page()
return
self.request.theme.add_msg('Register token on: '+auth_url, 'info')
try:
self.prepend_to_wiki_page(_wiki_base+'/Log', 'Step two: Register your OAuth token on mendeley.com', """\
* If you have a backup of the file {{{mendeley_api_keys.pkl}}}, upload it here [[attachment:%s/Config/mendeley_api_keys.pkl]].
* Otherwise [[%s|click here]] to register your token on mendeley.com. Then enter the verification code here:
{{{#!html
<form action="submit" method="GET">
<input type="hidden" name="action" value="Mendeley2Moin" />
<input type="hidden" name="token" value="%s" />
<input type="text" name="verifier" value="" size="36" />
<input type="submit" name="submitVerifier" value="Submit" />
</form>
}}}
""" % (_wiki_base, auth_url, wikiutil.escape(self.mendeley_importer.mendeley.request_token.to_string())))
except Exception as e:
self.request.theme.add_msg('Could not edit page "'+_wiki_base+'/Log": '+pformat(e), 'error')
Page(self.request, self.pagename).send_page()
return
Page(self.request, _wiki_base+'/Log').send_page()
return
#Get path of file with authenticated tokens and load it.
self.config['api_keys_pkl_dir'] = AttachFile.getAttachDir(self.request, _wiki_base+'/Config')
try:
#.........这里部分代码省略.........
示例14: execute
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
#.........这里部分代码省略.........
handler.startNode('image', attr={
(handler.xmlns['rdf'], 'about'): logo,
})
handler.simpleNode('title', cfg.sitename)
handler.simpleNode('link', baseurl)
handler.simpleNode('url', logo)
handler.endNode('image')
# Mapping { oldname: curname } for maintaining page renames
pagename_map = {}
# emit items
for item in logdata:
if item.pagename in pagename_map:
cur_pagename = pagename_map[item.pagename]
else:
cur_pagename = item.pagename
page = Page(request, cur_pagename)
action = item.action
comment = item.comment
anchor = "%04d%02d%02d%02d%02d%02d" % item.time[:6]
rdflink = full_url(request, page, anchor=anchor)
handler.startNode('item', attr={(handler.xmlns['rdf'], 'about'): rdflink, })
# general attributes
handler.simpleNode('title', item.pagename)
handler.simpleNode(('dc', 'date'), timefuncs.W3CDate(item.time))
show_diff = diffs
if action.startswith('ATT'): # Attachment
show_diff = 0
filename = wikiutil.url_unquote(item.extra)
att_exists = AttachFile.exists(request, cur_pagename, filename)
if action == 'ATTNEW':
# Once attachment deleted this link becomes invalid but we
# preserve it to prevent appearance of new RSS entries in
# RSS readers.
if ddiffs:
handler.simpleNode('link', attach_url(request,
cur_pagename, filename, do='view'))
comment = _(u"Upload of attachment '%(filename)s'.") % {
'filename': filename}
elif action == 'ATTDEL':
if ddiffs:
handler.simpleNode('link', full_url(request, page,
querystr={'action': 'AttachFile'}))
comment = _(u"Attachment '%(filename)s' deleted.") % {
'filename': filename}
elif action == 'ATTDRW':
if ddiffs:
handler.simpleNode('link', attach_url(request,
cur_pagename, filename, do='view'))
comment = _(u"Drawing '%(filename)s' saved.") % {
'filename': filename}
elif action.startswith('SAVE'):
if action == 'SAVE/REVERT':
to_rev = int(item.extra)
comment = (_(u"Revert to revision %(rev)d.") % {
示例15: history
# 需要导入模块: from MoinMoin.action import AttachFile [as 别名]
# 或者: from MoinMoin.action.AttachFile import exists [as 别名]
#.........这里部分代码省略.........
if url:
f = request.formatter
link = f.url(1, url) + f.text(text) + f.url(0)
return link
may_write = request.user.may.write(pagename)
may_delete = request.user.may.delete(pagename)
count = 0
pgactioncount = 0
for line in log.reverse():
count += 1
if paging and count <= offset:
continue
rev = int(line.rev)
actions = []
if line.action in ('SAVE', 'SAVENEW', 'SAVE/REVERT', 'SAVE/RENAME', ):
size = page.size(rev=rev)
actions.append(render_action(_('view'), {'action': 'recall', 'rev': '%d' % rev}))
if pgactioncount == 0:
rchecked = ' checked="checked"'
lchecked = ''
elif pgactioncount == 1:
lchecked = ' checked="checked"'
rchecked = ''
else:
lchecked = rchecked = ''
diff = '<input type="radio" name="rev1" value="%d"%s><input type="radio" name="rev2" value="%d"%s>' % (rev, lchecked, rev, rchecked)
if rev > 1:
diff += render_action(' ' + _('to previous'), {'action': 'diff', 'rev1': rev-1, 'rev2': rev})
comment = line.comment
if not comment:
if '/REVERT' in line.action:
comment = _("Revert to revision %(rev)d.") % {'rev': int(line.extra)}
elif '/RENAME' in line.action:
comment = _("Renamed from '%(oldpagename)s'.") % {'oldpagename': line.extra}
pgactioncount += 1
else: # ATT*
rev = '-'
diff = '-'
filename = wikiutil.url_unquote(line.extra)
comment = "%s: %s %s" % (line.action, filename, line.comment)
if AttachFile.exists(request, pagename, filename):
size = AttachFile.size(request, pagename, filename)
actions.append(render_file_action(_('view'), pagename, filename, request, do='view'))
actions.append(render_file_action(_('get'), pagename, filename, request, do='get'))
if may_delete:
actions.append(render_file_action(_('del'), pagename, filename, request, do='del'))
if may_write:
actions.append(render_file_action(_('edit'), pagename, filename, request, do='modify'))
else:
size = 0
history.addRow((
rev,
request.user.getFormattedDateTime(wikiutil.version2timestamp(line.ed_time_usecs)),
str(size),
diff,
line.getEditor(request) or _("N/A"),
wikiutil.escape(comment) or ' ',
" ".join(a for a in actions if a),
))
if (count >= max_count + offset) or (paging and count >= log_size):
break
# print version history
from MoinMoin.widget.browser import DataBrowserWidget
request.write(unicode(html.H2().append(_('Revision History'))))
if not count: # there was no entry in logfile
request.write(_('No log entries found.'))
return
history_table = DataBrowserWidget(request)
history_table.setData(history)
div = html.DIV(id="page-history")
div.append(html.INPUT(type="hidden", name="action", value="diff"))
div.append(history_table.render(method="GET"))
form = html.FORM(method="GET", action="")
if paging:
form.append(f.div(1, css_class="info-paging-info") + paging_info_html + count_select_html + f.div(0))
form.append("".join([
f.div(1, css_class="info-paging-nav info-paging-nav-top"),
paging_nav_html,
f.div(0),
]))
form.append(div)
if paging:
form.append("".join([
f.div(1, css_class="info-paging-nav info-paging-nav-bottom"),
paging_nav_html,
f.div(0)
]))
request.write(unicode(form))