def execute(self, args): #TODO - check that template is valid result = wikiutil.link_tag(self.request, "%s?action=edit&template=%s" % ( wikiutil.quoteWikinameURL(self.formatter.page.page_name), wikiutil.quoteWikinameURL(args)), args) return result
def execute(self, args): #TODO - check that template is valid result = wikiutil.link_tag( self.request, "%s?action=edit&template=%s" % (wikiutil.quoteWikinameURL( self.formatter.page.page_name), wikiutil.quoteWikinameURL(args)), args) return result
def _macro_WordIndex(self, args): _ = self._ allpages = int(self.form.get('allpages', [0])[0]) != 0 # Get page list readable by current user # Filter by isSystemPage if needed if allpages: # TODO: make this fast by caching full page list pages = self.request.rootpage.getPageList() else: def filter(name): return not wikiutil.isSystemPage(self.request, name) pages = self.request.rootpage.getPageList(filter=filter) map = {} word_re = re.compile(u'[%s][%s]+' % (config.chars_upper, config.chars_lower), re.UNICODE) for name in pages: for word in word_re.findall(name): try: if not map[word].count(name): map[word].append(name) except KeyError: map[word] = [name] all_words = map.keys() all_words.sort() index_letters = [] current_letter = None html = [] for word in all_words: letter = wikiutil.getUnicodeIndexGroup(word) if letter != current_letter: #html.append(self.formatter.anchordef()) # XXX no text param available! html.append(u'<a name="%s"><h3>%s</h3></a>' % ( wikiutil.quoteWikinameURL(letter), letter.replace('~', 'Others'))) current_letter = letter if letter not in index_letters: index_letters.append(letter) html.append(self.formatter.strong(1)) html.append(word) html.append(self.formatter.strong(0)) html.append(self.formatter.bullet_list(1)) links = map[word] links.sort() last_page = None for name in links: if name == last_page: continue html.append(self.formatter.listitem(1)) html.append(Page(self.request, name).link_to(self.request)) html.append(self.formatter.listitem(0)) html.append(self.formatter.bullet_list(0)) qpagename = wikiutil.quoteWikinameURL(self.formatter.page.page_name) index = _make_index_key(index_letters, u"""<br> <a href="%s?allpages=%d">%s</a> """ % (qpagename, not allpages, (_('Include system pages'), _('Exclude system pages'))[allpages]) ) return u'%s%s' % (index, u''.join(html))
def _macro_TitleIndex(self, args): _ = self._ html = [] index_letters = [] allpages = int(self.form.get('allpages', [0])[0]) != 0 # Get page list readable by current user # Filter by isSystemPage if needed if allpages: # TODO: make this fast by caching full page list pages = self.request.rootpage.getPageList() else: def filter(name): return not wikiutil.isSystemPage(self.request, name) pages = self.request.rootpage.getPageList(filter=filter) # Sort ignoring case tmp = [(name.upper(), name) for name in pages] tmp.sort() pages = [item[1] for item in tmp] current_letter = None for name in pages: letter = name[0].upper() letter = wikiutil.getUnicodeIndexGroup(name) if letter not in index_letters: index_letters.append(letter) if letter != current_letter: html.append(u'<a name="%s"><h3>%s</h3></a>' % ( wikiutil.quoteWikinameURL(letter), letter.replace('~', 'Others'))) current_letter = letter else: html.append(u'<br>') html.append(u'%s\n' % Page(self.request, name).link_to(self.request, attachment_indicator=1)) # add rss link index = '' if 0: # if wikixml.ok: # XXX currently switched off (not implemented) from MoinMoin import wikixml index = (index + self.formatter.url(1, wikiutil.quoteWikinameURL(self.formatter.page.page_name) + "?action=rss_ti", unescaped=1) + self.formatter.icon("rss") + self.formatter.url(0)) qpagename = wikiutil.quoteWikinameURL(self.formatter.page.page_name) index = index + _make_index_key(index_letters, u"""<br> <a href="%s?allpages=%d">%s</a> | <a href="%s?action=titleindex">%s</a> | <a href="%s?action=titleindex&mimetype=text/xml">%s</a> """ % (qpagename, not allpages, (_('Include system pages'), _('Exclude system pages'))[allpages], qpagename, _('Plain title index'), qpagename, _('XML title index')) ) return u'%s%s' % (index, u''.join(html))
def execute(pagename, request): _ = request.getText sub_page_name = request.cfg.supplementation_page_name sub_page_template = request.cfg.supplementation_page_template newpagename = "%s/%s" % (pagename, sub_page_name) errormsg = _("You are not allowed to create the supplementation page.") if pagename.endswith(sub_page_name): # sub_sub_page redirects to sub_page query = {} url = Page(request, pagename).url(request, query) request.http_redirect(url) elif request.user.may.read(newpagename): query = {} url = Page(request, newpagename).url(request, query) test = Page(request, newpagename) if test.exists(): # page is defined -> redirect request.http_redirect(url) elif request.user.may.write( newpagename): # page will be created from template query = { 'action': 'edit', 'backto': newpagename, 'template': quoteWikinameURL(sub_page_template) } url = Page(request, newpagename).url(request, query) request.http_redirect(url) else: request.theme.add_msg(errormsg, "error") else: request.theme.add_msg(errormsg, "error")
def _make_index_key(index_letters, additional_html=""): index_letters.sort() links = map(lambda ch: '<a href="#%s">%s</a>' % (wikiutil.quoteWikinameURL(ch), ch.replace('~', 'Others')), index_letters) return "<p>%s%s</p>" % (' | '.join(links), additional_html)
def prepare_node(self, node_name, node, orphaned_category): """ Prepare the wiki tree node Calculates the totals and the html code for the node. @param node name: @param path: list of nodes up to this one """ # Sort sub nodes node['categories'].sort() node['pages'].sort() node['attachments'].sort() # Calculate subnode counts node['categories_count'] = len(node['categories']) node['pages_count'] = len(node['pages']) node['attachments_count'] = len(node['attachments']) if not node['display_name']: node['display_name'] = node_name node['url'] = '%s/%s' % (self.request.getScriptname(), wikiutil.quoteWikinameURL(node_name)) orphaned_category[node['type']].append(node_name) # Build the html code for the link title = self.node_description(node) link_html = u'<a class="node" href="%s" title="%s">%s</a>' % ( node['url'], title, node['display_name']) node['html'] = self.node_icon_html[node['type']] + link_html return
def make_iconlink(self, which, d): """ Make a link with an icon @param which: icon id (dictionary key) @param d: parameter dictionary @rtype: string @return: html link tag """ page_name, querystr, title, icon = self.button_table[which] d['title'] = title % d d['i18ntitle'] = self.request.getText(d['title'], formatted=False) img_src = self.make_icon(icon, d) attrs = {'rel': 'nofollow', 'title': d['i18ntitle'], } if page_name: page = Page(self.request, page_name % d) else: page = d['page'] if self.is_moin_1_5: # Moin 1.5.x url = wikiutil.quoteWikinameURL(page.page_name) querystr = wikiutil.makeQueryString(querystr) if querystr: url = '%s?%s' % (url, querystr) html = wikiutil.link_tag(self.request, url, img_src, title="%(i18ntitle)s" % d) else: # Moin 1.6 rev = d['rev'] if rev and which in ['raw', 'print', ]: querystr['rev'] = str(rev) html = page.link_to_raw(self.request, text=img_src, querystr=querystr, **attrs) return html
def macro_NewPage(macro, template=u'', button_label=u'', parent_page=u'', name_template=u'%s', edit_action=''): including = False # Handle includedpage if parent_page == '@INCLUDINGPAGE': if hasattr(macro.request, 'includingpage'): parent_page = macro.request.includingpage[-1].page_name including = True else: parent_page = macro.request.page.page_name newpage = NewPage(macro, template, button_label, parent_page, name_template) macrotext = newpage.renderInPage() if edit_action: macrotext = macrotext.replace('<input', actioninput % edit_action, 1) if including: text = macrotext.split('\n') text[0] = text[0].split('action="')[0] text[0] += 'action="%s/%s"><div>' % \ (macro.request.getScriptname(), wikiutil.quoteWikinameURL( macro.request.includingpage[-1].page_name)) macrotext = '\n'.join(text) return macrotext
def attachUrl(request, pagename, filename=None, **kw): # filename is not used yet, but should be used later to make a sub-item url if kw: qs = '?%s' % wikiutil.makeQueryString(kw, want_unicode=False) else: qs = '' return "%s/%s%s" % (request.getScriptname(), wikiutil.quoteWikinameURL(pagename), qs)
def execute(pagename, request): _ = request.getText sub_page_name = request.cfg.supplementation_page_name sub_page_template = request.cfg.supplementation_page_template newpagename = "%s/%s" % (pagename, sub_page_name) errormsg = _("You are not allowed to create the supplementation page.") if pagename.endswith(sub_page_name): # sub_sub_page redirects to sub_page query = {} url = Page(request, pagename).url(request, query) request.http_redirect(url) elif request.user.may.read(newpagename): query = {} url = Page(request, newpagename).url(request, query) test = Page(request, newpagename) if test.exists(): # page is defined -> redirect request.http_redirect(url) elif request.user.may.write(newpagename): # page will be created from template query = {'action': 'edit', 'backto': newpagename, 'template': quoteWikinameURL(sub_page_template)} url = Page(request, newpagename).url(request, query) request.http_redirect(url) else: request.theme.add_msg(errormsg, "error") else: request.theme.add_msg(errormsg, "error")
def logo(self): """ Assemble logo with link to front page Changed: * we don't need a div wrapper for the textlogo * append text "FrontPage" to the logo string @rtype: unicode @return: logo html """ _ = self.request.getText html = u'' if self.cfg.logo_string: page = wikiutil.getFrontPage(self.request) logo_string = self.cfg.logo_string logo_append = '<span class="screenreader_info"> %s</span>' % _('FrontPage', formatted=False) logo_string = logo_string + logo_append # Try..except for backwards compatibility of Moin versions only try: logo = page.link_to_raw(self.request, logo_string) except: pagename = wikiutil.getFrontPage(self.request).page_name pagename = wikiutil.quoteWikinameURL(pagename) logo = wikiutil.link_tag(self.request, pagename, logo_string) html = u'%s' % logo return html
def sendBackupForm(request, pagename): _ = request.getText request.setContentLanguage(request.lang) title = _('Wiki Backup') request.theme.send_title(title, pagename=pagename) request.write(request.formatter.startContent("content")) request.write(_("""= Downloading a backup = Please note: * Store backups in a safe and secure place - they contain sensitive information. * Make sure your wiki configuration backup_* values are correct and complete. * Make sure the backup file you get contains everything you need in case of problems. * Make sure it is downloaded without problems. To get a backup, just click here:""", wiki=True)) request.write(""" <form action="%(baseurl)s/%(pagename)s" method="POST" enctype="multipart/form-data"> <input type="hidden" name="action" value="backup"> <input type="hidden" name="do" value="backup"> <input type="submit" value="%(backup_button)s"> </form> """ % { 'baseurl': request.script_root, 'pagename': wikiutil.quoteWikinameURL(pagename), 'backup_button': _('Backup'), }) request.write(request.formatter.endContent()) request.theme.send_footer(pagename) request.theme.send_closing_html()
def attachment_link(self, url, text, **kw): _ = self.request.getText pagename = self.page.page_name target = AttachFile.getAttachUrl(pagename, url, self.request) return (self.url(1, target, title="attachment:%s" % wikiutil.quoteWikinameURL(url)) + self.text(text) + self.url(0))
def sendBackupForm(request, pagename): _ = request.getText request.setContentLanguage(request.lang) title = _('Wiki Backup') request.theme.send_title(title, pagename=pagename) request.write(request.formatter.startContent("content")) request.write( _("""= Downloading a backup = Please note: * Store backups in a safe and secure place - they contain sensitive information. * Make sure your wiki configuration backup_* values are correct and complete. * Make sure the backup file you get contains everything you need in case of problems. * Make sure it is downloaded without problems. To get a backup, just click here:""", wiki=True)) request.write( """ <form action="%(baseurl)s/%(pagename)s" method="POST" enctype="multipart/form-data"> <input type="hidden" name="action" value="backup"> <input type="hidden" name="do" value="backup"> <input type="submit" value="%(backup_button)s"> </form> """ % { 'baseurl': request.script_root, 'pagename': wikiutil.quoteWikinameURL(pagename), 'backup_button': _('Backup'), }) request.write(request.formatter.endContent()) request.theme.send_footer(pagename) request.theme.send_closing_html()
def prepare_node(self, node_name, node, orphaned_category): """ Prepare the wiki tree node Calculates the totals and the html code for the node. @param node name: @param path: list of nodes up to this one """ # Sort sub nodes node['categories'].sort() node['pages'].sort() node['attachments'].sort() # Calculate subnode counts node['categories_count'] = len(node['categories']) node['pages_count'] = len(node['pages']) node['attachments_count'] = len(node['attachments']) if not node['display_name']: node['display_name'] = node_name node['url'] = '%s/%s' % (self.request.getScriptname(), wikiutil.quoteWikinameURL(node_name)) orphaned_category[node['type']].append(node_name) # Build the html code for the link title = self.node_description(node) link_html = u'<a class="node" href="%s" title="%s">%s</a>' % (node['url'], title, node['display_name']) node['html'] = self.node_icon_html[node['type']] + link_html return
def logo(self): logo = u'' if self.cfg.logo_string: pagename = wikiutil.getFrontPage(self.request).page_name pagename = wikiutil.quoteWikinameURL(pagename) logo = wikiutil.link_tag(self.request, pagename, self.cfg.logo_string, css_class="logo") return logo
def getAttachUrl(pagename, filename, request, addts=0, escaped=0, do='get'): """ Get URL that points to attachment `filename` of page `pagename`. If 'addts' is true, a timestamp with the file's modification time is added, so that browsers reload a changed file. """ if htdocs_access(request): # direct file access via webserver timestamp = '' if addts: try: timestamp = '?ts=%s' % os.path.getmtime( getFilename(request, pagename, filename)) except IOError: pass url = "%s/%s/attachments/%s%s" % ( request.cfg.attachments['url'], wikiutil.quoteWikinameFS(pagename), wikiutil.url_quote(filename), timestamp) else: # send file via CGI if do not in ['get', 'view']: do = 'get' url = "%s/%s?action=%s&do=%s&target=%s" % ( request.getScriptname(), wikiutil.quoteWikinameURL(pagename), action_name, do, wikiutil.url_quote_plus(filename)) if escaped: url = wikiutil.escape(url) return url
def gedit_drawing(self, url, text, **kw): # This is called for displaying a drawing image by gui editor. _ = self.request.getText # TODO: this 'text' argument is kind of superfluous, replace by using alt=... kw arg # ToDo: make this clickable for the gui editor if 'alt' not in kw or not kw['alt']: kw['alt'] = text # we force the title here, needed later for html>wiki converter kw['title'] = "drawing:%s" % wikiutil.quoteWikinameURL(url) pagename, drawing = AttachFile.absoluteName(url, self.page.page_name) containername = wikiutil.taintfilename(drawing) drawing_url = AttachFile.getAttachUrl(pagename, containername, self.request) ci = AttachFile.ContainerItem(self.request, pagename, containername) if not ci.exists(): title = _( 'Create new drawing "%(filename)s (opens in new window)"') % { 'filename': self.text(containername) } img = self.icon( 'attachimg' ) # TODO: we need a new "drawimg" in similar grey style and size css = 'nonexistent' return self.url(1, drawing_url, css=css, title=title) + img + self.url(0) kw['src'] = ci.member_url('drawing.png') return self.image(**kw)
def renderInText(self): """ Render macro in text context The parser should decide what to do if this macro is placed in a paragraph context. """ _ = self.request.getText # Default to show page instead of an error message (too lazy to # do an error message now). action = self.args.get('action', 'show') # Use translated text or action name text = self.args.get('text', action) text = _(text, formatted=False) # Escape user input action = wikiutil.escape(action, 1) text = wikiutil.escape(text, 1) # Create link formatter = self.macro.formatter page = wikiutil.quoteWikinameURL(formatter.page.page_name) url = '%s?action=%s' % (page, action) link = wikiutil.link_tag(self.request, url, text=text, formatter=formatter) return link
def editorLink(self, page): """ Return a link to the editor If the user can't edit, return a disabled edit link. If the user want to show both editors, it will display "Edit (Text)", otherwise as "Edit". """ #if not (page.isWritable() and # self.request.user.may.write(page.page_name)): # return self.disabledEdit() _ = self.request.getText params = (wikiutil.quoteWikinameURL(page.page_name) + '?action=edit&editor=') guiworks = self.guiworks(page) if self.showBothEditLinks() and guiworks: text = _('Edit (Text)', formatted=False) params = params + 'text' attrs = {'name': "texteditlink"} else: text = _('Edit', formatted=False) if guiworks: # 'textonly' will be upgraded dynamically to 'guipossible' by JS params = params + 'textonly' attrs = {'name': "editlink"} else: params = params + 'text' attrs = {'name': "texteditlink"} return wikiutil.link_tag(self.request, params, text, **attrs)
def render(self): """ Redirect to the new page, using edit action and template """ error = self.checkAndCombineArguments() or self.checkPermissions() if error: # Send back to the page you came from, with an error msg page = Page(self.request, self.referrer) page.send_page(self.request, msg=error) else: # Redirect to new page using edit action. No error checking # is needed because it is done later in new request. pagename = self.pagename query = {'action': 'edit', 'backto': self.referrer} template = self.request.form.get('template', [''])[0] if template: from MoinMoin.wikiutil import quoteWikinameURL query['template'] = quoteWikinameURL(template) parent = self.request.form.get('parent', [''])[0] if parent: pagename = "%s/%s" % (parent, pagename) url = Page(self.request, pagename).url(self.request, query, 0) self.request.http_redirect(url) raise MoinMoinNoFooter return ''
def attachment_drawing(self, url, text, **kw): _ = self.request.getText pagename = self.page.page_name image = url + u'.png' fname = wikiutil.taintfilename(image) fpath = AttachFile.getFilename(self.request, pagename, fname) return self.image( title="drawing:%s" % wikiutil.quoteWikinameURL(url), src=AttachFile.getAttachUrl(pagename, image, self.request, addts=1))
def revert_link(self, page): try: rev = self.request.rev except AttributeError: return u'' if not (rev and page.isWritable() and self.request.user.may.revert(page.page_name)): return u'' params = '%s?action=revert&rev=%d' % (wikiutil.quoteWikinameURL(page.page_name), rev) return wikiutil.link_tag(self.request, params, self._('Revert'), css_class="revert")
def makeform(self, error=""): """ Display a package page form The form might contain an error that happened when package file was not given. """ from MoinMoin.widget.dialog import Dialog _ = self.request.getText if error: error = u'<p class="error">%s</p>\n' % error d = { 'baseurl': self.request.getScriptname(), 'error': error, 'action': self.__class__.__name__, 'pagename': wikiutil.escape(self.pagename, True), 'pagename_quoted': wikiutil.quoteWikinameURL(self.pagename), 'include_attachments_label': _('Include all attachments?'), 'package': _('Package pages'), 'cancel': _('Cancel'), 'newname_label': _("Package name"), 'list_label': _("List of page names - separated by a comma"), } form = ''' %(error)s <form method="post" action="%(baseurl)s/%(pagename_quoted)s"> <input type="hidden" name="action" value="%(action)s"> <table> <tr> <td class="label"><label>%(newname_label)s</label></td> <td class="content"> <input type="text" name="packagename" value="package.zip" size="80"> </td> </tr> <tr> <td class="label"><label>%(list_label)s</label></td> <td class="content"> <input type="text" name="pagelist" size="80" maxlength="200" value="%(pagename)s"> </td> </tr> <tr> <td class="label"> %(include_attachments_label)s<input type="checkbox" name="include_attachments" value="0" %(include_attachments_label)s> </td> </tr> <tr> <td></td> <td class="buttons"> <input type="submit" name="submit" value="%(package)s"> <input type="submit" name="cancel" value="%(cancel)s"> </td> </tr> </table> </form>''' % d return Dialog(self.request, content=form)
def visit(self, request, name, depth): """ Visit a page, i.e. create a link. """ if not name: return self.append(' ' * (5*depth)) self.append(' ' + wikiutil.link_tag(request, '%s?action=%s' % (wikiutil.quoteWikinameURL(name), __name__.split('.')[-1]), name)) self.append(" <small>[") self.append(Page(request, name).link_to(request, 'view')) self.append("</small>]<br>")
def interwikilink(self, on, interwiki='', pagename='', **kw): """ @keyword title: override using the interwiki wikiname as title """ if not on: return self.url(0) # return '</a>' html_class = 'badinterwiki' # we use badinterwiki in any case to simplify reverse conversion href = wikiutil.quoteWikinameURL(pagename) or "/" # FCKeditor behaves strange on empty href title = kw.get('title', interwiki) return self.url(1, href, title=title, css=html_class) # interwiki links with pages with umlauts
def attachment_image(self, url, **kw): _ = self.request.getText # we force the title here, needed later for html>wiki converter kw['title'] = "attachment:%s" % wikiutil.quoteWikinameURL(url) pagename = self.page.page_name if '/' in url: pagename, target = AttachFile.absoluteName(url, pagename) url = url.split('/')[-1] kw['src'] = AttachFile.getAttachUrl(pagename, url, self.request, addts=1) return self.image(**kw)
def more_link(self, d, **keywords): _ = self.request.getText page = d['page'] if not self.shouldShowEditbar(page): return u'' params = (wikiutil.quoteWikinameURL(page.page_name) + '?action=allactions') text = _('Other', formatted=False) attrs = {'id': "otherlink"} return wikiutil.link_tag(self.request, params, text, **attrs)
def _add_refresh(self, formatter, cache, arena, key): _ = self._ refresh = wikiutil.link_tag( formatter.request, wikiutil.quoteWikinameURL(formatter.page.page_name) + "?action=refresh&arena=%s&key=%s" % (arena, key), _("RefreshCache") ) + ' ' + _('for this page (cached %(date)s)') % { 'date': formatter.request.user.getFormattedDateTime(cache.mtime()), } + '<br>' self.request.add2footer('RefreshCache', refresh)
def send_uploadform(pagename, request): """ Send the HTML code for the list of already stored attachments and the file upload form. """ _ = request.getText if not request.user.may.read(pagename): request.write('<p>%s</p>' % _('You are not allowed to view this page.')) return writeable = request.user.may.write(pagename) # First send out the upload new attachment form on top of everything else. # This avoids usability issues if you have to scroll down a lot to upload # a new file when the page already has lots of attachments: if writeable: request.write('<h2>' + _("New Attachment") + '</h2>') request.write(""" <form action="%(baseurl)s/%(pagename)s" method="POST" enctype="multipart/form-data"> <dl> <dt>%(upload_label_file)s</dt> <dd><input type="file" name="file" size="50"></dd> <dt>%(upload_label_rename)s</dt> <dd><input type="text" name="rename" size="50" value="%(rename)s"></dd> <dt>%(upload_label_overwrite)s</dt> <dd><input type="checkbox" name="overwrite" value="1" %(overwrite_checked)s></dd> </dl> %(textcha)s <p> <input type="hidden" name="action" value="%(action_name)s"> <input type="hidden" name="do" value="upload"> <input type="submit" value="%(upload_button)s"> </p> </form> """ % { 'baseurl': request.getScriptname(), 'pagename': wikiutil.quoteWikinameURL(pagename), 'action_name': action_name, 'upload_label_file': _('File to upload'), 'upload_label_rename': _('Rename to'), 'rename': request.form.get('rename', [''])[0], 'upload_label_overwrite': _('Overwrite existing attachment of same name'), 'overwrite_checked': ('', 'checked')[request.form.get('overwrite', ['0'])[0] == '1'], 'upload_button': _('Upload'), 'textcha': TextCha(request).render(), }) request.write('<h2>' + _("Attached Files") + '</h2>') request.write(_get_filelist(request, pagename)) if not writeable: request.write('<p>%s</p>' % _('You are not allowed to attach a file to this page.')) if writeable and request.form.get('drawing', [None])[0]: send_hotdraw(pagename, request)
def _do_move(pagename, request): _ = request.getText pagename, filename, fpath = _access_file(pagename, request) if not request.user.may.delete(pagename): return _('You are not allowed to move attachments from this page.') if not filename: return # error msg already sent in _access_file # move file d = {'action': action_name, 'baseurl': request.getScriptname(), 'do': 'attachment_move', 'ticket': wikiutil.createTicket(request), 'pagename': pagename, 'pagename_quoted': wikiutil.quoteWikinameURL(pagename), 'attachment_name': filename, 'move': _('Move'), 'cancel': _('Cancel'), 'newname_label': _("New page name"), 'attachment_label': _("New attachment name"), } formhtml = ''' <form action="%(baseurl)s/%(pagename_quoted)s" method="POST"> <input type="hidden" name="action" value="%(action)s"> <input type="hidden" name="do" value="%(do)s"> <input type="hidden" name="ticket" value="%(ticket)s"> <table> <tr> <td class="label"><label>%(newname_label)s</label></td> <td class="content"> <input type="text" name="newpagename" value="%(pagename)s" size="80"> </td> </tr> <tr> <td class="label"><label>%(attachment_label)s</label></td> <td class="content"> <input type="text" name="newattachmentname" value="%(attachment_name)s" size="80"> </td> </tr> <tr> <td></td> <td class="buttons"> <input type="hidden" name="oldattachmentname" value="%(attachment_name)s"> <input type="submit" name="move" value="%(move)s"> <input type="submit" name="cancel" value="%(cancel)s"> </td> </tr> </table> </form>''' % d thispage = Page(request, pagename) request.theme.add_msg(formhtml, "dialog") return thispage.send_page()
def editbar(self, d): """ Assemble the page edit bar. Display on existing page. Replace iconbar, showtext, edit text, refresh cache and available actions. @param d: parameter dictionary @rtype: unicode @return: iconbar html """ page = d['page'] if not self.shouldShowEditbar(page): return '' # Use cached editbar if possible. cacheKey = 'editbar' cached = self._cache.get(cacheKey) if cached: return cached # Make new edit bar request = self.request _ = self.request.getText link = wikiutil.link_tag quotedname = wikiutil.quoteWikinameURL(page.page_name) links = [] add = links.append # Parent page parent = page.getParentPage() if parent: add(parent.link_to(request, _("Show Parent", formatted=False))) # Page actions if page.isWritable() and request.user.may.write(page.page_name): add(link(request, quotedname + '?action=edit', _('Edit'))) else: add(_('Immutable Page', formatted=False)) add(link(request, quotedname + '?action=diff', _('Show Changes', formatted=False))) add(link(request, quotedname + '?action=info', _('Get Info', formatted=False))) add(self.subscribeLink(page)) add(self.actionsMenu(page)) # Format items = '\n'.join(['<li>%s</li>' % item for item in links if item != '']) html = u'<ul class="editbar">\n%s\n</ul>\n' % items # cache for next call self._cache[cacheKey] = html return html
def deleteform(): # Javascript codes for deleting or restoring a comment request = Globs.macro.request _ = request.getText htmlresult = [] html = [ '<script language="javascript">', '<!--', ] htmlresult.append(u'\n'.join(html)) html = [ ' function requesttodeleteadmin%d(delform, comkey) {' % Globs.formid, ' if (confirm("%s")) {;' % _('Really delete this comment?'), ' delform.delkey.value = comkey;', ' delform.delpasswd.value = "****";', ' delform.submit();', ' }', ' }', ' function requesttodelete%d(delform, comkey) {' % Globs.formid, ' var passwd = prompt("%s:", "");' % _('Please specify a password!'), ' if(!(passwd == "" || passwd == null)) {', ' delform.delkey.value = comkey;', ' delform.delpasswd.value = passwd;', ' delform.submit();', ' }', ' }', ] htmlresult.append(u'\n'.join(html)) page_url = wikiutil.quoteWikinameURL(Globs.cursubname) html = [ '//-->', '</script>', '<form name="delform%d" action="%s#pagecomment%d" METHOD="post">' % (Globs.formid, page_url, Globs.formid), '<input type="hidden" value="show" name="action">', '<input name="delpasswd" type="hidden" value="****">', '<input name="delkey" type="hidden" value="">', '<input type="hidden" name="commentaction" value="delcomment%s">' % Globs.formid, '</form>', ] htmlresult.append(u'\n'.join(html)) return u'\n'.join(htmlresult)
def edit_link(self, d, **keywords): _ = self.request.getText page = d['page'] text = _('Edit', formatted=False) # if not self.shouldShowEditbar(page): # return u'' if not (page.isWritable() and self.request.user.may.write(page.page_name)): return u'<span id="editlink">%s</span>' % text params = (wikiutil.quoteWikinameURL(page.page_name) + '?action=edit') attrs = {'id': "editlink"} return wikiutil.link_tag(self.request, params, text, **attrs)
def send_link_rel(request, pagename): files = _get_files(request, pagename) if len(files) > 0 and not htdocs_access(request): scriptName = request.getScriptname() pagename_quoted = wikiutil.quoteWikinameURL(pagename) for file in files: url = "%s/%s?action=%s&do=view&target=%s" % ( scriptName, pagename_quoted, action_name, wikiutil.url_quote_plus(file)) request.write(u'<link rel="Appendix" title="%s" href="%s">\n' % ( wikiutil.escape(file), wikiutil.escape(url)))
def attachment_link(self, on, url=None, **kw): assert on in (0, 1, False, True) # make sure we get called the new way, not like the 1.5 api was _ = self.request.getText querystr = kw.get('querystr', {}) assert isinstance(querystr, dict) # new in 1.6, only support dicts if 'do' not in querystr: querystr['do'] = 'view' if on: pagename = self.page.page_name target = AttachFile.getAttachUrl(pagename, url, self.request, do=querystr['do']) return self.url(on, target, title="attachment:%s" % wikiutil.quoteWikinameURL(url)) else: return self.url(on)
def attach_link(self, d, **keywords): _ = self.request.getText page = d['page'] if not self.shouldShowEditbar(page): return u'' if not (page.isWritable() and self.request.user.may.write(page.page_name)): return u'' params = (wikiutil.quoteWikinameURL(page.page_name) + '?action=AttachFile') text = _('Attach', formatted=False) attrs = {'id': "attachlink"} return wikiutil.link_tag(self.request, params, text, **attrs)
def searchform(self, d): """ assemble HTML code for the search forms @param d: parameter dictionary @rtype: unicode @return: search form html """ _ = self.request.getText form = self.request.form updates = { # Rick - commented out because we don't need it. We wrap this in the panel above: #'search_label': _('Search:'), 'search_value': wikiutil.escape(form.get('value', [''])[0], 1), 'search_full_label': _('Text'), 'search_title_label': _('Titles'), 'baseurl': self.request.getScriptname(), 'pagename_quoted': wikiutil.quoteWikinameURL(d['page'].page_name), } d.update(updates) # Rick - paste this in below if you want a needless field label. # <label for="searchinput">%(search_label)s</label> # Rick - I also whack the 'size' from input id because that belongs in CSS. html = u''' <form id="searchform" method="get" action="%(baseurl)s/%(pagename_quoted)s"> <div> <input type="hidden" name="action" value="fullsearch"> <input type="hidden" name="context" value="180"> <input id="searchinput" type="text" name="value" value="%(search_value)s" onfocus="searchFocus(this)" onblur="searchBlur(this)" onkeyup="searchChange(this)" onchange="searchChange(this)" alt="this"> <div id="searchbuttons"> <input id="titlesearch" name="titlesearch" type="submit" value="%(search_title_label)s" alt="Search Titles"> <input id="fullsearch" name="fullsearch" type="submit" value="%(search_full_label)s" alt="Search Full Text"> </div> </div> </form> <script type="text/javascript"> // Initialize search form // var f = document.getElementById('searchform'); // f.getElementsByTagName('label')[0].style.display = 'none'; var e = document.getElementById('searchinput'); e.value = ""; searchChange(e); searchBlur(e); </script> ''' % d return html
def search_box(type, macro): """ Make a search box Make both Title Search and Full Search boxes, according to type. @param type: search box type: 'titlesearch' or 'fullsearch' @rtype: unicode @return: search box html fragment """ _ = macro._ if 'value' in macro.form: default = wikiutil.escape(macro.form["value"][0], quote=1) else: default = '' # Title search settings boxes = '' button = _("Search Titles") # Special code for fullsearch if type == "fullsearch": boxes = [ u'<br>', u'<input type="checkbox" name="context" value="160" checked="checked">', _('Display context of search results'), u'<br>', u'<input type="checkbox" name="case" value="1">', _('Case-sensitive searching'), ] boxes = u'\n'.join(boxes) button = _("Search Text") # Format type = (type == "titlesearch") html = [ u'<form method="get" action="%s/%s">' % (macro.request.getScriptname(), wikiutil.quoteWikinameURL(macro.request.formatter.page.page_name)), u'<div>', u'<input type="hidden" name="action" value="fullsearch">', u'<input type="hidden" name="titlesearch" value="%i">' % type, u'<input type="text" name="value" size="30" value="%s">' % default, u'<input type="submit" value="%s">' % button, boxes, u'</div>', u'</form>', ] html = u'\n'.join(html) return macro.formatter.rawHTML(html)
def redirect_last_visited(request): pagetrail = request.user.getTrail() if pagetrail: # Redirect to last page visited last_visited = pagetrail[-1] wikiname, pagename = wikiutil.split_interwiki(last_visited) if wikiname != 'Self': wikitag, wikiurl, wikitail, error = wikiutil.resolve_interwiki(request, wikiname, pagename) url = wikiurl + wikiutil.quoteWikinameURL(wikitail) else: url = Page(request, pagename).url(request) else: # Or to localized FrontPage url = wikiutil.getFrontPage(request).url(request) url = request.getQualifiedURL(url) return abort(redirect(url))
def make_iconlink(self, which, d): """ Make a link with an icon @param which: icon id (dictionary key) @param d: parameter dictionary @rtype: string @return: html link tag """ page_name, querystr, title, icon = self.button_table[which] d['title'] = title % d d['i18ntitle'] = self.request.getText(d['title'], formatted=False) img_src = self.make_icon(icon, d) attrs = { 'rel': 'nofollow', 'title': d['i18ntitle'], } if page_name: page = Page(self.request, page_name % d) else: page = d['page'] if self.is_moin_1_5: # Moin 1.5.x url = wikiutil.quoteWikinameURL(page.page_name) querystr = wikiutil.makeQueryString(querystr) if querystr: url = '%s?%s' % (url, querystr) html = wikiutil.link_tag(self.request, url, img_src, title="%(i18ntitle)s" % d) else: # Moin 1.6 rev = d['rev'] if rev and which in [ 'raw', 'print', ]: querystr['rev'] = str(rev) html = page.link_to_raw(self.request, text=img_src, querystr=querystr, **attrs) return html
def execute(macro, text, args_re=re.compile(_args_re_pattern), title_re=re.compile(_title_re, re.M), called_by_toc=0): request = macro.request _ = request.getText # return immediately if getting links for the current page if request.mode_getpagelinks: return '' # parse and check arguments args = text and args_re.match(text) if not args: return (_sysmsg % ('error', _('Invalid include arguments "%s"!')) % (text, )) # prepare including page result = [] print_mode = macro.form.has_key('action') and macro.form['action'][0] in ( "print", "format") this_page = macro.formatter.page if not hasattr(this_page, '_macroInclude_pagelist'): this_page._macroInclude_pagelist = {} # get list of pages to include inc_name = wikiutil.AbsPageName(request, this_page.page_name, args.group('name')) pagelist = [inc_name] if inc_name.startswith("^"): try: inc_match = re.compile(inc_name) except re.error: pass # treat as plain page name else: # Get user filtered readable page list pagelist = request.rootpage.getPageList(filter=inc_match.match) # sort and limit page list pagelist.sort() sort_dir = args.group('sort') if sort_dir == 'descending': pagelist.reverse() max_items = args.group('items') if max_items: pagelist = pagelist[:int(max_items)] skipitems = 0 if args.group("skipitems"): skipitems = int(args.group("skipitems")) titlesonly = args.group('titlesonly') editlink = args.group('editlink') # iterate over pages for inc_name in pagelist: if not request.user.may.read(inc_name): continue if this_page._macroInclude_pagelist.has_key(inc_name): result.append( u'<p><strong class="error">Recursive include of "%s" forbidden</strong></p>' % (inc_name, )) continue if skipitems: skipitems -= 1 continue fmt = macro.formatter.__class__(request, is_included=True) fmt._base_depth = macro.formatter._base_depth inc_page = Page(request, inc_name, formatter=fmt) if not inc_page.exists(): continue inc_page._macroInclude_pagelist = this_page._macroInclude_pagelist # check for "from" and "to" arguments (allowing partial includes) body = inc_page.get_raw_body() + '\n' # body = body.replace(this_page.page_name, "_" + this_page.page_name + "_") body = body.replace('amcl', "_" + this_page.page_name + "_") # set or increment include marker this_page._macroInclude_pagelist[inc_name] = \ this_page._macroInclude_pagelist.get(inc_name, 0) + 1 # output the included page strfile = StringIO.StringIO() request.redirect(strfile) try: cid = request.makeUniqueID( "Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name)) inc_page.send_page(request, content_only=1, content_id=cid, omit_footnotes=True) result.append(strfile.getvalue()) finally: request.redirect() # decrement or remove include marker if this_page._macroInclude_pagelist[inc_name] > 1: this_page._macroInclude_pagelist[inc_name] = \ this_page._macroInclude_pagelist[inc_name] - 1 else: del this_page._macroInclude_pagelist[inc_name] # return include text str = ''.join(result) return str
def actionsMenu(self, page): """ Create actions menu list and items data dict The menu will contain the same items always, but items that are not available will be disabled (some broken browsers will let you select disabled options though). The menu should give best user experience for javascript enabled browsers, and acceptable behavior for those who prefer not to use Javascript. TODO: Move actionsMenuInit() into body onload - requires that the theme will render body, it is currently done in wikiutil/page. @param page: current page, Page object @rtype: unicode @return: actions menu html fragment """ request = self.request _ = request.getText rev = request.rev # rev was a hidden input within the more actions form # alternative will be to append it to anchor urls if rev: revision = '&rev=%s' % rev else: revision = '' menu = [ 'raw', 'print', 'RenderAsDocbook', 'refresh', #'__separator__', 'SpellCheck', 'LikePages', 'LocalSiteMap', #'__separator__', 'RenamePage', 'CopyPage', 'DeletePage', #'__separator__', 'MyPages', 'SubscribeUser', #'__separator__', 'Despam', 'revert', 'PackagePages', 'SyncPages', ] titles = { # action: menu title '__title__': _("More Actions:"), # Rick: Set separator to blank, as that looks better in our drop down menu: '__separator__': _(''), 'raw': _('Raw Text'), 'print': _('Print View'), 'refresh': _('Delete Cache'), 'SpellCheck': _('Check Spelling'), # rename action! 'RenamePage': _('Rename Page'), 'CopyPage': _('Copy Page'), 'DeletePage': _('Delete Page'), 'LikePages': _('Like Pages'), 'LocalSiteMap': _('Local Site Map'), 'MyPages': _('My Pages'), 'SubscribeUser': _('Subscribe User'), 'Despam': _('Remove Spam'), 'revert': _('revert to this revision'), 'PackagePages': _('Package Pages'), 'RenderAsDocbook': _('Render as Docbook'), 'SyncPages': _('Sync Pages'), } options = [] #original: option = '<option value="%(action)s"%(disabled)s>%(title)s</option>' option = '<li><a href="%(baseurl)s?action=%(action)s%(revision)s">%(title)s</a></li>' disabledOption = '<li class="disabled">%(title)s</li>' # class="disabled" is a workaround for browsers that ignore # "disabled", e.g IE, Safari # for XHTML: data['disabled'] = ' disabled="disabled"' disabled = ' disabled class="disabled"' # @@@ is this best way to form link to current page? Had trouble with subpages replicating parent page name in url # baseurl is full url as used here baseurl = self.request.getScriptname( ) + '/' + wikiutil.quoteWikinameURL(page.page_name) # Format standard actions available = get_available_actions(request.cfg, page, request.user) for action in menu: data = { 'action': action, 'disabled': '', 'title': titles[action], 'baseurl': baseurl, 'revision': revision, } # removes excluded actions from the more actions menu if action in request.cfg.actions_excluded: continue # Enable delete cache only if page can use caching if action == 'refresh': if not page.canUseCache(): data['action'] = 'show' data['disabled'] = disabled # revert action enabled only if user can revert if action == 'revert' and not request.user.may.revert( page.page_name): data['action'] = 'show' data['disabled'] = disabled # SubscribeUser action enabled only if user has admin rights if action == 'SubscribeUser' and not request.user.may.admin( page.page_name): data['action'] = 'show' data['disabled'] = disabled # PackagePages action only if user has write rights if action == 'PackagePages' and not request.user.may.write( page.page_name): data['action'] = 'show' data['disabled'] = disabled # Despam action enabled only for superusers if action == 'Despam' and not request.user.isSuperUser(): data['action'] = 'show' data['disabled'] = disabled # Special menu items. Without javascript, executing will # just return to the page. if action.startswith('__'): data['action'] = 'show' # Actions which are not available for this wiki, user or page if (action == '__separator__' or (action[0].isupper() and not action in available)): data['disabled'] = disabled #~ options.append(option % data) # @@@ if data['disabled']: options.append(disabledOption % data) else: options.append(option % data) # Add custom actions not in the standard menu, except for # some actions like AttachFile (we have them on top level) more = [ item for item in available if not item in titles and not item in ('AttachFile', ) ] more.sort() if more: # Add separator #~ separator = option % {'action': 'show', 'disabled': disabled, # @@@ #~ 'title': titles['__separator__'], 'baseurl': baseurl,} # @@@ deleted by last fix #~ 'title': titles['__separator__'], 'baseurl': baseurl, 'revision': revision,} # @@@ separator = disabledOption % { 'action': 'show', 'disabled': disabled, 'title': titles['__separator__'], 'baseurl': baseurl, } options.append(separator) # Add more actions (all enabled) for action in more: data = { 'action': action, 'disabled': '', 'baseurl': baseurl, 'revision': revision, } # Always add spaces: AttachFile -> Attach File # XXX do not create page just for using split_title - # creating pages for non-existent does 2 storage lookups #title = Page(request, action).split_title(force=1) title = action # Use translated version if available data['title'] = _(title) options.append(option % data) data = { 'label': titles['__title__'], 'options': '\n'.join(options), 'rev_field': rev and '<input type="hidden" name="rev" value="%d">' % rev or '', 'do_button': _("Do"), 'baseurl': self.request.getScriptname(), 'pagename_quoted': wikiutil.quoteWikinameURL(page.page_name), } html = ''' <div class="togglelink" id="togglelink" onclick="toggleMenu('menu1')">[ more options ]</div> <div id="menu1"> <ul> %(options)s </ul> </div> ''' % data return html
class PluginScript(script.MoinScript): """\ Purpose: ======== This tool allows you to dump MoinMoin wiki pages to static HTML files. Detailed Instructions: ====================== General syntax: moin [options] export dump [dump-options] [options] usually should be: --config-dir=/path/to/my/cfg/ --wiki-url=http://wiki.example.org/ [dump-options] see below: 0. You must run this script as owner of the wiki files, usually this is the web server user. 1. To dump all the pages on the wiki to the directory '/mywiki' moin ... export dump --target-dir=/mywiki 2. To dump all the pages readable by 'JohnSmith' on the wiki to the directory '/mywiki' moin ... export dump --target-dir=/mywiki --username JohnSmith """ def __init__(self, argv=None, def_values=None): script.MoinScript.__init__(self, argv, def_values) self.parser.add_option("-t", "--target-dir", dest="target_dir", help="Write html dump to DIRECTORY") self.parser.add_option( "-u", "--username", dest="dump_user", help="User the dump will be performed as (for ACL checks, etc)") def mainloop(self): """ moin-dump's main code. """ # Prepare output directory if not self.options.target_dir: script.fatal( "you must use --target-dir=/your/output/path to specify the directory we write the html files to" ) outputdir = os.path.abspath(self.options.target_dir) try: os.mkdir(outputdir) script.log("Created output directory '%s'!" % outputdir) except OSError, err: if err.errno != errno.EEXIST: script.fatal("Cannot create output directory '%s'!" % outputdir) # Insert config dir or the current directory to the start of the path. config_dir = self.options.config_dir if config_dir and os.path.isfile(config_dir): config_dir = os.path.dirname(config_dir) if config_dir and not os.path.isdir(config_dir): script.fatal("bad path given to --config-dir option") sys.path.insert(0, os.path.abspath(config_dir or os.curdir)) self.init_request() request = self.request # fix script_root so we get relative paths in output html request.script_root = url_prefix_static # use this user for permissions checks request.user = user.User(request, name=self.options.dump_user) pages = request.rootpage.getPageList( user='') # get list of all pages in wiki pages.sort() if self.options.page: # did user request a particular page or group of pages? try: namematch = re.compile(self.options.page) pages = [page for page in pages if namematch.match(page)] if not pages: pages = [self.options.page] except: pages = [self.options.page] wikiutil.quoteWikinameURL = lambda pagename, qfn=wikiutil.quoteWikinameFS: ( qfn(pagename) + HTML_SUFFIX) AttachFile.getAttachUrl = lambda pagename, filename, request, **kw: _attachment( request, pagename, filename, outputdir, **kw) errfile = os.path.join(outputdir, 'error.log') errlog = open(errfile, 'w') errcnt = 0 page_front_page = wikiutil.getLocalizedPage( request, request.cfg.page_front_page).page_name page_title_index = wikiutil.getLocalizedPage(request, 'TitleIndex').page_name page_word_index = wikiutil.getLocalizedPage(request, 'WordIndex').page_name navibar_html = '' for p in [page_front_page, page_title_index, page_word_index]: navibar_html += '[<a href="%s">%s</a>] ' % ( wikiutil.quoteWikinameURL(p), wikiutil.escape(p)) urlbase = request.url # save wiki base url for pagename in pages: # we have the same name in URL and FS file = wikiutil.quoteWikinameURL(pagename) script.log('Writing "%s"...' % file) try: pagehtml = '' request.url = urlbase + pagename # add current pagename to url base page = Page.Page(request, pagename) request.page = page try: request.reset() pagehtml = request.redirectedOutput(page.send_page, count_hit=0, content_only=1) except: errcnt = errcnt + 1 print >> sys.stderr, "*** Caught exception while writing page!" print >> errlog, "~" * 78 print >> errlog, file # page filename import traceback traceback.print_exc(None, errlog) finally: timestamp = time.strftime("%Y-%m-%d %H:%M") filepath = os.path.join(outputdir, file) fileout = codecs.open(filepath, 'w', config.charset) fileout.write( page_template % { 'charset': config.charset, 'pagename': pagename, 'pagehtml': pagehtml, 'logo_html': logo_html, 'navibar_html': navibar_html, 'timestamp': timestamp, 'theme': request.cfg.theme_default, }) fileout.close() # copy FrontPage to "index.html" indexpage = page_front_page if self.options.page: indexpage = pages[ 0] # index page has limited use when dumping specific pages, but create one anyway shutil.copyfile( os.path.join(outputdir, wikiutil.quoteWikinameFS(indexpage) + HTML_SUFFIX), os.path.join(outputdir, 'index' + HTML_SUFFIX)) errlog.close() if errcnt: print >> sys.stderr, "*** %d error(s) occurred, see '%s'!" % ( errcnt, errfile)
def html_head(self, d): html = ThemeBase.html_head(self, d) html += '\n<link rel="canonical" href="http://wiki.ros.org/%s" />' % wikiutil.quoteWikinameURL(d['page'].page_name) return html
def _emit(request, pagename): """ Send pagename, encode it if it contains spaces """ request.write(wikiutil.quoteWikinameURL(pagename))
def commentform(tmpauthor, tmptext, tmppasswd, tmpicon, comrev, tmpautopass, tmpmarkup, rating): # A form for posting a new comment request = Globs.macro.request datapagename = Globs.datapagename _ = request.getText cellstyle = u'border-width: 0px; vertical-align: middle; font-size: 0.9em;' pg = Page(request, datapagename) if pg.exists(): comrev = pg.current_rev() else: comrev = 0 if not Params.nosmiley: if not Params.smileylist: iconlist = getsmileymarkupradio(tmpicon) else: iconlist = getsmileymarkuplist(tmpicon) else: iconlist = '' initName = '' initPass = '' initText = '' if not (request.user.valid or tmpauthor): tmpauthor = getAuthorFromCookie() if not tmpauthor: import socket host = request.remote_addr try: hostname = socket.gethostbyaddr(host)[0] except socket.error: hostname = host tmpauthor = hostname.split('.')[0] initName = tmpauthor if not tmppasswd: tmppasswd = nicepass() initPass = tmppasswd elif tmpautopass and tmpautopass == tmppasswd: tmppasswd = nicepass() initPass = tmppasswd if not tmptext: tmptext = u'Add your comment' initText = tmptext elif tmptext and tmptext == u'Add your comment': initText = tmptext previewbutton = '' markupcheckbox = '' if Params.markup: if not (tmpmarkup == '0'): markupchecked = "checked" else: markupchecked = '' previewbutton = '<br><input type="submit" name="button_preview" value="%s" style="color: #ff7777; font-size: 9pt; width: 6em; ">' % _( 'Preview') markupcheckbox = '<input type="checkbox" name="commarkup%d" value="1" %s> Markup' % ( Globs.formid, markupchecked) if request.user.valid: html1 = [ u'<input type="hidden" value="%s" name="comauthor">' % request.user.name, u'<input type="hidden" value="*" name="compasswd">', ] authorJavascriptCode = '' onSubmitCode = '' else: html1 = [ u'Username: <input type="text" style="font-size: 9pt;" size="6" maxlength="20" name="comauthor" value="%(author)s" onfocus="if (this.value==\'%(msg)s\') {this.value=\'\';};" onblur="if (this.value==\'\') {this.value=\'%(msg)s\';};">' % { 'msg': wikiutil.escape(initName), 'cellstyle': cellstyle, 'author': wikiutil.escape(tmpauthor) }, u'Password: <input type="password" style="font-size: 9pt;" size="4" maxlength="10" name="compasswd" value="%(passwd)s" onfocus="if (this.value==\'%(msg)s\') {this.value=\'\';};" onblur="if (this.value==\'\') {this.value=\'%(msg)s\';};">' % { 'msg': wikiutil.escape(initPass), 'passwd': wikiutil.escape(tmppasswd) }, u'<input type="hidden" value="%s" name="autopasswd">' % wikiutil.escape(initPass), ] authorJavascriptCode = """ <script language="javascript"> <!-- function setCookie(name, value) { var today = new Date(); var expire = new Date(today.getTime() + 60*60*24*365*1000); document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expire.toGMTString() + "; path=%s"; } function validateForm() { if (document.getElementById('comment').checked && document.getElementById('comment').value == '') { alert("You must select a rating."); return false; } return true; } //--> </script>""" % request.getScriptname() onSubmitCode = 'onSubmit="setCookie(\'PG2AUTHOR\', this.comauthor.value);"' validateJavascriptCode = """ <script language='javascript'> <!-- function validateForm() { rating = document.getElementById('rating'); if (rating.selectedIndex == 0) { alert('You must select a rating.'); return false; } return true; } //--> </script>""" html1 = u'\n'.join(html1) scripthtml = u'onfocus="if (this.value==\'%(msg)s\') {this.value=\'\';};" onblur="if (this.value==\'\') {this.value=\'%(msg)s\';};"' % { 'msg': wikiutil.escape(initText) } page_url = wikiutil.quoteWikinameURL(Globs.cursubname) html2 = [ u'%s' % validateJavascriptCode, u'%s' % authorJavascriptCode, u'<form action="%s#pagecomment%d" id="comment" name="comment" METHOD="POST" %s onsubmit="return validateForm();">' % (page_url, Globs.formid, onSubmitCode), u'<table class="addcommentform">', u'<tr>', u'<td style="%s">Rating: <select id="rating" name="rating"><option value="">Please choose a rating...<option value=1.0>1.0 - Completely useless!<option value=2.0>2.0 - Not very useful.<option value=2.5>2.5 - Neutral.<option value=3.0>3.0 - Useful.<option value=4.0>4.0 - Definately useful!<option value="Comment">Additional comments<option value="helpful">Helpful but not what I was looking for.</option></select> ' % (cellstyle, ), u'</tr>', u'<tr>', u'<td style="%s"><textarea name="comtext" rows="%d" cols="%d" style="font-size: 9pt;" ' % (cellstyle, Params.rows, Params.cols), u'%s>%s</textarea></td></tr>' % (scripthtml, wikiutil.escape(tmptext)), u'<tr><td style="%s vertical-align: bottom;"><input type="submit" name="button_save" value="%s" style="font-size: 9pt; width: 6em; height:3em; ">%s</td>' % (cellstyle, _('Save'), previewbutton), u'</tr>', u'<tr><td style="%s">' % cellstyle, u'%s' % html1, u'%s' % iconlist, u'</td>', u'<td style="%s text-align: right; font-size: 9pt;">%s</td>' % (cellstyle, markupcheckbox), u'</tr>', u'</table>', u'<input type="hidden" name="action" value="show" >', u'<input type="hidden" name="comrev" value="%s">' % comrev, u'<input type="hidden" name="commentaction" value="addcomment%d">' % Globs.formid, u'</form>', ] return u'\n'.join(html2)
def print_abandoned(macro): request = macro.request _ = request.getText output = [] d = {} page = macro.formatter.page pagename = page.page_name d['page'] = page d['q_page_name'] = wikiutil.quoteWikinameURL(pagename) msg = None pages = request.rootpage.getPageList() last_edits = [] for name in pages: log = Page(request, name).editlog_entry() if log: last_edits.append(log) # we don't want all Systempages at the beginning of the abandoned list # line = editlog.EditLogLine({}) # line.pagename = page # line.ed_time = 0 # line.comment = 'not edited' # line.action = '' # line.userid = '' # line.hostname = '' # line.addr = '' # last_edits.append(line) del pages last_edits.sort() # set max size in days max_days = min(int(request.values.get('max_days', 0)), _DAYS_SELECTION[-1]) # default to _MAX_DAYS for users without bookmark if not max_days: max_days = _MAX_DAYS d['rc_max_days'] = max_days # give known user the option to extend the normal display if request.user.valid: d['rc_days'] = _DAYS_SELECTION else: d['rc_days'] = None d['rc_update_bookmark'] = None output.append(request.theme.recentchanges_header(d)) length = len(last_edits) index = 0 last_index = 0 day_count = 0 if length > 0: line = last_edits[index] line.time_tuple = request.user.getTime(wikiutil.version2timestamp(line.ed_time_usecs)) this_day = line.time_tuple[0:3] day = this_day while 1: index += 1 if index > length: break if index < length: line = last_edits[index] line.time_tuple = request.user.getTime(wikiutil.version2timestamp(line.ed_time_usecs)) day = line.time_tuple[0:3] if (day != this_day) or (index == length): d['bookmark_link_html'] = None d['date'] = request.user.getFormattedDate(wikiutil.version2timestamp(last_edits[last_index].ed_time_usecs)) output.append(request.theme.recentchanges_daybreak(d)) this_day = day for page in last_edits[last_index:index]: output.append(format_page_edits(macro, [page], None)) last_index = index day_count += 1 if (day_count >= max_days): break d['rc_msg'] = msg output.append(request.theme.recentchanges_footer(d)) return ''.join(output)
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))
def macro_RecentChanges(macro, abandoned=False): # handle abandoned keyword if abandoned: return print_abandoned(macro) request = macro.request _ = request.getText output = [] user = request.user page = macro.formatter.page pagename = page.page_name d = {} d['page'] = page d['q_page_name'] = wikiutil.quoteWikinameURL(pagename) log = editlog.EditLog(request) tnow = time.time() msg = "" # get bookmark from valid user bookmark_usecs = request.user.getBookmark() or 0 # add bookmark link if valid user d['rc_curr_bookmark'] = None d['rc_update_bookmark'] = None if request.user.valid: d['rc_curr_bookmark'] = _('(no bookmark set)') if bookmark_usecs: currentBookmark = wikiutil.version2timestamp(bookmark_usecs) currentBookmark = user.getFormattedDateTime(currentBookmark) currentBookmark = _('(currently set to %s)') % currentBookmark deleteBookmark = page.link_to(request, _("Delete bookmark"), querystr={'action': 'bookmark', 'time': 'del'}, rel='nofollow') d['rc_curr_bookmark'] = currentBookmark + ' ' + deleteBookmark version = wikiutil.timestamp2version(tnow) d['rc_update_bookmark'] = page.link_to(request, _("Set bookmark"), querystr={'action': 'bookmark', 'time': '%d' % version}, rel='nofollow') # set max size in days max_days = min(int(request.values.get('max_days', 0)), _DAYS_SELECTION[-1]) # default to _MAX_DAYS for useres without bookmark if not max_days and not bookmark_usecs: max_days = _MAX_DAYS d['rc_max_days'] = max_days # give known user the option to extend the normal display if request.user.valid: d['rc_days'] = _DAYS_SELECTION else: d['rc_days'] = [] output.append(request.theme.recentchanges_header(d)) pages = {} ignore_pages = {} today = request.user.getTime(tnow)[0:3] this_day = today day_count = 0 for line in log.reverse(): if not request.user.may.read(line.pagename): continue line.time_tuple = request.user.getTime(wikiutil.version2timestamp(line.ed_time_usecs)) day = line.time_tuple[0:3] hilite = line.ed_time_usecs > (bookmark_usecs or line.ed_time_usecs) if ((this_day != day or (not hilite and not max_days))) and len(pages) > 0: # new day or bookmark reached: print out stuff this_day = day for p in pages: ignore_pages[p] = None pages = pages.values() pages.sort(cmp_lines) pages.reverse() if request.user.valid: bmtime = pages[0][0].ed_time_usecs d['bookmark_link_html'] = page.link_to(request, _("Set bookmark"), querystr={'action': 'bookmark', 'time': '%d' % bmtime}, rel='nofollow') else: d['bookmark_link_html'] = None d['date'] = request.user.getFormattedDate(wikiutil.version2timestamp(pages[0][0].ed_time_usecs)) output.append(request.theme.recentchanges_daybreak(d)) for p in pages: output.append(format_page_edits(macro, p, bookmark_usecs)) pages = {} day_count += 1 if max_days and (day_count >= max_days): break elif this_day != day: # new day but no changes this_day = day if line.pagename in ignore_pages: continue # end listing by default if user has a bookmark and we reached it if not max_days and not hilite: msg = _('[Bookmark reached]') break if line.pagename in pages: pages[line.pagename].append(line) else: pages[line.pagename] = [line] else: if len(pages) > 0: # end of loop reached: print out stuff # XXX duplicated code from above # but above does not trigger if we have the first day in wiki history for p in pages: ignore_pages[p] = None pages = pages.values() pages.sort(cmp_lines) pages.reverse() if request.user.valid: bmtime = pages[0][0].ed_time_usecs d['bookmark_link_html'] = page.link_to(request, _("Set bookmark"), querystr={'action': 'bookmark', 'time': '%d' % bmtime}, rel='nofollow') else: d['bookmark_link_html'] = None d['date'] = request.user.getFormattedDate(wikiutil.version2timestamp(pages[0][0].ed_time_usecs)) output.append(request.theme.recentchanges_daybreak(d)) for p in pages: output.append(format_page_edits(macro, p, bookmark_usecs)) d['rc_msg'] = msg output.append(request.theme.recentchanges_footer(d)) return ''.join(output)
def sendEditor(self, **kw): """ Send the editor form page. @keyword preview: if given, show this text in preview mode @keyword staytop: don't go to #preview @keyword comment: comment field (when preview is true) """ from MoinMoin import i18n from MoinMoin.action import SpellCheck request = self.request form = request.form _ = self._ raw_body = '' msg = None conflict_msg = None edit_lock_message = None preview = kw.get('preview', None) staytop = kw.get('staytop', 0) # check edit permissions if not request.user.may.write(self.page_name): msg = _('You are not allowed to edit this page.') elif not self.isWritable(): msg = _('Page is immutable!') elif self.rev: # Trying to edit an old version, this is not possible via # the web interface, but catch it just in case... msg = _('Cannot edit old revisions!') else: # try to acquire edit lock ok, edit_lock_message = self.lock.acquire() if not ok: # failed to get the lock if preview is not None: edit_lock_message = _('The lock you held timed out. Be prepared for editing conflicts!' ) + "<br>" + edit_lock_message else: msg = edit_lock_message # Did one of the prechecks fail? if msg: request.theme.add_msg(msg, "error") self.send_page() return # Emit http_headers after checks (send_page) request.disableHttpCaching(level=2) # check if we want to load a draft use_draft = None if 'button_load_draft' in form: wanted_draft_timestamp = int(form.get('draft_ts', '0')) if wanted_draft_timestamp: draft = self._load_draft() if draft is not None: draft_timestamp, draft_rev, draft_text = draft if draft_timestamp == wanted_draft_timestamp: use_draft = draft_text # Check for draft / normal / preview submit if use_draft is not None: title = _('Draft of "%(pagename)s"') # Propagate original revision rev = int(form['draft_rev']) self.set_raw_body(use_draft, modified=1) preview = use_draft elif preview is None: title = _('Edit "%(pagename)s"') else: title = _('Preview of "%(pagename)s"') # Propagate original revision rev = request.rev self.set_raw_body(preview, modified=1) # send header stuff lock_timeout = self.lock.timeout / 60 lock_page = wikiutil.escape(self.page_name, quote=1) lock_expire = _("Your edit lock on %(lock_page)s has expired!") % {'lock_page': lock_page} lock_mins = _("Your edit lock on %(lock_page)s will expire in # minutes.") % {'lock_page': lock_page} lock_secs = _("Your edit lock on %(lock_page)s will expire in # seconds.") % {'lock_page': lock_page} # get request parameters try: text_rows = int(form['rows']) except StandardError: text_rows = self.cfg.edit_rows if request.user.valid: text_rows = int(request.user.edit_rows) if preview is not None: # Check for editing conflicts if not self.exists(): # page does not exist, are we creating it? if rev: conflict_msg = _('Someone else deleted this page while you were editing!') elif rev != self.current_rev(): conflict_msg = _('Someone else changed this page while you were editing!') if self.mergeEditConflict(rev): conflict_msg = _("""Someone else saved this page while you were editing! Please review the page and save then. Do not save this page as it is!""") rev = self.current_rev() if conflict_msg: # We don't show preview when in conflict preview = None elif self.exists(): # revision of existing page rev = self.current_rev() else: # page creation rev = 0 self.setConflict(bool(conflict_msg)) # Page editing is done using user language request.setContentLanguage(request.lang) # Get the text body for the editor field. # TODO: what about deleted pages? show the text of the last revision or use the template? if preview is not None: raw_body = self.get_raw_body() if use_draft: request.write(_("[Content loaded from draft]"), '<br>') elif self.exists(): # If the page exists, we get the text from the page. # TODO: maybe warn if template argument was ignored because the page exists? raw_body = self.get_raw_body() elif 'template' in request.values: # If the page does not exist, we try to get the content from the template parameter. template_page = wikiutil.unquoteWikiname(request.values['template']) template_page_escaped = wikiutil.escape(template_page) if request.user.may.read(template_page): raw_body = Page(request, template_page).get_raw_body() if raw_body: request.write(_("[Content of new page loaded from %s]") % (template_page_escaped, ), '<br>') else: request.write(_("[Template %s not found]") % (template_page_escaped, ), '<br>') else: request.write(_("[You may not read %s]") % (template_page_escaped, ), '<br>') # Make backup on previews - but not for new empty pages if not use_draft and preview and raw_body: self._save_draft(raw_body, rev) draft_message = None loadable_draft = False if preview is None: draft = self._load_draft() if draft is not None: draft_timestamp, draft_rev, draft_text = draft if draft_text != raw_body: loadable_draft = True page_rev = rev draft_timestamp_str = request.user.getFormattedDateTime(draft_timestamp) draft_message = _(u"'''<<BR>>Your draft based on revision %(draft_rev)d (saved %(draft_timestamp_str)s) can be loaded instead of the current revision %(page_rev)d by using the load draft button - in case you lost your last edit somehow without saving it.''' A draft gets saved for you when you do a preview, cancel an edit or unsuccessfully save.", wiki=True, percent=True) % locals() # Setup status message status = [kw.get('msg', ''), conflict_msg, edit_lock_message, draft_message] status = [msg for msg in status if msg] status = ' '.join(status) status = Status(request, content=status) request.theme.add_msg(status, "error") request.theme.send_title( title % {'pagename': self.split_title(), }, page=self, html_head=self.lock.locktype and ( PageEditor._countdown_js % { 'countdown_script': request.theme.externalScript('countdown'), 'lock_timeout': lock_timeout, 'lock_expire': lock_expire, 'lock_mins': lock_mins, 'lock_secs': lock_secs, }) or '', editor_mode=1, allow_doubleclick=1, ) request.write(request.formatter.startContent("content")) # Generate default content for new pages if not raw_body: raw_body = _('Describe %s here.') % (self.page_name, ) # send form request.write('<form id="editor" method="post" action="%s#preview">' % ( request.href(self.page_name) )) # yet another weird workaround for broken IE6 (it expands the text # editor area to the right after you begin to type...). IE sucks... # http://fplanque.net/2003/Articles/iecsstextarea/ request.write('<fieldset style="border:none;padding:0;">') request.write(unicode(html.INPUT(type="hidden", name="action", value="edit"))) # Send revision of the page our edit is based on request.write('<input type="hidden" name="rev" value="%d">' % (rev, )) # Add src format (e.g. 'wiki') into a hidden form field, so that # we can load the correct converter after POSTing. request.write('<input type="hidden" name="format" value="%s">' % self.pi['format']) # Create and send a ticket, so we can check the POST request.write('<input type="hidden" name="ticket" value="%s">' % wikiutil.createTicket(request)) # Save backto in a hidden input backto = request.values.get('backto') if backto: request.write(unicode(html.INPUT(type="hidden", name="backto", value=backto))) # button bar button_spellcheck = '<input class="button" type="submit" name="button_spellcheck" value="%s">' % _('Check Spelling') save_button_text = _('Save Changes') cancel_button_text = _('Cancel') if self.cfg.page_license_enabled: request.write('<p><em>', _( """By hitting '''%(save_button_text)s''' you put your changes under the %(license_link)s. If you don't want that, hit '''%(cancel_button_text)s''' to cancel your changes.""", wiki=True) % { 'save_button_text': save_button_text, 'cancel_button_text': cancel_button_text, 'license_link': wikiutil.getLocalizedPage(request, self.cfg.page_license_page).link_to(request), }, '</em></p>') request.write(''' <input class="button" type="submit" name="button_save" value="%s"> <input class="button" type="submit" name="button_preview" value="%s"> <input class="button" type="submit" name="button_switch" value="%s"> ''' % (save_button_text, _('Preview'), _('Text mode'), )) if loadable_draft: request.write(''' <input class="button" type="submit" name="button_load_draft" value="%s" onClick="flgChange = false;"> <input type="hidden" name="draft_ts" value="%d"> <input type="hidden" name="draft_rev" value="%d"> ''' % (_('Load Draft'), draft_timestamp, draft_rev)) request.write(''' %s <input class="button" type="submit" name="button_cancel" value="%s"> <input type="hidden" name="editor" value="gui"> ''' % (button_spellcheck, cancel_button_text, )) if self.cfg.mail_enabled: request.write(''' <script type="text/javascript"> function toggle_trivial(CheckedBox) { TrivialBoxes = document.getElementsByName("trivial"); for (var i = 0; i < TrivialBoxes.length; i++) TrivialBoxes[i].checked = CheckedBox.checked; } </script> <input type="checkbox" name="trivial" id="chktrivialtop" value="1" %(checked)s onclick="toggle_trivial(this)"> <label for="chktrivialtop">%(label)s</label> ''' % { 'checked': ('', 'checked')[form.get('trivial', '0') == '1'], 'label': _("Trivial change"), }) from MoinMoin.security.textcha import TextCha request.write(TextCha(request).render()) self.sendconfirmleaving() # TODO update state of flgChange to make this work, see PageEditor # Add textarea with page text lang = self.pi.get('language', request.cfg.language_default) contentlangdirection = i18n.getDirection(lang) # 'ltr' or 'rtl' uilanguage = request.lang url_prefix_static = request.cfg.url_prefix_static url_prefix_local = request.cfg.url_prefix_local wikipage = wikiutil.quoteWikinameURL(self.page_name) fckbasepath = request.cfg.url_prefix_fckeditor wikiurl = request.script_root + '/' themepath = '%s/%s' % (url_prefix_static, request.theme.name) smileypath = themepath + '/img' # auto-generating a list for SmileyImages does NOT work from here! text_rows = int(request.user.edit_rows) if not text_rows: # if no specific value is given for editor height, but 0, we # compute the rows from the raw_body line count plus some # extra rows for adding new text in the editor. Maybe this helps # with the "double slider" usability issue, esp. for devices like # the iphone where you can't operate both sliders. current_rows = len(raw_body.split('\n')) text_rows = max(10, int(current_rows * 1.5)) editor_size = text_rows * 22 # 22 height_pixels/line word_rule = self.word_rule() request.write(""" <script type="text/javascript" src="%(fckbasepath)s/fckeditor.js"></script> <script type="text/javascript"> <!-- var oFCKeditor = new FCKeditor( 'savetext', '100%%', %(editor_size)s, 'MoinDefault' ) ; oFCKeditor.BasePath= '%(fckbasepath)s/' ; oFCKeditor.Config['WikiBasePath'] = '%(wikiurl)s' ; oFCKeditor.Config['WikiPage'] = '%(wikipage)s' ; oFCKeditor.Config['PluginsPath'] = '%(url_prefix_local)s/applets/moinFCKplugins/' ; oFCKeditor.Config['CustomConfigurationsPath'] = '%(url_prefix_local)s/applets/moinfckconfig.js' ; oFCKeditor.Config['WordRule'] = %(word_rule)s ; oFCKeditor.Config['SmileyPath'] = '%(smileypath)s/' ; oFCKeditor.Config['EditorAreaCSS'] = '%(themepath)s/css/common.css' ; oFCKeditor.Config['SkinPath'] = '%(fckbasepath)s/editor/skins/silver/' ; oFCKeditor.Config['AutoDetectLanguage'] = false ; oFCKeditor.Config['DefaultLanguage'] = '%(uilanguage)s' ; oFCKeditor.Config['ContentLangDirection'] = '%(contentlangdirection)s' ; oFCKeditor.Value= """ % locals()) from MoinMoin.formatter.text_gedit import Formatter self.formatter = Formatter(request) self.formatter.page = self output = request.redirectedOutput(self.send_page_content, request, raw_body, format=self.pi['format'], do_cache=False) output = repr(output) if output[0] == 'u': output = output[1:] request.write(output) request.write(""" ; oFCKeditor.Create() ; //--> </script> """) request.write("<p>") request.write(_("Comment:"), ' <input id="editor-comment" type="text" name="comment" value="%s" size="80" maxlength="200">' % ( wikiutil.escape(kw.get('comment', ''), 1), )) request.write("</p>") # Category selection filterfn = self.cfg.cache.page_category_regexact.search cat_pages = request.rootpage.getPageList(filter=filterfn) cat_pages.sort() cat_pages = [wikiutil.pagelinkmarkup(p) for p in cat_pages] cat_pages.insert(0, ('', _('<No addition>'))) request.write("<p>") request.write(_('Add to: %(category)s') % { 'category': unicode(web.makeSelection('category', cat_pages)), }) if self.cfg.mail_enabled: request.write(''' <input type="checkbox" name="trivial" id="chktrivial" value="1" %(checked)s onclick="toggle_trivial(this)"> <label for="chktrivial">%(label)s</label> ''' % { 'checked': ('', 'checked')[form.get('trivial', '0') == '1'], 'label': _("Trivial change"), }) request.write(''' <input type="checkbox" name="rstrip" id="chkrstrip" value="1" %(checked)s> <label for="chkrstrip">%(label)s</label> </p> ''' % { 'checked': ('', 'checked')[form.get('rstrip', '0') == '1'], 'label': _('Remove trailing whitespace from each line') }) request.write("</p>") badwords_re = None if preview is not None: if 'button_spellcheck' in form or 'button_newwords' in form: badwords, badwords_re, msg = SpellCheck.checkSpelling(self, request, own_form=0) request.write("<p>%s</p>" % msg) request.write('</fieldset>') request.write("</form>") if preview is not None: if staytop: content_id = 'previewbelow' else: content_id = 'preview' self.send_page(content_id=content_id, content_only=1, hilite_re=badwords_re) request.write(request.formatter.endContent()) # end content div request.theme.send_footer(self.page_name) request.theme.send_closing_html()
def _format(self, formatter=None, method=None): """ does the formatting of the table @param formatter: formatter @param method: None is the default and does not create a form while "GET" or "POST" will create the form using the given method """ fmt = formatter or self.request.formatter result = [] if method: result.append( fmt.rawHTML( '<form action="%s/%s" method="%s" name="%sform">' % (self.request.script_root, wikiutil.quoteWikinameURL( self.request.page.page_name), method, self.data_id))) result.append(fmt.div(1)) havefilters = False for col in self.data.columns: if col.autofilter: havefilters = True break if havefilters: result.append( fmt.rawHTML('<input type="submit" value="%s" %s>' % (self._filter, self._name('submit')))) result.append(fmt.table(1, id='%stable' % self.unqual_data_id)) # add header line if self._show_header: result.append(fmt.table_row(1)) for idx in range(len(self.data.columns)): col = self.data.columns[idx] if col.hidden: continue cell_attrs = {'class': 'hcolumn%d' % idx} result.append(fmt.table_cell(1, cell_attrs)) result.append(fmt.strong(1)) result.append(col.label or col.name) result.append(fmt.strong(0)) if col.autofilter: result.append(fmt.linebreak(False)) select = '<select %s onchange="dbw_update_search(\'%s\');">%s</select>' % ( self._name('filter%d' % idx), self.data_id, self._filteroptions(idx)) result.append(fmt.rawHTML(select)) result.append(fmt.table_cell(0)) result.append(fmt.table_row(0)) # add data self.data.reset() row = self.data.next() if row is not None: filters = [None] * len(row) if havefilters: for idx in range(len(row)): name = '%sfilter%d' % (self.data_id, idx) if name in self.request.values: filters[idx] = self.request.getlist(name) if filters[idx] == self._all: filters[idx] = None while row: hidden = False if havefilters: # check if row needs to be hidden due to filtering for idx in range(len(row)): if filters[idx]: if isinstance(row[idx], tuple): data = unicode(row[idx][1]) else: data = unicode(row[idx]) if data != '' and filters[idx] == self._notempty: continue if data == '' and filters[idx] == self._empty: continue if data != filters[idx]: hidden = True break if not hidden: result.append(fmt.table_row(1)) for idx in range(len(row)): if self.data.columns[idx].hidden: continue cell_attrs = {'class': 'column%d' % idx} if isinstance(row[idx], tuple): result.append( fmt.table_cell(1, cell_attrs, abbr=unicode(row[idx][1]))) result.append(unicode(row[idx][0])) else: result.append(fmt.table_cell(1, cell_attrs)) result.append(unicode(row[idx])) result.append(fmt.table_cell(0)) result.append(fmt.table_row(0)) row = self.data.next() result.append(fmt.table(0)) result.append(fmt.div(0)) if method: result.append(fmt.rawHTML('</form>')) return ''.join(result)
def execute(macro, text): request = macro.request formatter = macro.formatter _ = request.getText # return immediately if getting links for the current page if request.mode_getpagelinks: return '' currentyear, currentmonth, currentday, h, m, s, wd, yd, ds = request.user.getTime( time.time()) thispage = formatter.page.page_name # does the url have calendar params (= somebody has clicked on prev/next links in calendar) ? if 'calparms' in macro.request.args: has_calparms = 1 # yes! text2 = macro.request.args['calparms'] cparmpagename, cparmyear, cparmmonth, cparmoffset, cparmoffset2, cparmheight6, cparmanniversary, cparmtemplate = \ parseargs(request, text2, thispage, currentyear, currentmonth, 0, 0, False, False, u'') # Note: cparmheight6 and cparmanniversary are not used, they are just there # to have a consistent parameter string in calparms and macro args else: has_calparms = 0 if text is None: # macro call without parameters text = u'' # parse and check arguments parmpagename, parmyear, parmmonth, parmoffset, parmoffset2, parmheight6, anniversary, parmtemplate = \ parseargs(request, text, thispage, currentyear, currentmonth, 0, 0, False, False, u'') # does url have calendar params and is THIS the right calendar to modify (we can have multiple # calendars on the same page)? #if has_calparms and (cparmpagename,cparmyear,cparmmonth,cparmoffset) == (parmpagename,parmyear,parmmonth,parmoffset): # move all calendars when using the navigation: if has_calparms and cparmpagename == parmpagename: year, month = yearmonthplusoffset(parmyear, parmmonth, parmoffset + cparmoffset2) parmoffset2 = cparmoffset2 parmtemplate = cparmtemplate else: year, month = yearmonthplusoffset(parmyear, parmmonth, parmoffset) if request.isSpiderAgent and abs(currentyear - year) > 1: return '' # this is a bot and it didn't follow the rules (see below) if currentyear == year: attrs = {} else: attrs = { 'rel': 'nofollow' } # otherwise even well-behaved bots will index forever # get the calendar monthcal = calendar.monthcalendar(year, month) # european / US differences months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') # Set things up for Monday or Sunday as the first day of the week if calendar.firstweekday() == calendar.MONDAY: wkend = (5, 6) wkdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') if calendar.firstweekday() == calendar.SUNDAY: wkend = (0, 6) wkdays = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') colorstep = 85 p = Page(request, thispage) qpagenames = '*'.join( [wikiutil.quoteWikinameURL(pn) for pn in parmpagename]) qtemplate = wikiutil.quoteWikinameURL(parmtemplate) querystr = "calparms=%%s,%d,%d,%d,%%d,,,%%s" % (parmyear, parmmonth, parmoffset) prevlink = p.url(request, querystr % (qpagenames, parmoffset2 - 1, qtemplate)) nextlink = p.url(request, querystr % (qpagenames, parmoffset2 + 1, qtemplate)) prevylink = p.url(request, querystr % (qpagenames, parmoffset2 - 12, qtemplate)) nextylink = p.url(request, querystr % (qpagenames, parmoffset2 + 12, qtemplate)) prevmonth = formatter.url(1, prevlink, 'cal-link', ** attrs) + '<' + formatter.url(0) nextmonth = formatter.url(1, nextlink, 'cal-link', ** attrs) + '>' + formatter.url(0) prevyear = formatter.url(1, prevylink, 'cal-link', ** attrs) + '<<' + formatter.url(0) nextyear = formatter.url(1, nextylink, 'cal-link', ** attrs) + '>>' + formatter.url(0) if parmpagename != [thispage]: pagelinks = '' r, g, b = (255, 0, 0) l = len(parmpagename[0]) steps = len(parmpagename) maxsteps = (255 / colorstep) if steps > maxsteps: steps = maxsteps chstep = int(l / steps) st = 0 while st < l: ch = parmpagename[0][st:st + chstep] r, g, b = cliprgb(r, g, b) link = Page(request, parmpagename[0]).link_to( request, ch, rel='nofollow', style= 'background-color:#%02x%02x%02x;color:#000000;text-decoration:none' % (r, g, b)) pagelinks = pagelinks + link r, g, b = (r, g + colorstep, b) st = st + chstep r, g, b = (255 - colorstep, 255, 255 - colorstep) for page in parmpagename[1:]: link = Page(request, page).link_to( request, page, rel='nofollow', style= 'background-color:#%02x%02x%02x;color:#000000;text-decoration:none' % (r, g, b)) pagelinks = pagelinks + '*' + link showpagename = ' %s<BR>\n' % pagelinks else: showpagename = '' if calendar.firstweekday() == calendar.SUNDAY: resth1 = ' <th colspan="7" class="cal-header">\n' \ '%s' \ ' %s %s <b> %s %s</b> %s\n %s\n' \ ' </th>\n' % (showpagename, prevyear, prevmonth, months[month-1], str(year), nextmonth, nextyear) if calendar.firstweekday() == calendar.MONDAY: resth1 = ' <th colspan="7" class="cal-header">\n' \ '%s' \ ' %s %s <b> %s / %s</b> %s\n %s\n' \ ' </th>\n' % (showpagename, prevyear, prevmonth, str(year), month, nextmonth, nextyear) restr1 = ' <tr>\n%s </tr>\n' % resth1 r7 = range(7) restd2 = [] for wkday in r7: wday = _(wkdays[wkday]) if wkday in wkend: cssday = "cal-weekend" else: cssday = "cal-workday" restd2.append(' <td class="%s">%s</td>\n' % (cssday, wday)) restr2 = ' <tr>\n%s </tr>\n' % "".join(restd2) if parmheight6: while len(monthcal) < 6: monthcal = monthcal + [[0, 0, 0, 0, 0, 0, 0]] maketip_js = [] restrn = [] for week in monthcal: restdn = [] for wkday in r7: day = week[wkday] if not day: restdn.append(' <td class="cal-invalidday"> </td>\n') else: page = parmpagename[0] if anniversary: link = "%s/%02d-%02d" % (page, month, day) else: link = "%s/%4d-%02d-%02d" % (page, year, month, day) daypage = Page(request, link) if daypage.exists() and request.user.may.read(link): csslink = "cal-usedday" query = {} r, g, b, u = (255, 0, 0, 1) daycontent = daypage.get_raw_body() header1_re = re.compile(r'^\s*=\s(.*)\s=$', re.MULTILINE) # re.UNICODE titletext = [] for match in header1_re.finditer(daycontent): if match: title = match.group(1) title = wikiutil.escape(title).replace("'", "\\'") titletext.append(title) tipname_unescaped = link.replace("'", "\\'") link = wikiutil.escape(link).replace("'", "\\'") tipname = link tiptitle = link tiptext = '<br>'.join(titletext) maketip_js.append("maketip('%s','%s','%s');" % (tipname, tiptitle, tiptext)) attrs = { 'onMouseOver': "tip('%s')" % tipname_unescaped, 'onMouseOut': "untip()" } else: csslink = "cal-emptyday" if parmtemplate: query = {'action': 'edit', 'template': parmtemplate} else: query = {} r, g, b, u = (255, 255, 255, 0) if wkday in wkend: csslink = "cal-weekend" attrs = {'rel': 'nofollow'} for otherpage in parmpagename[1:]: otherlink = "%s/%4d-%02d-%02d" % (otherpage, year, month, day) otherdaypage = Page(request, otherlink) if otherdaypage.exists(): csslink = "cal-usedday" if u == 0: r, g, b = (r - colorstep, g, b - colorstep) else: r, g, b = (r, g + colorstep, b) r, g, b = cliprgb(r, g, b) style = 'background-color:#%02x%02x%02x' % (r, g, b) fmtlink = formatter.url(1, daypage.url(request, query), csslink, ** attrs) + str(day) + formatter.url(0) if day == currentday and month == currentmonth and year == currentyear: cssday = "cal-today" fmtlink = "<b>%s</b>" % fmtlink # for browser with CSS probs else: cssday = "cal-nottoday" restdn.append(' <td style="%s" class="%s">%s</td>\n' % (style, cssday, fmtlink)) restrn.append(' <tr>\n%s </tr>\n' % "".join(restdn)) restable = '<table border="2" cellspacing="2" cellpadding="2">\n<col width="14%%" span="7">%s%s%s</table>\n' restable = restable % (restr1, restr2, "".join(restrn)) if maketip_js: tip_js = '''<script language="JavaScript" type="text/javascript"> <!-- %s // --> </script> ''' % '\n'.join(maketip_js) else: tip_js = '' result = """\ <script type="text/javascript" src="%s/common/js/infobox.js"></script> <div id="%s" style="position:absolute; visibility:hidden; z-index:20; top:-999em; left:0px;"></div> %s%s """ % (request.cfg.url_prefix_static, formatter.make_id_unique('infodiv'), tip_js, restable) return formatter.rawHTML(result)
def send_title(self, text, **keywords): """ Output the page header (and title). @param text: the title text @keyword page: the page instance that called us - using this is more efficient than using pagename.. @keyword pagename: 'PageName' @keyword print_mode: 1 (or 0) @keyword editor_mode: 1 (or 0) @keyword media: css media type, defaults to 'screen' @keyword allow_doubleclick: 1 (or 0) @keyword html_head: additional <head> code @keyword body_attr: additional <body> attributes @keyword body_onload: additional "onload" JavaScript code """ request = self.request _ = request.getText rev = request.rev if keywords.has_key('page'): page = keywords['page'] pagename = page.page_name else: pagename = keywords.get('pagename', '') page = Page(request, pagename) if keywords.get('msg', ''): raise DeprecationWarning( "Using send_page(msg=) is deprecated! Use theme.add_msg() instead!" ) scriptname = request.script_root # get name of system pages page_front_page = wikiutil.getFrontPage(request).page_name page_help_contents = wikiutil.getLocalizedPage( request, 'HelpContents').page_name page_title_index = wikiutil.getLocalizedPage(request, 'TitleIndex').page_name page_site_navigation = wikiutil.getLocalizedPage( request, 'SiteNavigation').page_name page_word_index = wikiutil.getLocalizedPage(request, 'WordIndex').page_name page_help_formatting = wikiutil.getLocalizedPage( request, 'HelpOnFormatting').page_name page_find_page = wikiutil.getLocalizedPage(request, 'FindPage').page_name home_page = wikiutil.getInterwikiHomePage( request ) # sorry theme API change!!! Either None or tuple (wikiname,pagename) now. page_parent_page = getattr(page.getParentPage(), 'page_name', None) # Prepare the HTML <head> element user_head = [request.cfg.html_head] # include charset information - needed for moin_dump or any other case # when reading the html without a web server user_head.append( '''<meta http-equiv="Content-Type" content="%s;charset=%s">\n''' % (page.output_mimetype, page.output_charset)) meta_keywords = request.getPragma('keywords') meta_desc = request.getPragma('description') if meta_keywords: user_head.append('<meta name="keywords" content="%s">\n' % wikiutil.escape(meta_keywords, 1)) if meta_desc: user_head.append('<meta name="description" content="%s">\n' % wikiutil.escape(meta_desc, 1)) # search engine precautions / optimization: # if it is an action or edit/search, send query headers (noindex,nofollow): if request.query_string: user_head.append(request.cfg.html_head_queries) elif request.method == 'POST': user_head.append(request.cfg.html_head_posts) # we don't want to have BadContent stuff indexed: elif pagename in [ 'BadContent', 'LocalBadContent', ]: user_head.append(request.cfg.html_head_posts) # if it is a special page, index it and follow the links - we do it # for the original, English pages as well as for (the possibly # modified) frontpage: elif pagename in [ page_front_page, request.cfg.page_front_page, page_title_index, 'TitleIndex', page_find_page, 'FindPage', page_site_navigation, 'SiteNavigation', 'RecentChanges', ]: user_head.append(request.cfg.html_head_index) # if it is a normal page, index it, but do not follow the links, because # there are a lot of illegal links (like actions) or duplicates: else: user_head.append(request.cfg.html_head_normal) if 'pi_refresh' in keywords and keywords['pi_refresh']: user_head.append( '<meta http-equiv="refresh" content="%d;URL=%s">' % keywords['pi_refresh']) # output buffering increases latency but increases throughput as well output = [] # later: <html xmlns=\"http://www.w3.org/1999/xhtml\"> output.append("""\ <!doctype html> <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>%(title)s</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="%(static_url)scss/style.css"> <script src="%(static_url)sjs/libs/moin.common.js"></script> <script type="text/javascript"> <!-- var search_hint = "Search"; //--> </script> <script src="%(static_url)sjs/libs/modernizr-2.0.6.min.js"></script> """ % { 'title': text, 'static_url': django_settings.STATIC_URL }) # Links output.append('<link rel="Start" href="%s">\n' % request.href(page_front_page)) if pagename: output.append( '<link rel="Alternate" title="%s" href="%s">\n' % (_('Wiki Markup'), request.href(pagename, action='raw'))) output.append( '<link rel="Alternate" media="print" title="%s" href="%s">\n' % (_('Print View'), request.href(pagename, action='print'))) # !!! currently disabled due to Mozilla link prefetching, see # http://www.mozilla.org/projects/netlib/Link_Prefetching_FAQ.html #~ all_pages = request.getPageList() #~ if all_pages: #~ try: #~ pos = all_pages.index(pagename) #~ except ValueError: #~ # this shopuld never happend in theory, but let's be sure #~ pass #~ else: #~ request.write('<link rel="First" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[0])) #~ if pos > 0: #~ request.write('<link rel="Previous" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos-1]))) #~ if pos+1 < len(all_pages): #~ request.write('<link rel="Next" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[pos+1]))) #~ request.write('<link rel="Last" href="%s/%s">\n' % (request.script_root, quoteWikinameURL(all_pages[-1]))) if page_parent_page: output.append('<link rel="Up" href="%s">\n' % request.href(page_parent_page)) # write buffer because we call AttachFile request.write(''.join(output)) output = [] # XXX maybe this should be removed completely. moin emits all attachments as <link rel="Appendix" ...> # and it is at least questionable if this fits into the original intent of rel="Appendix". if pagename and request.user.may.read(pagename): from MoinMoin.action import AttachFile AttachFile.send_link_rel(request, pagename) output.extend([ '<link rel="Search" href="%s">\n' % request.href(page_find_page), '<link rel="Index" href="%s">\n' % request.href(page_title_index), '<link rel="Glossary" href="%s">\n' % request.href(page_word_index), '<link rel="Help" href="%s">\n' % request.href(page_help_formatting), ]) output.append("</head>\n") request.write(''.join(output)) output = [] # start the <body> bodyattr = [] if keywords.has_key('body_attr'): bodyattr.append(' ') bodyattr.append(keywords['body_attr']) # Add doubleclick edit action if (pagename and keywords.get('allow_doubleclick', 0) and not keywords.get('print_mode', 0) and request.user.edit_on_doubleclick): if request.user.may.write(pagename): # separating this gains speed url = page.url(request, {'action': 'edit'}) bodyattr.append(''' ondblclick="location.href='%s'" ''' % wikiutil.escape(url, True)) # Set body to the user interface language and direction bodyattr.append(' %s' % self.ui_lang_attr()) body_onload = keywords.get('body_onload', '') if body_onload: bodyattr.append(''' onload="%s"''' % body_onload) output.append('\n<body%s>\n' % ''.join(bodyattr)) # Output ----------------------------------------------------------- # If in print mode, start page div and emit the title if keywords.get('print_mode', 0): d = { 'title_text': text, 'page': page, 'page_name': pagename or '', 'rev': rev, } request.themedict = d output.append(self.startPage()) output.append(self.interwiki(d)) output.append(self.title(d)) # In standard mode, emit theme.header else: exists = pagename and page.exists(includeDeleted=True) # prepare dict for theme code: d = { 'theme': self.name, 'script_name': scriptname, 'title_text': text, 'logo_string': request.cfg.logo_string, 'site_name': request.cfg.sitename, 'page': page, 'rev': rev, 'pagesize': pagename and page.size() or 0, # exists checked to avoid creation of empty edit-log for non-existing pages 'last_edit_info': exists and page.lastEditInfo() or '', 'page_name': pagename or '', 'page_find_page': page_find_page, 'page_front_page': page_front_page, 'home_page': home_page, 'page_help_contents': page_help_contents, 'page_help_formatting': page_help_formatting, 'page_parent_page': page_parent_page, 'page_title_index': page_title_index, 'page_word_index': page_word_index, 'user_name': request.user.name, 'user_valid': request.user.valid, 'msg': self._status, 'trail': keywords.get('trail', None), # Discontinued keys, keep for a while for 3rd party theme developers 'titlesearch': 'use self.searchform(d)', 'textsearch': 'use self.searchform(d)', 'navibar': ['use self.navibar(d)'], 'available_actions': ['use self.request.availableActions(page)'], } # add quoted versions of pagenames newdict = {} for key in d: if key.startswith('page_'): if not d[key] is None: newdict['q_' + key] = wikiutil.quoteWikinameURL(d[key]) else: newdict['q_' + key] = None d.update(newdict) request.themedict = d # now call the theming code to do the rendering if keywords.get('editor_mode', 0): output.append(self.editorheader(d)) else: output.append(self.header(d)) # emit it request.write(''.join(output)) output = [] self._send_title_called = True