def _do_recover(request): _ = request.getText form = request.form if not request.cfg.mail_enabled: return _("""This wiki is not enabled for mail processing. Contact the owner of the wiki, who can enable email.""") try: email = wikiutil.clean_input(form['email'].lower()) if not email: # continue if email not given raise KeyError u = user.get_by_email_address(request, email) return _do_email(request, u) except KeyError: pass try: username = wikiutil.clean_input(form['name']) if not username: # continue if name not given raise KeyError u = user.User(request, user.getUserId(request, username)) return _do_email(request, u) except KeyError: pass # neither succeeded, give error message return _("Please provide a valid email address or a username!")
def do_action(self): """ Load """ status = False _ = self._ form = self.form request = self.request comment = form.get('comment', [u''])[0] comment = wikiutil.clean_input(comment) filename = form.get('file__filename__') rename = form.get('rename', [''])[0].strip() if rename: target = rename else: target = filename target = AttachFile.preprocess_filename(target) target = wikiutil.clean_input(target) if target: filecontent = form['file'][0] if hasattr(filecontent, 'read'): # a file-like object filecontent = filecontent.read() # XXX reads complete file into memory! filecontent = wikiutil.decodeUnknownInput(filecontent) self.pagename = target pg = PageEditor(request, self.pagename) try: msg = pg.saveText(filecontent, 0, comment=comment) status = True except pg.EditConflict, e: msg = e.message except pg.SaveError, msg: msg = unicode(msg)
def do_action(self): form = values_to_form(self.request.values) template = form.get('template', [''])[0] template = wikiutil.clean_input(template).strip().split(',') new_template = old_template = None if len(template) > 0: new_template = template[0] if len(template) > 1: old_template = template[1] email = form.get('email', [u''])[0] email = wikiutil.clean_input(email).strip() if len(email) == 0: return False, "Please specify an email address." pagename = self.pagename try: if wikiutil.isGroupPage(pagename, self.request.cfg): myuser = invite_user_to_wiki(self.request, pagename, email, new_template, old_template) mygrouppage = pagename else: myuser = invite_user_to_page(self.request, pagename, email, new_template, old_template) mygrouppage = getattr(self.request.cfg, GROUP_DEFAULT_VARIABLE, GROUP_DEFAULT_DEFAULT) if mygrouppage: mycomment = "invited {0}.".format(myuser.email) try: add_user_to_group(self.request, myuser, mygrouppage, comment=mycomment) except GroupException, ge: tmp = "User invitation mail sent to address '%s', but could not add the user to group '%s': %s" if myuser.email != email: tmp += " Please note that the email address was converted to lowercase!" return True, wikiutil.escape( tmp % (email, mygrouppage, unicode(ge))) tmp = "User invitation mail sent to address '%s' and the user was added to group '%s'." if myuser.email != email: tmp += " Please note that the email address was converted to lowercase!" return True, wikiutil.escape(tmp % (email, mygrouppage)) except InviteException, ie: return False, wikiutil.escape(unicode(ie).encode(config.charset))
def do_action(self): """ Delete pagename """ form = self.form comment = form.get('comment', [u''])[0] comment = wikiutil.clean_input(comment) # Create a page editor that does not do editor backups, because # delete generates a "deleted" version of the page. self.page = PageEditor(self.request, self.pagename, do_editor_backup=0) success, msgs = self.page.deletePage(comment) delete_subpages = 0 if 'delete_subpages' in form: try: delete_subpages = int(form['delete_subpages'][0]) except: pass if delete_subpages and self.subpages: for name in self.subpages: self.page = PageEditor(self.request, name, do_editor_backup=0) success_i, msg = self.page.deletePage(comment) msgs = "%s %s" % (msgs, msg) return success, msgs
def do_action(self): """ Rename this page to "pagename" """ _ = self._ form = self.form newpagename = form.get('newpagename', [u''])[0] newpagename = self.request.normalizePagename(newpagename) comment = form.get('comment', [u''])[0] comment = wikiutil.clean_input(comment) self.page = PageEditor(self.request, self.pagename) success, msgs = self.page.renamePage(newpagename, comment) rename_subpages = 0 if 'rename_subpages' in form: try: rename_subpages = int(form['rename_subpages'][0]) except: pass if rename_subpages and self.subpages: for name in self.subpages: self.page = PageEditor(self.request, name) new_subpagename = name.replace(self.pagename, newpagename, 1) success_i, msg = self.page.renamePage(new_subpagename, comment) msgs = "%s %s" % (msgs, msg) self.newpagename = newpagename # keep there for finish return success, msgs
def do_action(self): """ copy this page to "pagename" """ _ = self._ # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(self.request).check_answer_from_form(): return status, _('TextCha: Wrong answer! Go back and try again...') form = self.form newpagename = form.get('newpagename', u'') newpagename = wikiutil.normalize_pagename(newpagename, self.cfg) comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) self.page = PageEditor(self.request, self.pagename) success, msgs = self.page.copyPage(newpagename, comment) copy_subpages = 0 try: copy_subpages = int(form['copy_subpages']) except: pass if copy_subpages and self.subpages or (not self.users_subpages and self.subpages): for name in self.subpages: self.page = PageEditor(self.request, name) new_subpagename = name.replace(self.pagename, newpagename, 1) success_i, msg = self.page.copyPage(new_subpagename, comment) msgs = "%s %s" % (msgs, msg) self.newpagename = newpagename # keep there for finish return success, msgs
def _create_user(request): collab_mode = getattr(request.cfg, 'collab_mode', False) _ = request.getText form = request.form if request.method != 'POST': return if not wikiutil.checkTicket(request, form.get('ticket', '')): return if not TextCha(request).check_answer_from_form(): return _('TextCha: Wrong answer! Go back and try again...') # Create user profile theuser = user.User(request, auth_method="new-user") # Require non-empty name try: if collab_mode: name = wikiutil.clean_input(form.get('email', [''])) theuser.name = name.strip() else: theuser.name = form['name'] except KeyError: return _("Empty user name. Please enter a user name.") # Don't allow creating users with invalid names if not user.isValidName(request, theuser.name): return _("""Invalid user name {{{'%s'}}}. Name may contain any Unicode alpha numeric character, with optional one space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(theuser.name) # Name required to be unique. Check if name belong to another user. if user.getUserId(request, theuser.name): return _("This user name already belongs to somebody else.") # try to get the password and pw repeat password = form.get('password1', '') password2 = form.get('password2', '') # Check if password is given and matches with password repeat if password != password2: return _("Passwords don't match!") if not password: return _("Please specify a password!") pw_checker = request.cfg.password_checker if pw_checker: pw_error = pw_checker(request, theuser.name, password) if pw_error: return _("Password not acceptable: %s") % wikiutil.escape(pw_error) # Encode password try: theuser.enc_password = user.encodePassword(request.cfg, password) except UnicodeError, err: # Should never happen return "Can't encode password: %s" % wikiutil.escape(str(err))
def testCleanInput(self): tests = [(u"", u""), # empty (u"aaa\r\n\tbbb", u"aaa bbb"), # ws chars -> blanks (u"aaa\x00\x01bbb", u"aaabbb"), # strip weird chars (u"a"*500, u""), # too long ] for instr, outstr in tests: assert wikiutil.clean_input(instr) == outstr
def do_action(self): form = values_to_form(self.request.values) template = form.get('template', [''])[0] template = wikiutil.clean_input(template).strip().split(',') new_template = old_template = None if len(template) > 0: new_template = template[0] if len(template) > 1: old_template = template[1] email = form.get('email', [u''])[0] email = wikiutil.clean_input(email).strip() if len(email) == 0: return False, "Please specify an email address." pagename = self.pagename try: if wikiutil.isGroupPage(pagename, self.request.cfg): myuser = invite_user_to_wiki(self.request, pagename, email, new_template, old_template) mygrouppage = pagename else: myuser = invite_user_to_page(self.request, pagename, email, new_template, old_template) mygrouppage = getattr(self.request.cfg, GROUP_DEFAULT_VARIABLE, GROUP_DEFAULT_DEFAULT) if mygrouppage: mycomment = "invited {0}.".format(myuser.email) try: add_user_to_group(self.request, myuser, mygrouppage, comment=mycomment) except GroupException, ge: tmp = "User invitation mail sent to address '%s', but could not add the user to group '%s': %s" if myuser.email != email: tmp += " Please note that the email address was converted to lowercase!" return True, wikiutil.escape(tmp % (email, mygrouppage, unicode(ge))) tmp = "User invitation mail sent to address '%s' and the user was added to group '%s'." if myuser.email != email: tmp += " Please note that the email address was converted to lowercase!" return True, wikiutil.escape(tmp % (email, mygrouppage)) except InviteException, ie: return False, wikiutil.escape(unicode(ie).encode(config.charset))
def do_action(self): """ Load """ status = False _ = self._ form = self.form request = self.request # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(request).check_answer_from_form(): return status, _('TextCha: Wrong answer! Go back and try again...') comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) file_upload = request.files.get('file') if not file_upload: # This might happen when trying to upload file names # with non-ascii characters on Safari. return False, _("No file content. Delete non ASCII characters from the file name and try again.") filename = file_upload.filename rename = form.get('rename', '').strip() if rename: target = rename else: target = filename target = wikiutil.clean_input(target) if target: filecontent = file_upload.stream.read() # XXX reads complete file into memory! filecontent = wikiutil.decodeUnknownInput(filecontent) self.pagename = target pg = PageEditor(request, self.pagename) try: msg = pg.saveText(filecontent, 0, comment=comment) status = True except pg.EditConflict, e: msg = e.message except pg.SaveError, msg: msg = unicode(msg)
def __init__(self, pagename, request, **kw): ActionBase.__init__(self, pagename, request) self.getText = request.getText self.request = request self.use_ticket = True self.form_trigger = 'requestinvite' self.form_trigger_label = wikiutil.escape(kw.get('button_text', [self.getText('Send Request')])[0], True) self.querytext = kw.get('text', [self.getText('Send invite request for collab')])[0] form = values_to_form(self.request.values) collab = form.get('collab', [u''])[0] self.collab = wikiutil.clean_input(collab).strip()
def do_action(self): _ = self.request.getText pdata = self.request.graphdata.getpage(self.pagename) oldpagename = self.pagename success, msgs = RenamePageBasic.do_action(self) form = values_to_form(self.request.values) rename_links = 0 if 'rename_links' in form: try: rename_links = int(form['rename_links'][0]) except: pass if rename_links and success: newpagename = form.get('newpagename', [u''])[0] newpagename = wikiutil.normalize_pagename(newpagename, self.cfg) comment = form.get('comment', [u''])[0] comment = wikiutil.clean_input(comment) comment = "%s (%s)" % (comment, _("changed links:") + " %s -> %s" % (self.pagename, newpagename)) # List pages that link to the renamed page pages = set() inlinks = self.request.graphdata.get_in(self.pagename) for type in inlinks: pages.update(inlinks[type]) # Update listed pages for page in pages: # User rights _ARE_ checked here! if not self.request.user.may.write(page): continue # If inlink rename of a single page does not work, # continue but make sure to emit a warning success_single, msg = self._inlink_rename(page, newpagename, oldpagename, comment) if not success_single: success = False if msg: msgs = self._add_msg(msgs, msg) if not success: msgs = self._add_msg(msgs, _(u'Other pages with inlinks renamed successfully.')) return success, msgs
def _do_upload(pagename, request): _ = request.getText # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(request).check_answer_from_form(): return _('TextCha: Wrong answer! Go back and try again...') form = request.form overwrite = form.get('overwrite', [u'0'])[0] try: overwrite = int(overwrite) except: overwrite = 0 if not request.user.may.write(pagename): return _('You are not allowed to attach a file to this page.') if overwrite and not request.user.may.delete(pagename): return _('You are not allowed to overwrite a file attachment of this page.') filename = form.get('file__filename__') rename = form.get('rename', [u''])[0].strip() if rename: target = rename else: target = filename target = preprocess_filename(target) target = wikiutil.clean_input(target) if not target: return _("Filename of attachment not specified!") # get file content filecontent = request.form.get('file', [None])[0] if filecontent is None: # This might happen when trying to upload file names # with non-ascii characters on Safari. return _("No file content. Delete non ASCII characters from the file name and try again.") # add the attachment try: target, bytes = add_attachment(request, pagename, target, filecontent, overwrite=overwrite) msg = _("Attachment '%(target)s' (remote name '%(filename)s')" " with %(bytes)d bytes saved.") % { 'target': target, 'filename': filename, 'bytes': bytes} except AttachmentAlreadyExists: msg = _("Attachment '%(target)s' (remote name '%(filename)s') already exists.") % { 'target': target, 'filename': filename} # return attachment list upload_form(pagename, request, msg)
def _do_upload(pagename, request): _ = request.getText if not wikiutil.checkTicket(request, request.form.get('ticket', '')): return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.upload' } # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(request).check_answer_from_form(): return _('TextCha: Wrong answer! Go back and try again...') form = request.form file_upload = request.files.get('file') if not file_upload: # This might happen when trying to upload file names # with non-ascii characters on Safari. return _("No file content. Delete non ASCII characters from the file name and try again.") try: overwrite = int(form.get('overwrite', '0')) except: overwrite = 0 if not request.user.may.write(pagename): return _('You are not allowed to attach a file to this page.') if overwrite and not request.user.may.delete(pagename): return _('You are not allowed to overwrite a file attachment of this page.') target = form.get('target', u'').strip() if not target: target = file_upload.filename or u'' target = wikiutil.clean_input(target) if not target: return _("Filename of attachment not specified!") # add the attachment try: target, bytes = add_attachment(request, pagename, target, file_upload.stream, overwrite=overwrite) msg = _("Attachment '%(target)s' (remote name '%(filename)s')" " with %(bytes)d bytes saved.") % { 'target': target, 'filename': file_upload.filename, 'bytes': bytes} except AttachmentAlreadyExists: msg = _("Attachment '%(target)s' (remote name '%(filename)s') already exists.") % { 'target': target, 'filename': file_upload.filename} # return attachment list upload_form(pagename, request, msg)
def add(self, request, mtime, rev, action, pagename, host=None, extra=u'', comment=u''): """ Generate (and add) a line to the edit-log. If `host` is None, it's read from request vars. """ if request.cfg.log_remote_addr or self.force_ip: if host is None: host = request.remote_addr or '' if request.cfg.log_reverse_dns_lookups: import socket try: hostname = socket.gethostbyaddr(host)[0] hostname = unicode(hostname, config.charset) except (socket.error, UnicodeError): hostname = host else: hostname = host else: host = '' hostname = '' comment = wikiutil.clean_input(comment) user_id = request.user.valid and request.user.id or '' if self.uid_override is not None: user_id = '' hostname = self.uid_override host = '' line = u"\t".join(( str(long(mtime)), # has to be long for py 2.2.x "%08d" % rev, action, wikiutil.quoteWikinameFS(pagename), host, hostname, user_id, extra, comment, )) + "\n" self._add(line)
def add(self, request, mtime, rev, action, pagename, host=None, extra=u"", comment=u""): """ Generate (and add) a line to the edit-log. If `host` is None, it's read from request vars. """ if request.cfg.log_remote_addr or self.force_ip: if host is None: host = request.remote_addr or "" if request.cfg.log_reverse_dns_lookups: import socket try: hostname = socket.gethostbyaddr(host)[0] hostname = unicode(hostname, config.charset) except (socket.error, UnicodeError): hostname = host else: hostname = host else: host = "" hostname = "" comment = wikiutil.clean_input(comment) user_id = request.user.valid and request.user.id or "" if self.uid_override is not None: user_id = "" hostname = self.uid_override host = "" line = ( u"\t".join( ( str(long(mtime)), # has to be long for py 2.2.x "%08d" % rev, action, wikiutil.quoteWikinameFS(pagename), host, hostname, user_id, extra, comment, ) ) + "\n" ) self._add(line)
def do_action(self): """ revert pagename """ form = self.form comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) if self.request.method != 'POST': return False, u'' rev = self.request.rev pg = PageEditor(self.request, self.pagename) try: msg = pg.revertPage(rev, comment) # make it show the current version... self.request.rev = None except PageEditor.SaveError, error: msg = unicode(error)
def do_action(self): """ revert pagename """ form = self.form comment = form.get('comment', [u''])[0] comment = wikiutil.clean_input(comment) if self.request.request_method != 'POST': return False, u'' rev = self.request.rev pg = PageEditor(self.request, self.pagename) try: msg = pg.revertPage(rev, comment) # make it show the current version... self.request.rev = None except PageEditor.RevertError, error: msg = unicode(error)
def do_action(self): """ Rename this page to "pagename" """ _ = self._ form = self.form newpagename = form.get('newpagename', u'') newpagename = wikiutil.normalize_pagename(newpagename, self.cfg) comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) try: rename_subpages = int(self.request.form.get('rename_subpages', '0')) except ValueError: rename_subpages = 0 self.page = PageEditor(self.request, self.pagename) success, msgs = self.page.renamePage(newpagename, comment) if not success: return success, msgs msgs = [msgs] if rename_inlinks: success, msgs = self.rename_inlinks(newpagename, comment, msgs) if self.show_redirect and self.rename_redirect: self.page = PageEditor(self.request, self.pagename) self.page.saveText('#redirect %s' % newpagename, 0) if rename_subpages and self.subpages: for name in self.subpages: self.page = PageEditor(self.request, name) new_subpagename = name.replace(self.pagename, newpagename, 1) success_i, msg = self.page.renamePage(new_subpagename, comment) msgs.append(msg) if self.show_redirect and self.rename_redirect and success_i: self.page = PageEditor(self.request, name) self.page.saveText('#redirect %s' % new_subpagename, 0) msgs = ' '.join([msg for msg in msgs if msg]) self.newpagename = newpagename # keep there for finish return success, msgs
def do_action(self): form = values_to_form(self.request.values) days = form.get('days', [u''])[0] days = wikiutil.clean_input(days) try: days = int(days) except ValueError: return False, "Invalid number: %s" % days fake = FakeXmlrpcObj() fake.request = self.request cookie = generateCookie(fake, str(self.pagename), days * SECONDS_IN_DAY) if isinstance(cookie, xmlrpclib.Fault): return False, cookie.faultString default_filename = self.pagename + ".cookie" filename = form.get('filename', [default_filename])[0] self.filename = filename.encode("ascii", "ignore") self.cookie = cookie.data return True, ""
def do_action(self): """ Delete pagename """ form = self.form comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) ngowikiutil = NgoWikiUtil(self.request) ngowikiutil.open_database() try: # Create a page editor that does not do editor backups, because # delete generates a "deleted" version of the page. self.page = PageEditor(self.request, self.pagename, do_editor_backup=0) success, msgs = self.page.deletePage(comment) ngowikiutil.remove_page_by_path(self.pagename) delete_subpages = 0 try: delete_subpages = int(form['delete_subpages']) except: pass if delete_subpages and self.subpages: for name in self.subpages: self.page = PageEditor(self.request, name, do_editor_backup=0) success_i, msg = self.page.deletePage(comment) ngowikiutil.remove_page_by_path(name) msgs = "%s %s" % (msgs, msg) finally: ngowikiutil.close_database(True) return success, msgs
def do_action(self): """ Delete pagename """ form = self.form comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) # Create a page editor that does not do editor backups, because # delete generates a "deleted" version of the page. self.page = PageEditor(self.request, self.pagename, do_editor_backup=0) success, msgs = self.page.deletePage(comment) delete_subpages = 0 try: delete_subpages = int(form['delete_subpages']) except: pass if delete_subpages and self.subpages: for name in self.subpages: self.page = PageEditor(self.request, name, do_editor_backup=0) success_i, msg = self.page.deletePage(comment) msgs = "%s %s" % (msgs, msg) return success, msgs
def do_action(self): """ Load """ status = False _ = self._ form = self.form request = self.request # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(request).check_answer_from_form(): return status, _('TextCha: Wrong answer! Go back and try again...') comment = form.get('comment', u'') comment = wikiutil.clean_input(comment) file_upload = request.files.get('file') if not file_upload: # This might happen when trying to upload file names # with non-ascii characters on Safari. return False, _("No file content. Delete non ASCII characters from the file name and try again.") filename = file_upload.filename rename = form.get('rename', '').strip() if rename: target = rename else: target = filename target = wikiutil.clean_input(target) if target: tmpdir = tempfile.mkdtemp() swsfile = os.path.join(tmpdir,'worksheet.sws') fff = open(swsfile, 'wb') fff.write(file_upload.stream.read()) fff.close() swstarfile = tarfile.open(swsfile) swstarfile.extractall(path=tmpdir) swstarfile.close() txtfile = codecs.open(os.path.join(tmpdir, 'sage_worksheet/worksheet.txt'), 'r', encoding='latin-1') l = txtfile.readlines() txtfile.close() shutil.rmtree(tmpdir) l.pop(0) l.pop(0) bloques = [] cadena = u'' i = 0 while l: lin = l.pop(0) if lin[:3] == '{{{': bloques.append(cadena) cadena = u'\n{{{#!sagecell\n' i += 1 lin = l.pop(0) while lin[:3] != '///': try: cadena+=lin.decode('utf-8') except: for letra in lin: try: cadena += letra.decode('utf-8') except: pass lin = l.pop(0) i += 1 cadena += u'}}}\n' bloques.append(cadena) cadena = u'' while lin[:3] != '}}}': lin = l.pop(0) i+=1 else: try: cadena+=lin.decode('utf-8') except: for letra in lin: try: cadena += letra.decode('utf-8') except: pass bloques2=[] p = HTML2MoinMoin() for l in bloques: if l[:14] == '\n{{{#!sagecell': bloques2.append(p.parsed()) p.clear() bloques2.append(l) else: p.feed(l) filecontent = u'' for l in bloques2: filecontent += l self.pagename = target oldtext = Page(request, self.pagename).get_raw_body() pg = PageEditor(request, self.pagename) try: msg = pg.saveText(oldtext + filecontent, 0, comment=comment) status = True except pg.EditConflict, e: msg = e.message
def execute(pagename, request): """ edit a page """ _ = request.getText if 'button_preview' in request.form and 'button_spellcheck' in request.form: # multiple buttons pressed at once? must be some spammer/bot check_surge_protect(request, kick=True) # get rid of him return if not request.user.may.write(pagename): page = wikiutil.getLocalizedPage(request, 'PermissionDeniedPage') page.body = _('You are not allowed to edit this page.') page.page_name = pagename page.send_page(send_special=True) return valideditors = [ 'text', 'gui', ] editor = '' if request.user.valid: editor = request.user.editor_default if editor not in valideditors: editor = request.cfg.editor_default editorparam = request.values.get('editor', editor) if editorparam == "guipossible": lasteditor = editor elif editorparam == "textonly": editor = lasteditor = 'text' else: editor = lasteditor = editorparam if request.cfg.editor_force: editor = request.cfg.editor_default # if it is still nothing valid, we just use the text editor if editor not in valideditors: editor = 'text' rev = request.rev or 0 savetext = request.form.get('savetext') comment = request.form.get('comment', u'') category = request.form.get('category') rstrip = int(request.form.get('rstrip', '0')) trivial = int(request.form.get('trivial', '0')) ideastatus = int(request.form.get('ideastatus', '0')) if 'button_switch' in request.form: if editor == 'text': editor = 'gui' else: # 'gui' editor = 'text' # load right editor class if editor == 'gui': from MoinMoin.PageGraphicalEditor import PageGraphicalEditor pg = PageGraphicalEditor(request, pagename) else: # 'text' from MoinMoin.PageEditor import PageEditor pg = PageEditor(request, pagename) # is invoked without savetext start editing if savetext is None or 'button_load_draft' in request.form: pg.sendEditor() return # did user hit cancel button? cancelled = 'button_cancel' in request.form from MoinMoin.error import ConvertError try: if lasteditor == 'gui': # convert input from Graphical editor format = request.form.get('format', 'wiki') if format == 'wiki': converter_name = 'text_html_text_moin_wiki' else: converter_name = 'undefined' # XXX we don't have other converters yet convert = wikiutil.importPlugin(request.cfg, "converter", converter_name, 'convert') savetext = convert(request, pagename, savetext) # IMPORTANT: normalize text from the form. This should be done in # one place before we manipulate the text. savetext = pg.normalizeText(savetext, stripspaces=rstrip) except ConvertError: # we don't want to throw an exception if user cancelled anyway if not cancelled: raise if cancelled: pg.sendCancel(savetext or "", rev) pagedir = pg.getPagePath(check_create=0) import os if not os.listdir(pagedir): os.removedirs(pagedir) return comment = wikiutil.clean_input(comment) # Add category # TODO: this code does not work with extended links, and is doing # things behind your back, and in general not needed. Either we have # a full interface for categories (add, delete) or just add them by # markup. if category and category != _('<No addition>'): # opera 8.5 needs this # strip trailing whitespace savetext = savetext.rstrip() # Add category separator if last non-empty line contains # non-categories. lines = [line for line in savetext.splitlines() if line] if lines: #TODO: this code is broken, will not work for extended links #categories, e.g ["category hebrew"] categories = lines[-1].split() if categories: confirmed = wikiutil.filterCategoryPages(request, categories) if len(confirmed) < len(categories): # This was not a categories line, add separator savetext += u'\n----\n' # Add new category if savetext and savetext[-1] != u'\n': savetext += ' ' savetext += category + u'\n' # Should end with newline! if (request.cfg.edit_ticketing and not wikiutil.checkTicket(request, request.form.get('ticket', ''))): request.theme.add_msg( _('Please use the interactive user interface to use action %(actionname)s!' ) % {'actionname': 'edit'}, "error") pg.sendEditor(preview=savetext, comment=comment, staytop=1) # Preview, spellcheck or spellcheck add new words elif ('button_preview' in request.form or 'button_spellcheck' in request.form or 'button_newwords' in request.form): pg.sendEditor(preview=savetext, comment=comment) # Preview with mode switch elif 'button_switch' in request.form: pg.sendEditor(preview=savetext, comment=comment, staytop=1) # Save new text else: try: from MoinMoin.security.textcha import TextCha if not TextCha(request).check_answer_from_form(): raise pg.SaveError( _('TextCha: Wrong answer! Try again below...')) if request.cfg.comment_required and not comment: raise pg.SaveError( _('Supplying a comment is mandatory. Write a comment below and try again...' )) savemsg = pg.saveText(savetext, rev, trivial=trivial, comment=comment) except pg.EditConflict, e: msg = e.message # Handle conflict and send editor pg.set_raw_body(savetext, modified=1) pg.mergeEditConflict(rev) # We don't send preview when we do merge conflict pg.sendEditor(msg=msg, comment=comment) return except pg.SaveError, msg: # Show the error message request.theme.add_msg(unicode(msg), "error") # And show the editor again pg.sendEditor(preview=savetext, comment=comment, staytop=1) return
def _do_upload(pagename, request): _ = request.getText if not wikiutil.checkTicket(request, request.form.get('ticket', '')): return _( 'Please use the interactive user interface to use action %(actionname)s!' ) % { 'actionname': 'AttachFile.upload' } # Currently we only check TextCha for upload (this is what spammers ususally do), # but it could be extended to more/all attachment write access if not TextCha(request).check_answer_from_form(): return _('TextCha: Wrong answer! Go back and try again...') form = request.form file_upload = request.files.get('file') if not file_upload: # This might happen when trying to upload file names # with non-ascii characters on Safari. return _( "No file content. Delete non ASCII characters from the file name and try again." ) try: overwrite = int(form.get('overwrite', '0')) except: overwrite = 0 if not request.user.may.write(pagename): return _('You are not allowed to attach a file to this page.') if overwrite and not request.user.may.delete(pagename): return _( 'You are not allowed to overwrite a file attachment of this page.') target = form.get('target', u'').strip() if not target: target = file_upload.filename or u'' target = wikiutil.clean_input(target) if not target: return _("Filename of attachment not specified!") # add the attachment try: target, bytes = add_attachment(request, pagename, target, file_upload.stream, overwrite=overwrite) msg = _("Attachment '%(target)s' (remote name '%(filename)s')" " with %(bytes)d bytes saved.") % { 'target': target, 'filename': file_upload.filename, 'bytes': bytes } except AttachmentAlreadyExists: msg = _( "Attachment '%(target)s' (remote name '%(filename)s') already exists." ) % { 'target': target, 'filename': file_upload.filename } # return attachment list upload_form(pagename, request, msg)
def do_action(self): description = wikiutil.clean_input(self.form.get('activity', u'')) return True, self.start_activity(description)
pw_checker = request.cfg.password_checker if pw_checker: pw_error = pw_checker(request, theuser.name, password) if pw_error: return _("Password not acceptable: %s") % pw_error # Encode password if password and not password.startswith('{SHA}'): try: theuser.enc_password = user.encodePassword(password) except UnicodeError, err: # Should never happen return "Can't encode password: %s" % str(err) # try to get the email, for new users it is required email = wikiutil.clean_input(form.get('email', [''])[0]) theuser.email = email.strip() if not theuser.email and 'email' not in request.cfg.user_form_remove: return _("Please provide your email address. If you lose your" " login information, you can get it by email.") # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py if theuser.email and request.cfg.user_email_unique: if user.get_by_email_address(request, theuser.email): return _("This email already belongs to somebody else.") # save data theuser.save() result = _("User account created! You can use this account to login now...") if _debug:
def _save_user_prefs(self): _ = self._ form = self.request.form request = self.request if not 'name' in request.user.auth_attribs: # Require non-empty name new_name = wikiutil.clean_input(form.get('name', request.user.name)).strip() # Don't allow changing the name to an invalid one if not user.isValidName(request, new_name): return 'error', _("""Invalid user name {{{'%s'}}}. Name may contain any Unicode alpha numeric character, with optional one space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(new_name) # Is this an existing user trying to change information or a new user? # Name required to be unique. Check if name belong to another user. existing_id = user.getUserId(request, new_name) if existing_id is not None and existing_id != request.user.id: return 'error', _("This user name already belongs to somebody else.") if not new_name: return 'error', _("Empty user name. Please enter a user name.") # done sanity checking the name, set it request.user.name = new_name if not 'email' in request.user.auth_attribs: # try to get the email new_email = wikiutil.clean_input(form.get('email', request.user.email)).strip() # Require email if not new_email and 'email' not in request.cfg.user_form_remove: return 'error', _("Please provide your email address. If you lose your" " login information, you can get it by email.") # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py if new_email and request.cfg.user_email_unique: other = user.get_by_email_address(request, new_email) if other is not None and other.id != request.user.id: return 'error', _("This email already belongs to somebody else.") # done checking the email, set it request.user.email = new_email if not 'jid' in request.user.auth_attribs: # try to get the jid new_jid = wikiutil.clean_input(form.get('jid', '')).strip() jid_changed = request.user.jid != new_jid previous_jid = request.user.jid if new_jid and request.cfg.user_jid_unique: other = user.get_by_jabber_id(request, new_jid) if other is not None and other.id != request.user.id: return 'error', _("This jabber id already belongs to somebody else.") if jid_changed: set_event = events.JabberIDSetEvent(request, new_jid) unset_event = events.JabberIDUnsetEvent(request, previous_jid) events.send_event(unset_event) events.send_event(set_event) # done checking the JID, set it request.user.jid = new_jid if not 'aliasname' in request.user.auth_attribs: # aliasname request.user.aliasname = wikiutil.clean_input(form.get('aliasname', '')).strip() # editor size request.user.edit_rows = util.web.getIntegerInput(request, 'edit_rows', request.user.edit_rows, 0, 999) # try to get the editor request.user.editor_default = wikiutil.clean_input(form.get('editor_default', self.cfg.editor_default)) request.user.editor_ui = wikiutil.clean_input(form.get('editor_ui', self.cfg.editor_ui)) # time zone request.user.tz_offset = util.web.getIntegerInput(request, 'tz_offset', request.user.tz_offset, -84600, 84600) # datetime format try: dt_d_combined = Settings._date_formats.get(form['datetime_fmt'], '') request.user.datetime_fmt, request.user.date_fmt = dt_d_combined.split(' & ') except (KeyError, ValueError): request.user.datetime_fmt = '' # default request.user.date_fmt = '' # default # try to get the (optional) theme theme_name = wikiutil.clean_input(form.get('theme_name', self.cfg.theme_default)) if theme_name != request.user.theme_name: # if the theme has changed, load the new theme # so the user has a direct feedback # WARNING: this should be refactored (i.e. theme load # after userform handling), cause currently the # already loaded theme is just replaced (works cause # nothing has been emitted yet) request.user.theme_name = theme_name if load_theme_fallback(request, theme_name) > 0: theme_name = wikiutil.escape(theme_name) return 'error', _("The theme '%(theme_name)s' could not be loaded!") % locals() # try to get the (optional) preferred language request.user.language = wikiutil.clean_input(form.get('language', '')) if request.user.language == u'': # For language-statistics from MoinMoin import i18n request.user.real_language = i18n.get_browser_language(request) else: request.user.real_language = '' # I want to handle all inputs from user_form_fields, but # don't want to handle the cases that have already been coded # above. # This is a horribly fragile kludge that's begging to break. # Something that might work better would be to define a # handler for each form field, instead of stuffing them all in # one long and inextensible method. That would allow for # plugins to provide methods to validate their fields as well. already_handled = ['name', 'email', 'aliasname', 'edit_rows', 'editor_default', 'editor_ui', 'tz_offset', 'datetime_fmt', 'theme_name', 'language', 'real_language', 'jid'] for field in self.cfg.user_form_fields: key = field[0] if ((key in self.cfg.user_form_disable) or (key in already_handled)): continue default = self.cfg.user_form_defaults[key] value = form.get(key, default) value = wikiutil.clean_input(value) setattr(request.user, key, value) # checkbox options for key, label in self.cfg.user_checkbox_fields: if key not in self.cfg.user_checkbox_disable and key not in self.cfg.user_checkbox_remove: value = form.get(key, "0") try: value = int(value) except ValueError: # value we got is crap, do not setattr this value, just pass pass else: setattr(request.user, key, value) # quicklinks for navibar request.user.quicklinks = self._decode_pagelist('quicklinks') # save data request.user.save() if request.user.disabled: # set valid to false so the current request won't # show the user as logged-in any more request.user.valid = False result = _("User preferences saved!") return result
class PluginScript(MoinScript): """Purpose: ======== This script imports the wiki page from given file into the wiki. Detailed Instructions: ====================== General syntax: moin [options] import wikipage [wikipage-options] [options] usually should be: --config-dir=/path/to/cfg --wiki-url=http://wiki.example.org/ --page=Page """ def __init__(self, argv, def_values): MoinScript.__init__(self, argv, def_values) self.parser.add_option('--acl', dest='acl', default='', metavar='ACL', help='Set a specific ACL for the wiki page') self.parser.add_option('--author', dest='author', metavar='AUTHOR', default='PageImporter', help='Use AUTHOR for edit history / RecentChanges') self.parser.add_option('--comment', dest='comment', metavar='COMMENT', default='', help='COMMENT for edit history / RecentChanges') self.parser.add_option('--file', dest='file', default='', metavar='FILE', help='Read the wiki page from the given file') self.parser.add_option('--no-backup', dest='revision_backup', default=True, action='store_false', help="Suppress making a page backup per revision") self._update_option_help('--page', 'Name of the wiki page which should be imported') def mainloop(self): self.init_request() request = self.request request.user.may = IAmRoot() if not self.options.page: fatal('You must specify a wiki page name (--page=Page)!') if not self.options.file: fatal('You must specify a FILE to read from (--file=FILE)!') try: fileObj = open(self.options.file, 'rb') except IOError, err: fatal(str(err)) page_content = decodeUnknownInput(fileObj.read()).rstrip() fileObj.close() if not self.options.acl: acl = '' else: acl = '#acl %s\n' % self.options.acl comment = clean_input(self.options.comment) pe = PageEditor(request, self.options.page, do_editor_backup=0, uid_override=self.options.author, do_revision_backup=int(self.options.revision_backup)) try: pe.saveText(acl + page_content, 0, comment=comment) except PageEditor.Unchanged: log("info: wikipage was not modified - ignored update.") except PageEditor.SaveError, err: log("error: %r" % err)
pw_checker = request.cfg.password_checker if pw_checker: pw_error = pw_checker(request, theuser.name, password) if pw_error: return _("Password not acceptable: %s") % pw_error # Encode password if password and not password.startswith('{SHA}'): try: theuser.enc_password = user.encodePassword(password) except UnicodeError, err: # Should never happen return "Can't encode password: %s" % str(err) # try to get the email, for new users it is required email = wikiutil.clean_input(form.get('email', '')) theuser.email = email.strip() if not theuser.email and 'email' not in request.cfg.user_form_remove: return _("Please provide your email address. If you lose your" " login information, you can get it by email.") # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py if theuser.email and request.cfg.user_email_unique: if user.get_by_email_address(request, theuser.email): return _("This email already belongs to somebody else.") # save data theuser.save() result = _( "User account created! You can use this account to login now...")
pw_checker = request.cfg.password_checker if pw_checker: pw_error = pw_checker(request, theuser.name, password) if pw_error: return _("Password not acceptable: %s") % wikiutil.escape(pw_error) # Encode password try: theuser.enc_password = user.encodePassword(request.cfg, password) except UnicodeError, err: # Should never happen return "Can't encode password: %s" % wikiutil.escape(str(err)) # try to get the email, for new users it is required email = wikiutil.clean_input(form.get('email', '')) theuser.email = email.strip() if not theuser.email and 'email' not in request.cfg.user_form_remove: return _("Please provide your email address. If you lose your" " login information, you can get it by email.") # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py if theuser.email and request.cfg.user_email_unique: if user.get_by_email_address(request, theuser.email): return _("This email already belongs to somebody else.") # save data theuser.save() result = _("User account created! You can use this account to login now...") return result
def execute(pagename, request): """ edit a page """ _ = request.getText if 'button_preview' in request.form and 'button_spellcheck' in request.form: # multiple buttons pressed at once? must be some spammer/bot check_surge_protect(request, kick=True) # get rid of him return if not request.user.may.write(pagename): page = wikiutil.getLocalizedPage(request, 'PermissionDeniedPage') page.body = _('You are not allowed to edit this page.') page.page_name = pagename page.send_page(send_special=True) return valideditors = ['text', 'gui', ] editor = '' if request.user.valid: editor = request.user.editor_default if editor not in valideditors: editor = request.cfg.editor_default editorparam = request.values.get('editor', editor) if editorparam == "guipossible": lasteditor = editor elif editorparam == "textonly": editor = lasteditor = 'text' else: editor = lasteditor = editorparam if request.cfg.editor_force: editor = request.cfg.editor_default # if it is still nothing valid, we just use the text editor if editor not in valideditors: editor = 'text' rev = request.rev or 0 savetext = request.form.get('savetext') comment = request.form.get('comment', u'') category = request.form.get('category') rstrip = int(request.form.get('rstrip', '0')) trivial = int(request.form.get('trivial', '0')) if 'button_switch' in request.form: if editor == 'text': editor = 'gui' else: # 'gui' editor = 'text' # load right editor class if editor == 'gui': from MoinMoin.PageGraphicalEditor import PageGraphicalEditor pg = PageGraphicalEditor(request, pagename) else: # 'text' from MoinMoin.PageEditor import PageEditor pg = PageEditor(request, pagename) # is invoked without savetext start editing if savetext is None or 'button_load_draft' in request.form: pg.sendEditor() return # did user hit cancel button? cancelled = 'button_cancel' in request.form from MoinMoin.error import ConvertError try: if lasteditor == 'gui': # convert input from Graphical editor format = request.form.get('format', 'wiki') if format == 'wiki': converter_name = 'text_html_text_moin_wiki' else: converter_name = 'undefined' # XXX we don't have other converters yet convert = wikiutil.importPlugin(request.cfg, "converter", converter_name, 'convert') savetext = convert(request, pagename, savetext) # IMPORTANT: normalize text from the form. This should be done in # one place before we manipulate the text. savetext = pg.normalizeText(savetext, stripspaces=rstrip) except ConvertError: # we don't want to throw an exception if user cancelled anyway if not cancelled: raise if cancelled: pg.sendCancel(savetext or "", rev) pagedir = pg.getPagePath(check_create=0) import os if not os.listdir(pagedir): os.removedirs(pagedir) return comment = wikiutil.clean_input(comment) # Add category # TODO: this code does not work with extended links, and is doing # things behind your back, and in general not needed. Either we have # a full interface for categories (add, delete) or just add them by # markup. if category and category != _('<No addition>'): # opera 8.5 needs this # strip trailing whitespace savetext = savetext.rstrip() # Add category separator if last non-empty line contains # non-categories. lines = [line for line in savetext.splitlines() if line] if lines: #TODO: this code is broken, will not work for extended links #categories, e.g ["category hebrew"] categories = lines[-1].split() if categories: confirmed = wikiutil.filterCategoryPages(request, categories) if len(confirmed) < len(categories): # This was not a categories line, add separator savetext += u'\n----\n' # Add new category if savetext and savetext[-1] != u'\n': savetext += ' ' savetext += category + u'\n' # Should end with newline! if (request.cfg.edit_ticketing and not wikiutil.checkTicket(request, request.form.get('ticket', ''))): request.theme.add_msg(_('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'edit' }, "error") pg.sendEditor(preview=savetext, comment=comment, staytop=1) # Preview, spellcheck or spellcheck add new words elif ('button_preview' in request.form or 'button_spellcheck' in request.form or 'button_newwords' in request.form): pg.sendEditor(preview=savetext, comment=comment) # Preview with mode switch elif 'button_switch' in request.form: pg.sendEditor(preview=savetext, comment=comment, staytop=1) # Save new text else: try: from MoinMoin.security.textcha import TextCha if not TextCha(request).check_answer_from_form(): raise pg.SaveError(_('TextCha: Wrong answer! Try again below...')) if request.cfg.comment_required and not comment: raise pg.SaveError(_('Supplying a comment is mandatory. Write a comment below and try again...')) savemsg = pg.saveText(savetext, rev, trivial=trivial, comment=comment) except pg.EditConflict, e: msg = e.message # Handle conflict and send editor pg.set_raw_body(savetext, modified=1) pg.mergeEditConflict(rev) # We don't send preview when we do merge conflict pg.sendEditor(msg=msg, comment=comment) return except pg.SaveError, msg: # Show the error message request.theme.add_msg(unicode(msg), "error") # And show the editor again pg.sendEditor(preview=savetext, comment=comment, staytop=1) return
def _save_user_prefs(self): _ = self._ form = self.request.form request = self.request if request.request_method != 'POST': return if not 'name' in request.user.auth_attribs: # Require non-empty name new_name = form.get('name', [request.user.name])[0] # Don't allow changing the name to an invalid one if not user.isValidName(request, new_name): return 'error', _("""Invalid user name {{{'%s'}}}. Name may contain any Unicode alpha numeric character, with optional one space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(new_name) # Is this an existing user trying to change information or a new user? # Name required to be unique. Check if name belong to another user. existing_id = user.getUserId(request, new_name) if existing_id is not None and existing_id != request.user.id: return 'error', _("This user name already belongs to somebody else.") if not new_name: return 'error', _("Empty user name. Please enter a user name.") # done sanity checking the name, set it request.user.name = new_name if not 'email' in request.user.auth_attribs: # try to get the email new_email = wikiutil.clean_input(form.get('email', [request.user.email])[0]) new_email = new_email.strip() # Require email if not new_email and 'email' not in request.cfg.user_form_remove: return 'error', _("Please provide your email address. If you lose your" " login information, you can get it by email.") # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py if new_email and request.cfg.user_email_unique: other = user.get_by_email_address(request, new_email) if other is not None and other.id != request.user.id: return 'error', _("This email already belongs to somebody else.") # done checking the email, set it request.user.email = new_email if not 'jid' in request.user.auth_attribs: # try to get the jid new_jid = wikiutil.clean_input(form.get('jid', [''])[0]).strip() jid_changed = request.user.jid != new_jid previous_jid = request.user.jid if new_jid and request.cfg.user_jid_unique: other = user.get_by_jabber_id(request, new_jid) if other is not None and other.id != request.user.id: return 'error', _("This jabber id already belongs to somebody else.") if jid_changed: set_event = events.JabberIDSetEvent(request, new_jid) unset_event = events.JabberIDUnsetEvent(request, previous_jid) events.send_event(unset_event) events.send_event(set_event) # done checking the JID, set it request.user.jid = new_jid if not 'aliasname' in request.user.auth_attribs: # aliasname request.user.aliasname = wikiutil.clean_input(form.get('aliasname', [''])[0]) # editor size request.user.edit_rows = util.web.getIntegerInput(request, 'edit_rows', request.user.edit_rows, 10, 60) # try to get the editor request.user.editor_default = form.get('editor_default', [self.cfg.editor_default])[0] request.user.editor_ui = form.get('editor_ui', [self.cfg.editor_ui])[0] # time zone request.user.tz_offset = util.web.getIntegerInput(request, 'tz_offset', request.user.tz_offset, -84600, 84600) # datetime format try: dt_d_combined = Settings._date_formats.get(form['datetime_fmt'][0], '') request.user.datetime_fmt, request.user.date_fmt = dt_d_combined.split(' & ') except (KeyError, ValueError): request.user.datetime_fmt = '' # default request.user.date_fmt = '' # default # try to get the (optional) theme theme_name = form.get('theme_name', [self.cfg.theme_default])[0] if theme_name != request.user.theme_name: # if the theme has changed, load the new theme # so the user has a direct feedback # WARNING: this should be refactored (i.e. theme load # after userform handling), cause currently the # already loaded theme is just replaced (works cause # nothing has been emitted yet) request.user.theme_name = theme_name if request.loadTheme(theme_name) > 0: theme_name = wikiutil.escape(theme_name) return 'error', _("The theme '%(theme_name)s' could not be loaded!") % locals() # try to get the (optional) preferred language request.user.language = form.get('language', [''])[0] if request.user.language == u'': # For language-statistics from MoinMoin import i18n request.user.real_language = i18n.get_browser_language(request) else: request.user.real_language = '' # I want to handle all inputs from user_form_fields, but # don't want to handle the cases that have already been coded # above. # This is a horribly fragile kludge that's begging to break. # Something that might work better would be to define a # handler for each form field, instead of stuffing them all in # one long and inextensible method. That would allow for # plugins to provide methods to validate their fields as well. already_handled = ['name', 'email', 'aliasname', 'edit_rows', 'editor_default', 'editor_ui', 'tz_offset', 'datetime_fmt', 'theme_name', 'language', 'real_language', 'jid'] for field in self.cfg.user_form_fields: key = field[0] if ((key in self.cfg.user_form_disable) or (key in already_handled)): continue default = self.cfg.user_form_defaults[key] value = form.get(key, [default])[0] setattr(request.user, key, value) # checkbox options for key, label in self.cfg.user_checkbox_fields: if key not in self.cfg.user_checkbox_disable and key not in self.cfg.user_checkbox_remove: value = form.get(key, ["0"])[0] try: value = int(value) except ValueError: pass else: setattr(request.user, key, value) # quicklinks for navibar request.user.quicklinks = self._decode_pagelist('quicklinks') # save data request.user.save() if request.user.disabled: # set valid to false so the current request won't # show the user as logged-in any more request.user.valid = False result = _("User preferences saved!") if _debug: result = result + util.dumpFormData(form) return result