Import initial des fichiers de la version 1.5.3 de MoinMoin (mj Etch).

darcs-hash:20070601130042-68412-6e583291d0079b28e4c0cc18a7c8428051d37cb0.gz
This commit is contained in:
glondu 2007-06-01 15:00:42 +02:00
parent 7d86a17433
commit 329eea2862
4 changed files with 1730 additions and 1165 deletions

View file

@ -6,7 +6,7 @@
@license: GNU GPL, see COPYING for details.
"""
import os, string, time, Cookie, sha, codecs
import os, time, sha, codecs
try:
import cPickle as pickle
@ -14,16 +14,10 @@ except ImportError:
import pickle
# Set pickle protocol, see http://docs.python.org/lib/node64.html
try:
# Requires 2.3
PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL
except AttributeError:
# Use protocol 1, binary format compatible with all python versions
PICKLE_PROTOCOL = 1
PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL
from MoinMoin import config, caching, wikiutil
from MoinMoin.util import datetime
from MoinMoin.util import filesys, timefuncs
def getUserList(request):
@ -36,9 +30,10 @@ def getUserList(request):
import re, dircache
user_re = re.compile(r'^\d+\.\d+(\.\d+)?$')
files = dircache.listdir(request.cfg.user_dir)
userlist = filter(user_re.match, files)
userlist = [f for f in files if user_re.match(f)]
return userlist
def getUserId(request, searchName):
"""
Get the user ID for a specific user NAME.
@ -74,6 +69,7 @@ def getUserId(request, searchName):
id = _name2id.get(searchName, None)
return id
def getUserIdentification(request, username=None):
"""
Return user name or IP or '<unknown>' indicator.
@ -96,7 +92,7 @@ def encodePassword(pwd, charset='utf-8'):
Compatible to Apache htpasswd SHA encoding.
When using different encoding then 'utf-8', the encoding might fail
When using different encoding than 'utf-8', the encoding might fail
and raise UnicodeError.
@param pwd: the cleartext password, (unicode)
@ -115,6 +111,7 @@ def encodePassword(pwd, charset='utf-8'):
pwd = sha.new(pwd).digest()
pwd = '{SHA}' + base64.encodestring(pwd).rstrip()
return pwd
def normalizeName(name):
""" Make normalized user name
@ -132,22 +129,26 @@ def normalizeName(name):
@rtype: unicode
@return: user name that can be used in acl lines
"""
# Strip non alpha numeric characters, keep white space
name = ''.join([c for c in name if c.isalnum() or c.isspace()])
name = name.replace('_', ' ') # we treat _ as a blank
username_allowedchars = "'@." # ' for names like O'Brian or email addresses.
# "," and ":" must not be allowed (ACL delimiters).
# Strip non alpha numeric characters (except username_allowedchars), keep white space
name = ''.join([c for c in name if c.isalnum() or c.isspace() or c in username_allowedchars])
# Normalize white space. Each name can contain multiple
# words separated with only one space.
name = ' '.join(name.split())
return name
def isValidName(request, name):
""" Validate user name
@param name: user name, unicode
"""
normalized = normalizeName(name)
name = name.replace('_', ' ') # we treat _ as a blank
return (name == normalized) and not wikiutil.isGroupPage(request, name)
@ -185,47 +186,49 @@ def decodeList(line):
continue
items.append(item)
return items
class User:
"""A MoinMoin User"""
_checkbox_fields = [
('edit_on_doubleclick', lambda _: _('Open editor on double click')),
('remember_last_visit', lambda _: _('Remember last page visited')),
('show_fancy_links', lambda _: _('Show fancy links')),
('show_nonexist_qm', lambda _: _('Show question mark for non-existing pagelinks')),
('show_page_trail', lambda _: _('Show page trail')),
('show_toolbar', lambda _: _('Show icon toolbar')),
('show_topbottom', lambda _: _('Show top/bottom links in headings')),
('show_fancy_diff', lambda _: _('Show fancy diffs')),
('wikiname_add_spaces', lambda _: _('Add spaces to displayed wiki names')),
('remember_me', lambda _: _('Remember login information')),
('want_trivial', lambda _: _('Subscribe to trivial changes')),
('disabled', lambda _: _('Disable this account forever')),
]
_transient_fields = ['id', 'valid', 'may', 'auth_username', 'trusted']
def __init__(self, request, id=None, name="", password=None, auth_username=""):
"""
Initialize user object
def __init__(self, request, id=None, name="", password=None, auth_username="", **kw):
""" Initialize User object
@param request: the request object
@param id: (optional) user ID
@param name: (optional) user name
@param password: (optional) user password
@param auth_username: (optional) already authenticated user name (e.g. apache basic auth)
@param auth_username: (optional) already authenticated user name
(e.g. when using http basic auth)
@keyword auth_method: method that was used for authentication,
default: 'internal'
@keyword auth_attribs: tuple of user object attribute names that are
determined by auth method and should not be
changed by UserPreferences form, default: ().
First tuple element was used for authentication.
"""
self._cfg = request.cfg
self.valid = 0
self.trusted = 0
self.id = id
if auth_username:
self.auth_username = auth_username
elif request:
self.auth_username = request.auth_username
else:
self.auth_username = ""
self.name = name
self.auth_username = auth_username
self.auth_method = kw.get('auth_method', 'internal')
self.auth_attribs = kw.get('auth_attribs', ())
# create some vars automatically
for tuple in self._cfg.user_form_fields:
key = tuple[0]
default = self._cfg.user_form_defaults.get(key, '')
setattr(self, key, default)
if name:
self.name = name
elif auth_username: # this is needed for user_autocreate
self.name = auth_username
# create checkbox fields (with default 0)
for key, label in self._cfg.user_checkbox_fields:
setattr(self, key, self._cfg.user_checkbox_defaults.get(key, 0))
self.enc_password = ""
if password:
@ -237,69 +240,41 @@ class User:
except UnicodeError:
pass # Should never happen
self.trusted = 0
self.email = ""
self.edit_rows = self._cfg.edit_rows
#self.edit_cols = 80
self.tz_offset = int(float(self._cfg.tz_offset) * 3600)
self.last_saved = str(time.time())
self.css_url = ""
self.language = ""
self.quicklinks = []
self.date_fmt = ""
self.datetime_fmt = ""
self.quicklinks = []
self.subscribed_pages = []
self.theme_name = self._cfg.theme_default
# if an account is disabled, it may be used for looking up
# id -> username for page info and recent changes, but it
# is not usable for the user any more:
# self.disabled = 0
# is handled by checkbox now.
self.editor_default = self._cfg.editor_default
self.editor_ui = self._cfg.editor_ui
self.last_saved = str(time.time())
# attrs not saved to profile
self._request = request
self._trail = []
# create checkbox fields (with default 0)
for key, label in self._checkbox_fields:
setattr(self, key, 0)
self.wikiname_add_spaces = 1
self.show_page_trail = 1
self.show_fancy_links = 1
#self.show_emoticons = 1
self.show_toolbar = 1
self.show_nonexist_qm = self._cfg.nonexist_qm
self.show_fancy_diff = 1
self.want_trivial = 0
self.remember_me = 1
if not self.id and not self.auth_username:
try:
cookie = Cookie.SimpleCookie(request.saved_cookie)
except Cookie.CookieError:
# ignore invalid cookies, else user can't re login
cookie = None
if cookie and cookie.has_key('MOIN_ID'):
self.id = cookie['MOIN_ID'].value
# we got an already authenticated username:
check_pass = 0
if not self.id and self.auth_username:
self.id = getUserId(request, self.auth_username)
if not password is None:
check_pass = 1
if self.id:
self.load_from_id()
self.load_from_id(check_pass)
if self.name == self.auth_username:
self.trusted = 1
elif self.name:
self.load()
self.id = getUserId(self._request, self.name)
if self.id:
self.load_from_id(1)
else:
self.id = self.make_id()
else:
#!!! this should probably be a hash of REMOTE_ADDR, HTTP_USER_AGENT
# and some other things identifying remote users, then we could also
# use it reliably in edit locking
from random import randint
self.id = "%s.%d" % (str(time.time()), randint(0,65535))
self.id = self.make_id()
# "may" so we can say "if user.may.read(pagename):"
if self._cfg.SecurityPolicy:
self.may = self._cfg.SecurityPolicy(self)
@ -311,40 +286,53 @@ class User:
if self.language and not languages.has_key(self.language):
self.language = 'en'
def __repr__(self):
return "<%s.%s at 0x%x name:%r id:%s valid:%r>" % (
self.__class__.__module__, self.__class__.__name__,
id(self), self.name, self.id, self.valid)
def __filename(self):
def make_id(self):
""" make a new unique user id """
#!!! this should probably be a hash of REMOTE_ADDR, HTTP_USER_AGENT
# and some other things identifying remote users, then we could also
# use it reliably in edit locking
from random import randint
return "%s.%d" % (str(time.time()), randint(0,65535))
def create_or_update(self, changed=False):
""" Create or update a user profile
@param changed: bool, set this to True if you updated the user profile values
"""
get filename of the user's file on disk
if self._cfg.user_autocreate:
if not self.valid and not self.disabled or changed: # do we need to save/update?
self.save() # yes, create/update user profile
def __filename(self):
""" Get filename of the user's file on disk
@rtype: string
@return: full path and filename of user account file
"""
return os.path.join(self._cfg.user_dir, self.id or "...NONE...")
def __bookmark_filename(self):
if self._cfg.interwikiname:
return (self.__filename() + "." + self._cfg.interwikiname +
".bookmark")
else:
return self.__filename() + ".bookmark"
def exists(self):
"""
Do we have a user account for this user?
""" Do we have a user account for this user?
@rtype: bool
@return: true, if we have a user account
"""
return os.path.exists(self.__filename())
def load(self):
"""
Lookup user ID by user name and load user account.
Can load user data if the user name is known, but only if the password is set correctly.
"""
self.id = getUserId(self._request, self.name)
if self.id:
self.load_from_id(1)
#print >>sys.stderr, "self.id: %s, self.name: %s" % (self.id, self.name)
def load_from_id(self, check_pass=0):
"""
Load user account data from disk.
""" Load user account data from disk.
Can only load user data if the id number is already known.
@ -354,7 +342,8 @@ class User:
@param check_pass: If 1, then self.enc_password must match the
password in the user account file.
"""
if not self.exists(): return
if not self.exists():
return
data = codecs.open(self.__filename(), "r", config.charset).readlines()
user_data = {'enc_password': ''}
@ -364,7 +353,7 @@ class User:
try:
key, val = line.strip().split('=', 1)
if key not in self._transient_fields and key[0] != '_':
if key not in self._cfg.user_transient_fields and key[0] != '_':
# Decode list values
if key in ['quicklinks', 'subscribed_pages']:
val = decodeList(val)
@ -387,6 +376,11 @@ class User:
else:
self.trusted = 1
# Remove ignored checkbox values from user data
for key, label in self._cfg.user_checkbox_fields:
if user_data.has_key(key) and key in self._cfg.user_checkbox_disable:
del user_data[key]
# Copy user data into user object
for key, val in user_data.items():
vars(self)[key] = val
@ -394,14 +388,14 @@ class User:
self.tz_offset = int(self.tz_offset)
# Remove old unsupported attributes from user data file.
remove_attributes = ['password', 'passwd', 'show_emoticons']
remove_attributes = ['passwd', 'show_emoticons']
for attr in remove_attributes:
if hasattr(self, attr):
delattr(self, attr)
changed = 1
# make sure checkboxes are boolean
for key, label in self._checkbox_fields:
for key, label in self._cfg.user_checkbox_fields:
try:
setattr(self, key, int(getattr(self, key)))
except ValueError:
@ -467,7 +461,6 @@ class User:
return False, False
# First get all available pre13 charsets on this system
import codecs
pre13 = ['iso-8859-1', 'iso-8859-2', 'euc-jp', 'gb2312', 'big5',]
available = []
for charset in pre13:
@ -496,8 +489,7 @@ class User:
return False, False
def save(self):
"""
Save user account data to user account file on disk.
""" Save user account data to user account file on disk.
This saves all member variables, except "id" and "valid" and
those starting with an underscore.
@ -506,9 +498,7 @@ class User:
return
user_dir = self._cfg.user_dir
if not os.path.isdir(user_dir):
os.mkdir(user_dir, 0777 & config.umask)
os.chmod(user_dir, 0777 & config.umask)
filesys.makeDirs(user_dir)
self.last_saved = str(time.time())
@ -522,7 +512,7 @@ class User:
attrs = vars(self).items()
attrs.sort()
for key, value in attrs:
if key not in self._transient_fields and key[0] != '_':
if key not in self._cfg.user_transient_fields and key[0] != '_':
# Encode list values
if key in ['quicklinks', 'subscribed_pages']:
value = encodeList(value)
@ -538,20 +528,21 @@ class User:
if not self.disabled:
self.valid = 1
# -----------------------------------------------------------------
# Time and date formatting
def getTime(self, tm):
"""
Get time in user's timezone.
""" Get time in user's timezone.
@param tm: time (UTC UNIX timestamp)
@rtype: int
@return: tm tuple adjusted for user's timezone
"""
return datetime.tmtuple(tm + self.tz_offset)
return timefuncs.tmtuple(tm + self.tz_offset)
def getFormattedDate(self, tm):
"""
Get formatted date adjusted for user's timezone.
""" Get formatted date adjusted for user's timezone.
@param tm: time (UTC UNIX timestamp)
@rtype: string
@ -562,8 +553,7 @@ class User:
def getFormattedDateTime(self, tm):
"""
Get formatted date and time adjusted for user's timezone.
""" Get formatted date and time adjusted for user's timezone.
@param tm: time (UTC UNIX timestamp)
@rtype: string
@ -572,62 +562,165 @@ class User:
datetime_fmt = self.datetime_fmt or self._cfg.datetime_fmt
return time.strftime(datetime_fmt, self.getTime(tm))
# -----------------------------------------------------------------
# Bookmark
def setBookmark(self, tm=None):
"""
Set bookmark timestamp.
def setBookmark(self, tm):
""" Set bookmark timestamp.
@param tm: time (UTC UNIX timestamp), default: current time
@param tm: timestamp
"""
if self.valid:
if tm is None:
tm = time.time()
bmfile = open(self.__filename() + ".bookmark", "w")
bm_fn = self.__bookmark_filename()
bmfile = open(bm_fn, "w")
bmfile.write(str(tm)+"\n")
bmfile.close()
try:
os.chmod(self.__filename() + ".bookmark", 0666 & config.umask)
os.chmod(bm_fn, 0666 & config.umask)
except OSError:
pass
# XXX Do we need that???
#try:
# os.utime(self.__filename() + ".bookmark", (tm, tm))
#except OSError:
# pass
def getBookmark(self):
"""
Get bookmark timestamp.
""" Get bookmark timestamp.
@rtype: int
@return: bookmark time (UTC UNIX timestamp) or None
@return: bookmark timestamp or None
"""
if self.valid and os.path.exists(self.__filename() + ".bookmark"):
try:
return int(open(self.__filename() + ".bookmark", 'r').readline())
except (OSError, ValueError):
return None
return None
bm = None
bm_fn = self.__bookmark_filename()
if self.valid and os.path.exists(bm_fn):
try:
bm = long(open(bm_fn, 'r').readline()) # must be long for py 2.2
except (OSError, ValueError):
pass
return bm
def delBookmark(self):
"""
Removes bookmark timestamp.
""" Removes bookmark timestamp.
@rtype: int
@return: 0 on success, 1 on failure
"""
bm_fn = self.__bookmark_filename()
if self.valid:
if os.path.exists(self.__filename() + ".bookmark"):
if os.path.exists(bm_fn):
try:
os.unlink(self.__filename() + ".bookmark")
os.unlink(bm_fn)
except OSError:
return 1
return 0
return 1
# -----------------------------------------------------------------
# Subscribe
def getSubscriptionList(self):
""" Get list of pages this user has subscribed to
@rtype: list
@return: pages this user has subscribed to
"""
return self.subscribed_pages
def isSubscribedTo(self, pagelist):
""" Check if user subscription matches any page in pagelist.
The subscription list may contain page names or interwiki page
names. e.g 'Page Name' or 'WikiName:Page_Name'
TODO: check if its fast enough when calling with many users
from page.getSubscribersList()
@param pagelist: list of pages to check for subscription
@rtype: bool
@return: if user is subscribed any page in pagelist
"""
if not self.valid:
return False
import re
# Create a new list with both names and interwiki names.
pages = pagelist[:]
if self._cfg.interwikiname:
pages += [self._interWikiName(pagename) for pagename in pagelist]
# Create text for regular expression search
text = '\n'.join(pages)
for pattern in self.getSubscriptionList():
# Try simple match first
if pattern in pages:
return True
# Try regular expression search, skipping bad patterns
try:
pattern = re.compile(r'^%s$' % pattern, re.M)
except re.error:
continue
if pattern.search(text):
return True
return False
def subscribe(self, pagename):
""" Subscribe to a wiki page.
To enable shared farm users, if the wiki has an interwiki name,
page names are saved as interwiki names.
@param pagename: name of the page to subscribe
@type pagename: unicode
@rtype: bool
@return: if page was subscribed
"""
if self._cfg.interwikiname:
pagename = self._interWikiName(pagename)
if pagename not in self.subscribed_pages:
self.subscribed_pages.append(pagename)
self.save()
return True
return False
def unsubscribe(self, pagename):
""" Unsubscribe a wiki page.
Try to unsubscribe by removing non-interwiki name (leftover
from old use files) and interwiki name from the subscription
list.
Its possible that the user will be subscribed to a page by more
then one pattern. It can be both pagename and interwiki name,
or few patterns that all of them match the page. Therefore, we
must check if the user is still subscribed to the page after we
try to remove names from the list.
TODO: should we remove non-interwiki subscription? what if the
user want to subscribe to the same page in multiple wikis?
@param pagename: name of the page to subscribe
@type pagename: unicode
@rtype: bool
@return: if unsubscrieb was successful. If the user has a
regular expression that match, it will always fail.
"""
changed = False
if pagename in self.subscribed_pages:
self.subscribed_pages.remove(pagename)
changed = True
interWikiName = self._interWikiName(pagename)
if interWikiName and interWikiName in self.subscribed_pages:
self.subscribed_pages.remove(interWikiName)
changed = True
if changed:
self.save()
return not self.isSubscribedTo([pagename])
# -----------------------------------------------------------------
# Quicklinks
def getQuickLinks(self):
""" Get list of pages this user wants in the navibar
@ -635,80 +728,105 @@ class User:
@return: quicklinks from user account
"""
return self.quicklinks
def getSubscriptionList(self):
""" Get list of pages this user has subscribed to
def isQuickLinkedTo(self, pagelist):
""" Check if user quicklink matches any page in pagelist.
@rtype: list
@return: pages this user has subscribed to
"""
return self.subscribed_pages
def isSubscribedTo(self, pagelist):
"""
Check if user subscription matches any page in pagelist.
@param pagelist: list of pages to check for subscription
@rtype: int
@return: 1, if user has subscribed any page in pagelist
0, if not
"""
import re
matched = 0
if self.valid:
pagelist_lines = '\n'.join(pagelist)
for pattern in self.getSubscriptionList():
# check if pattern matches one of the pages in pagelist
matched = pattern in pagelist
if matched: break
try:
rexp = re.compile("^"+pattern+"$", re.M)
except re.error:
# skip bad regex
continue
matched = rexp.search(pagelist_lines)
if matched: break
if matched:
return 1
else:
return 0
def subscribePage(self, pagename, remove=False):
""" Subscribe or unsubscribe to a wiki page.
Note that you need to save the user data to make this stick!
@param pagename: name of the page to subscribe
@param remove: unsubscribe pagename if set
@type remove: bool
@param pagelist: list of pages to check for quicklinks
@rtype: bool
@return: true, if page was NEWLY subscribed.
@return: if user has quicklinked any page in pagelist
"""
if remove:
if pagename in self.subscribed_pages:
self.subscribed_pages.remove(pagename)
return 1
else:
if pagename not in self.subscribed_pages:
self.subscribed_pages.append(pagename)
return 1
return 0
if not self.valid:
return False
for pagename in pagelist:
if pagename in self.quicklinks:
return True
interWikiName = self._interWikiName(pagename)
if interWikiName and interWikiName in self.quicklinks:
return True
return False
def addQuicklink(self, pagename):
""" Adds a page to the user quicklinks
If the wiki has an interwiki name, all links are saved as
interwiki names. If not, as simple page name.
@param pagename: page name
@type pagename: unicode
@rtype: bool
@return: if pagename was added
"""
changed = False
interWikiName = self._interWikiName(pagename)
if interWikiName:
if pagename in self.quicklinks:
self.quicklinks.remove(pagename)
changed = True
if interWikiName not in self.quicklinks:
self.quicklinks.append(interWikiName)
changed = True
else:
if pagename not in self.quicklinks:
self.quicklinks.append(pagename)
changed = True
if changed:
self.save()
return changed
def removeQuicklink(self, pagename):
""" Remove a page from user quicklinks
Remove both interwiki and simple name from quicklinks.
@param pagename: page name
@type pagename: unicode
@rtype: bool
@return: if pagename was removed
"""
changed = False
interWikiName = self._interWikiName(pagename)
if interWikiName and interWikiName in self.quicklinks:
self.quicklinks.remove(interWikiName)
changed = True
if pagename in self.quicklinks:
self.quicklinks.remove(pagename)
changed = True
if changed:
self.save()
return changed
def _interWikiName(self, pagename):
""" Return the inter wiki name of a page name
@param pagename: page name
@type pagename: unicode
"""
if not self._cfg.interwikiname:
return None
# Interwiki links must use _ e.g Wiki:Main_Page
pagename = pagename.replace(" ", "_")
return "%s:%s" % (self._cfg.interwikiname, pagename)
# -----------------------------------------------------------------
# Trail
def addTrail(self, pagename):
"""
Add page to trail.
""" Add page to trail.
@param pagename: the page name to add to the trail
"""
# TODO: acquire lock here, so multiple processes don't clobber
# each one trail.
if self.valid and (self.show_page_trail or self.remember_last_visit):
# load trail if not known
self.getTrail()
# don't append tail to trail ;)
if self._trail and self._trail[-1] == pagename: return
# Add only existing pages that the user may read
if self._request:
@ -718,25 +836,47 @@ class User:
self._request.user.may.read(page.page_name)):
return
# append new page, limiting the length
self._trail = filter(lambda p, pn=pagename: p != pn, self._trail)
# Save interwiki links internally
if self._cfg.interwikiname:
pagename = self._interWikiName(pagename)
# Don't append tail to trail ;)
if self._trail and self._trail[-1] == pagename:
return
# Append new page, limiting the length
self._trail = [p for p in self._trail if p != pagename]
self._trail = self._trail[-(self._cfg.trail_size-1):]
self._trail.append(pagename)
self.saveTrail()
# save new trail
trailfile = codecs.open(self.__filename() + ".trail", "w", config.charset)
for t in self._trail:
trailfile.write('%s\n' % t)
trailfile.close()
# TODO: release lock here
def saveTrail(self):
""" Save trail file
Save using one write call, which should be fine in most cases,
but will fail in rare cases without real file locking.
"""
data = '\n'.join(self._trail) + '\n'
path = self.__filename() + ".trail"
try:
file = codecs.open(path, "w", config.charset)
try:
os.chmod(self.__filename() + ".trail", 0666 & config.umask)
except OSError:
pass
file.write(data)
finally:
file.close()
try:
os.chmod(path, 0666 & config.umask)
except OSError, err:
self._request.log("Can't change mode of trail file: %s" %
str(err))
except (IOError, OSError), err:
self._request.log("Can't save trail file: %s" % str(err))
def getTrail(self):
"""
Return list of recently visited pages.
""" Return list of recently visited pages.
@rtype: list
@return: pages in trail
@ -745,12 +885,99 @@ class User:
and not self._trail \
and os.path.exists(self.__filename() + ".trail"):
try:
self._trail = codecs.open(self.__filename() + ".trail", 'r', config.charset).readlines()
trail = codecs.open(self.__filename() + ".trail", 'r', config.charset).readlines()
except (OSError, ValueError):
self._trail = []
else:
self._trail = filter(None, map(string.strip, self._trail))
self._trail = self._trail[-self._cfg.trail_size:]
trail = []
trail = [t.strip() for t in trail]
trail = [t for t in trail if t]
self._trail = trail[-self._cfg.trail_size:]
return self._trail
# -----------------------------------------------------------------
# Other
def isCurrentUser(self):
return self._request.user.name == self.name
def isSuperUser(self):
superusers = self._request.cfg.superuser
assert isinstance(superusers, (list, tuple))
return self.valid and self.name and self.name in superusers
def host(self):
""" Return user host """
_ = self._request.getText
host = self.isCurrentUser() and self._cfg.show_hosts and self._request.remote_addr
return host or _("<unknown>")
def signature(self):
""" Return user signature using markup
Users sign with a link to their homepage, or with text if they
don't have one. The text may be parsed as a link if it's using
CamelCase. Visitors return their host address.
TODO: The signature use wiki format only, for example, it will
not create a link when using rst format. It will also break if
we change wiki syntax.
"""
if not self.name:
return self.host()
wikiname, pagename = wikiutil.getInterwikiHomePage(self._request,
self.name)
if wikiname == 'Self':
if not wikiutil.isStrictWikiname(self.name):
markup = '["%s"]' % pagename
else:
markup = pagename
else:
markup = '%s:%s' % (wikiname, pagename.replace(" ","_"))
return markup
def mailAccountData(self, cleartext_passwd=None):
from MoinMoin.util import mail
from MoinMoin.wikiutil import getSysPage
_ = self._request.getText
if not self.enc_password: # generate pw if there is none yet
from random import randint
import base64
charset = 'utf-8'
pwd = "%s%d" % (str(time.time()), randint(0, 65535))
pwd = pwd.encode(charset)
pwd = sha.new(pwd).digest()
pwd = '{SHA}%s' % base64.encodestring(pwd).rstrip()
self.enc_password = pwd
self.save()
text = '\n' + _("""\
Login Name: %s
Login Password: %s
Login URL: %s/%s
""", formatted=False) % (
self.name, self.enc_password, self._request.getBaseURL(), getSysPage(self._request, 'UserPreferences').page_name)
text = _("""\
Somebody has requested to submit your account data to this email address.
If you lost your password, please use the data below and just enter the
password AS SHOWN into the wiki's password form field (use copy and paste
for that).
After successfully logging in, it is of course a good idea to set a new and known password.
""", formatted=False) + text
subject = _('[%(sitename)s] Your wiki account data',
formatted=False) % {'sitename': self._cfg.sitename or "Wiki"}
mailok, msg = mail.sendmail(self._request, [self.email], subject,
text, mail_from=self._cfg.mail_from)
return msg