def __contains__(self, username): self._init_groupdict() if self.name == 'All': return True elif self.name == 'Known': return user.User(self.request, id=user.getUserId(username, self.request)).valid if self.groupdict.has_key(username): return True return False
def users(self, proper_names=False): """ Returns a list of the user names belonging to the group. """ self._init_groupdict() if not proper_names: return self.groupdict.keys() proper_names = [] for username in self.groupdict.keys(): user_id = user.getUserId(username, self.request) if user_id: proper_names.append( user.User(self.request, id=user_id).propercased_name) else: proper_names.append(username) return proper_names
def isUserPage(request, page): if (config.user_page_prefix and page.page_name.startswith(config.user_page_prefix.lower())): username = page.page_name[len(config.user_page_prefix):] return getUserId(username, request)
def handleData(self, new_user=None): from Sycamore.Page import MAX_PAGENAME_LENGTH as MAX_USERNAME_LENGTH _ = self._ form = self.request.form msg = '' isdisabled = False if form.get('disabled', [0])[0] == '1': isdisabled = True self.from_wiki = None if self.request.form.has_key('from_wiki'): self.from_wiki = self.request.form['from_wiki'][0].lower().strip() if not wikiutil.isInFarm(self.from_wiki, self.request): self.from_wiki = None new_user = int(form.get('new_user', [0])[0]) # wiki farm authentication # we want them to be able to sign back in right after they # click the 'logout' GET link, hence this test is_form_logout = (form.has_key('qs') and urllib.unquote(form['qs'][0]) == 'action=userform&logout=Logout') if (self.request.form.has_key('badlogin') and self.request.form['badlogin'][0]): _create_nologin_cookie(self.request) if config.wiki_farm: wiki_base_url = farm.getBaseFarmURL(self.request) else: wiki_base_url = '%s/' % self.request.getScriptname() return_string = ('Unknown username or wrong password.<br/><br/>' 'New user? <a href="%s%s?new_user=1">Click here ' 'to create an account!</a><br/><br/>' 'Forgot your password? We\'ll email it to you.' '<form action="%s" method="POST">' '<input type="hidden" name="action" ' 'value="userform">' 'Email address: <input class="formfields" ' 'type="text" name="email">' ' <input type="submit" class="formbutton" ' 'name="login_sendmail" ' 'value="Mail me my account data">' '</form>' % ( wiki_base_url, wikiutil.quoteWikiname( config.page_user_preferences), wiki_base_url)) return return_string if (form.has_key('login_check') and form['login_check'][0] and form.has_key('backto_wiki') and form.has_key('backto_page')): backto_wiki = form['backto_wiki'][0] backto_page = form['backto_page'][0].encode(config.charset) if form.has_key('qs') and not is_form_logout: q_query_string = form['qs'][0] else: q_query_string = '' if self.request.user.valid: secret, stored_expire_time, session = \ self.request.user.cookie_dough if q_query_string: url = ('%s?action=userform&backto_page=%s&qs=%s' '&secret=%s&expire_time=%s&uid=%s&session=%s' % ( backto_page, urllib.quote(backto_page), urllib.quote(q_query_string), urllib.quote(secret), stored_expire_time, self.request.user.id, urllib.quote(session))) else: url = ('%s?action=userform&backto_page=%s&secret=%s' '&expire_time=%s&uid=%s&session=%s' % ( backto_page, urllib.quote(backto_page), urllib.quote(secret), stored_expire_time, self.request.user.id, urllib.quote(session))) else: if q_query_string: url = ('%s?action=userform&backto_page=%s¬_logged_in=1' '&qs=%s' % (backto_page, urllib.quote(backto_page), urllib.quote(q_query_string))) else: url = ('%s?action=userform&backto_page=%s¬_logged_in=1' % (backto_page, urllib.quote(backto_page))) self.request.http_redirect(url) return # bounce-back wiki farm authentication if form.has_key('not_logged_in') and form.has_key('backto_page'): backto = urllib.unquote(form['backto_page'][0].encode( config.charset)) if form.has_key('qs') and not is_form_logout: query_string = '?%s' % (urllib.unquote(form['qs'][0] ).encode(config.charset)) else: query_string = '' url = '%s%s' % (backto, query_string) _create_nologin_cookie(self.request) self.request.http_redirect(url) return # bounce-back wiki farm authentication elif (form.has_key('uid') and form.has_key('secret') and form.has_key('session') and form.has_key('expire_time')): uid = form['uid'][0] secret = urllib.unquote(form['secret'][0]) session = form['session'][0] expire_time = float(form['expire_time'][0]) if form.has_key('backto_page'): backto_page = form['backto_page'][0] else: backto_page = '/' if form.has_key('qs') and not is_form_logout: query_string = '?%s' % urllib.unquote(form['qs'][0]) else: query_string = '' url = '%s%s' % (backto_page, query_string) self.request.http_redirect(url) self.request.user.sendCookie(self.request, expire=expire_time, sessionid=session, secret=secret, id=uid) self.request.user.clearNologinCookie(self.request) return if form.has_key('logout') or isdisabled: msg = '' if isdisabled: if not self.request.isPOST(): return "Use the interactive interface to change settings!" # disable the account self.request.user.disabled = 1 # save user's profile self.request.user.save() msg = '<p>%s</p>' % _("Your account has been disabled.") # clear the cookie in the browser and locally try: cookie = Cookie.SimpleCookie(self.request.saved_cookie) except Cookie.CookieError: # ignore invalid cookies cookie = None else: if config.wiki_farm: cookie_id = wikiutil.quoteCookiename( config.wiki_base_domain + ',ID') else: cookie_id = wikiutil.quoteCookiename( config.sitename + ',ID') if cookie.has_key(cookie_id): self.removeSession(cookie[cookie_id].value) cookie_dir = config.web_dir if not cookie_dir: cookie_dir = '/' domain = wikiutil.getCookieDomain(self.request) expirestr = time.strftime("%A, %d-%b-%Y %H:%M:%S GMT", time.gmtime(0)) self.request.setHttpHeader(('Set-Cookie', ('%s="%s"; domain=%s; path=%s; ' 'expires=%s' % ( (cookie_id, cookie[cookie_id].value, domain, cookie_dir, expirestr))))) self.request.saved_cookie = '' self.request.auth_username = '' self.request.user = user.User(self.request) return msg + _("Cookie deleted. You are now logged out.") if form.has_key('login_sendmail'): if not self.request.isPOST(): return "Use the interactive interface to change settings!" if not config.mail_smarthost: return _('This wiki is not enabled for mail processing. ' 'Contact the owner of the wiki, who can either enable ' 'email, or remove the "Subscribe" icon.') try: email = form['email'][0] except KeyError: return _("Please provide a valid email address!") text = '' uid = user.getUserIdByEmail(email, self.request) if uid: theuser = user.User(self.request, uid) if theuser.valid: code = self.createCode(theuser.id) sitename = farm.getBaseWikiFullName(self.request) if config.wiki_farm: url = farm.getBaseFarmURL(self.request) else: url = '%s/' % self.request.getBaseURL() text = ("Go here to automatically log into %s: " "%s%s?action=userform&uid=%s&code=%s\n" "Once you're logged in, you should change your " "password in your settings " "(you forgot your password, right?).\n\n" "(The link in this email is good for " "one use only.)" % ( sitename, url, wikiutil.quoteWikiname( config.page_user_preferences), theuser.id, code)) if not text: return _("Found no account matching the given email address " "'%(email)s'!") % {'email': email} mailok, msg = util.mail.sendmail(self.request, [email], 'Your wiki account data', text, mail_from=config.mail_from) return wikiutil.escape(msg) if form.has_key('login') or form.has_key('uid'): uid = None if form.has_key('code') and form.has_key('uid'): given_uid = form['uid'][0].strip() given_code = form['code'][0].strip() given_code if self.isValidCode(given_uid, given_code): uid = given_uid if uid: # we were given account information so let's # create an account -> log them in theuser = user.User(self.request, id=uid) msg = _("You are now logged in! " "Please change your password below!") # send the cookie theuser.sendCookie(self.request) self.request.user = theuser return msg else: # we weren't given information, so let's see # if they gave us a login/password # try to get the user name try: name = form['username'][0].replace('\t', ' ').strip() except KeyError: name = '' # try to get the password password = form.get('password',[''])[0] # load the user data and check for validness if name: theuser = user.User(self.request, name=name, password=password, is_login=True) else: theuser = user.User(self.request, id=uid, name=name, password=password, is_login=True) if config.wiki_farm: wiki_base_url = farm.getBaseFarmURL(self.request) else: wiki_base_url = '%s/' % self.request.getScriptname() if not theuser.valid: if (not self.request.form.has_key('backto_wiki') or not self.request.form['backto_wiki'][0]): return_string = ('Unknown username or wrong password.' '<br/><br/>New user? ' '<a href="%s%s?new_user=1">' 'Click here to create an account!</a>' '<br/><br/>Forgot your password? ' 'We\'ll email it to you.' '<form action="%s" method="POST">' '<input type="hidden" name="action" ' 'value="userform">' 'Email address: ' '<input class="formfields" ' 'type="text" name="email">' ' ' '<input type="submit" ' 'class="formbutton" ' 'name="login_sendmail" ' 'value="Mail me my account ' 'data">' '</form>' % ( wiki_base_url, wikiutil.quoteWikiname( config.page_user_preferences), wiki_base_url)) return return_string else: self.request.http_redirect( urllib.unquote( self.request.form['backto_page'][0].encode( config.charset)) + '?action=userform&badlogin=1') return # send the cookie theuser.sendCookie(self.request) self.request.user = theuser send_back_home(self.request, msg="You are now logged in!") else: if not self.request.isPOST(): return """Use the interactive interface to change settings!""" # save user's profile, first get user instance theuser = user.User(self.request) # try to get the name # if name is empty or missing, return an error msg if (form.has_key('username') and form['username'][0].replace('\t', '').strip()): theuser.propercased_name = \ form['username'][0].replace('\t', ' ').strip() theuser.name = theuser.propercased_name.lower() elif form.has_key('username'): raise BadData, (_("Please enter a user name!"), new_user) if (self.request.user.name and (self.request.user.name != theuser.name)): # they are still logged on and are trying to make a new account raise BadData, (_("Please log out before creating an account."), new_user) if user.getUserId(theuser.name, self.request): if theuser.name != self.request.user.name: raise BadData, (_("User name already exists!"), new_user) else: new_user = False if form.has_key('save') and form['save'][0] == 'Change password': # change password setting # try to get the password and pw repeat password = form.get('password', [''])[0] password2 = form.get('password2',[''])[0] # Check if password is given and matches with password repeat if password != password2: raise BadData, (_("Passwords don't match!"), new_user) if not password and new_user: raise BadData, (_("Please specify a password!"), new_user) if password: theuser.enc_password = user.generate_hash(password) self._clear_all_sessions_except_current() msg = _("Password changed!") else: # process general settings # tr to get the email theuser.email = form.get('email', [''])[0] if theuser.email: email_user_id = user.getUserIdByEmail(theuser.email, self.request) else: email_user_id = None if not theuser.email or not re.match(".+@.+\..{2,}", theuser.email): raise BadData, (_("Please provide your email address - " "without that you could not " "get your login data via email just in " "case you lose it."), new_user) elif email_user_id and email_user_id != theuser.id: raise BadData, (_("Somebody else has already registered " "with the email address \"%s\", please " "pick something else." % theuser.email), new_user) # editor size theuser.edit_rows = util.web.getIntegerInput(self.request, 'edit_rows', theuser.edit_rows, 10, 60) theuser.edit_cols = util.web.getIntegerInput(self.request, 'edit_cols', theuser.edit_cols, 30, 100) # time zone tz = form.get('tz', theuser.tz)[0] if tz not in pytz.common_timezones: tz = theuser.tz theuser.tz = tz wiki_for_userpage = form.get('wiki_for_userpage', [''])[0].lower() if (wiki_for_userpage and not wikiutil.isInFarm(wiki_for_userpage, self.request)): raise BadData, (_('"%s" is not the name of a wiki.' % ( wiki_for_userpage)), new_user) if wiki_for_userpage != theuser.wiki_for_userpage: # they have changed the wiki! time to do # something differently msg = _("<p>User preferences saved!</p>" "<p><strong>Note:</strong> It may take a bit for " "all links to your name to point to the " "new wiki.</p>") theuser.wiki_for_userpage = wiki_for_userpage # User CSS URL theuser.css_url = form.get('css_url', [''])[0] # try to get the (optional) preferred language #theuser.language = form.get('language', [''])[0] # checkbox options keys = [] for key in user_checkbox_fields: value = form.get(key, [0])[0] try: value = int(value) except ValueError: pass setattr(theuser, key, value) if new_user: # strip spaces, we don't allow them anyway theuser.propercased_name = theuser.propercased_name.strip() theuser.name = theuser.propercased_name.lower() if not theuser.name.strip(): raise BadData, (_("Please provide a user name!"), new_user) elif theuser.propercased_name.find(' ') != -1: raise BadData, (_("Invalid username: spaces are not " "allowed in user names"), new_user) elif re.search('[%s]' % re.escape(USER_NOT_ALLOWED_CHARS), theuser.propercased_name): raise BadData, (_("Invalid username: the characters " "%s are not allowed in usernames." % ( wikiutil.escape( USER_NOT_ALLOWED_CHARS))), new_user) # messes up subpages. # '/' isn't allowed, so we just disallow this and we're cool. elif theuser.name == '..' or theuser.name == '.': raise BadData, (_("Invalid username: okay, seriously, " "that's a pretty lame name. " "Pick something better!"), new_user) elif len(theuser.propercased_name) > MAX_USERNAME_LENGTH: raise BadData, (_("Invalid username: a username can be " "at most %s characters long." % ( MAX_USERNAME_LEGNTH)), new_user) elif (not theuser.email or not re.match(".+@.+\..{2,}", theuser.email)): raise BadData, (_("Please provide your email address - " "without that you could not get your " "login data via email just in case you " "lose it."), new_user) name_exists = user.getUserId(theuser.name, self.request) if name_exists: raise BadData, (_("This user name already belongs to " "somebody else."), new_user) email_exists = user.getUserIdByEmail(theuser.email, self.request) if email_exists: raise BadData, (_("This email already belongs to somebody " "else."), new_user) # try to get the password and pw repeat password = form.get('password', [''])[0] password2 = form.get('password2',[''])[0] # Check if password is given and matches with password repeat if password != password2: raise BadData, (_("Passwords don't match!"), new_user) if not password and new_user: raise BadData, (_("Please specify a password!"), new_user) if password: theuser.enc_password = user.generate_hash(password) theuser.anonymous = False # save data and send cookie theuser.save(new_user=new_user) theuser.sendCookie(self.request) self.request.user = theuser from Sycamore.formatter.text_html import Formatter formatter = Formatter(self.request) if not new_user: if not msg: msg = _("User preferences saved!") if self.from_wiki: go_back_to_wiki = farm.link_to_wiki(self.from_wiki, formatter) msg = ('%s<br/><br/>Wanna go ' 'back to %s?' % (msg, go_back_to_wiki)) else: msg = _("Account created! You are now logged in.") self.request.user.valid = 1 if (self.from_wiki and self.from_wiki.lower() != farm.getBaseWikiName()): go_back_to_wiki = farm.link_to_wiki(self.from_wiki, formatter) msg = ('%s<br/><br/>Head back over to %s and your new account ' 'should work there!' % (msg, go_back_to_wiki)) if _debug: msg = msg + util.dumpFormData(form) return msg
def display_edits(request, userpage, on_pagename): def printNextPrev(request, pagename, last_edit, offset_given): """ prints the next and previous links, if they're needed. """ if last_edit == 1 and not offset_given: return html = [] if last_edit != 1: html.append( '<div class="actionBoxes" ' 'style="margin-right:10px !important; ' 'float: left !important;">' '<span>' '<a href="%s/%s?action=userinfo&offset=%s">' '←previous edits' '</a>' '</span></div>' % (request.getBaseURL(), pagename, offset_given+1)) if offset_given: html.append( '<div class="actionBoxes" style="float: left !important;">' '<span>' '<a href="%s/%s?action=userinfo&offset=%s">' 'next edits→' '</a>' '</span></div>' % (request.getBaseURL(), pagename, offset_given-1)) html.append('<div style="clear: both;"></div>') return [''.join(html)] _ = request.getText edits = TupleDataset() edits.columns = [ Column('page', label=_('Page')), Column('mtime', label=_('Date'), align='right'), Column('ip', label=_('From IP')), Column('comment', label=_('Comment')), ] if config.wiki_farm: edits.columns.insert(1, Column('wiki', label=_('Wiki'))) has_edits = False totalEdits = editedPages = 0 editedWiki = 0 this_edit = 0 offset_given = int(request.form.get('offset', [0])[0]) if not offset_given: offset = 0 else: offset = offset_given*100 - offset_given userid = getUserId(userpage, request) request.cursor.execute("""SELECT count(editTime) from allPages where userEdited=%(userid)s""", {'userid':userid}) count_result = request.cursor.fetchone() if count_result: totalEdits = count_result[0] request.cursor.execute("""SELECT count(DISTINCT name) from allPages where userEdited=%(userid)s""", {'userid':userid}) count_result = request.cursor.fetchone() if count_result: editedPages = count_result[0] request.cursor.execute("""SELECT count(DISTINCT wiki_id) from allPages where userEdited=%(userid)s""", {'userid':userid}) wiki_count_result = request.cursor.fetchone() if wiki_count_result: editedWikis = wiki_count_result[0] request.cursor.execute( """SELECT allPages.name, allPages.editTime, allPages.userIP, allPages.editType, allPages.comment, wikis.name from allPages, wikis where allPages.userEdited=%(userid)s and wikis.id=allPages.wiki_id order by editTime desc limit 100 offset %(offset)s""", {'userid':userid, 'offset':offset}) results = request.cursor.fetchall() if results: has_edits = True count = 1 original_wiki = request.config.wiki_name for edit in results: this_edit = 1 + totalEdits - count - offset pagename = edit[0] mtime = edit[1] userIp = '<a href="http://revip.info/ipinfo/%s" tooltip="%s">%s</a>' % (edit[2], edit[2], edit[2]) editType = edit[3] comment = edit[4] wiki_name = edit[5] request.switch_wiki(wiki_name) page = Page(pagename, request, wiki_name=wiki_name) version = page.date_to_version_number(mtime) if request.user.may.read(page): may_read = True show_page = page.link_to( querystr='action=diff&version2=%s&version1=%s' % (version, version-1), guess_case=True, absolute=True) formatted_mtime = request.user.getFormattedDateTime(mtime) comment = Comment(request, comment, editType).render() else: may_read = False show_page = """<em>hidden</em>""" userIp = '<em>hidden</em>' comment = '<em>hidden</em>' formatted_mtime = '<em>hidden</em>' if config.wiki_farm: if may_read: farm_link = farm.link_to_wiki(wiki_name, request.formatter) else: farm_link = '<em>hidden</em>' edits.addRow((show_page, farm_link, formatted_mtime, userIp, comment)) else: edits.addRow((show_page, formatted_mtime, userIp, comment)) count += 1 request.switch_wiki(original_wiki) if has_edits: request.write('<p>This user has made <b>%d</b> edits to <b>%d</b> ' 'pages' % (totalEdits, editedPages )) if config.wiki_farm: request.write(' on <b>%s</b> wikis' % editedWikis) request.write('.</p>') request.write('<div id="useredits">') edit_table = DataBrowserWidget(request) edit_table.setData(edits) edit_table.render(append=printNextPrev(request, on_pagename, this_edit, offset_given)) request.write('</div>') request.write('<script type="text/javascript" src="/wiki/revipbox.js"></script>') else: request.write("<p>This user hasn't edited any pages.</p>")