Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes
MoinMoin.userprefs.prefs.Settings Class Reference

This is still a mess. More...

Inheritance diagram for MoinMoin.userprefs.prefs.Settings:
Inheritance graph
[legend]
Collaboration diagram for MoinMoin.userprefs.prefs.Settings:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def handle_form
def create_form
def handle_form
def allowed
def make_form
def make_row

Public Attributes

 request
 cfg
 title
 name

Private Member Functions

def _decode_pagelist
def _save_user_prefs
def _tz_select
def _dtfmt_select
def _lang_select
def _theme_select
def _editor_default_select
def _editor_ui_select

Private Attributes

 _
 _form

Static Private Attributes

dictionary _date_formats

Detailed Description

This is still a mess.

The plan for refactoring would be: split the plugin into multiple preferences pages:

Definition at line 28 of file prefs.py.


Constructor & Destructor Documentation

def MoinMoin.userprefs.prefs.Settings.__init__ (   self,
  request 
)
Initialize user settings form. 

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 29 of file prefs.py.

00029 
00030     def __init__(self, request):
00031         """ Initialize user settings form. """
00032         UserPrefBase.__init__(self, request)
00033         self.request = request
00034         self._ = request.getText
00035         self.cfg = request.cfg
00036         _ = self._
00037         self.title = _("Preferences")
00038         self.name = 'prefs'


Member Function Documentation

def MoinMoin.userprefs.prefs.Settings._decode_pagelist (   self,
  key 
) [private]
Decode list of pages from form input

Each line is a page name, empty lines ignored.

@param key: the form key to get
@rtype: list of unicode strings
@return: list of normalized names

Definition at line 39 of file prefs.py.

00039 
00040     def _decode_pagelist(self, key):
00041         """ Decode list of pages from form input
00042 
00043         Each line is a page name, empty lines ignored.
00044 
00045         @param key: the form key to get
00046         @rtype: list of unicode strings
00047         @return: list of normalized names
00048         """
00049         text = self.request.form.get(key, '')
00050         text = text.replace('\r', '')
00051         items = []
00052         for item in text.split('\n'):
00053             item = item.strip()
00054             if not item:
00055                 continue
00056             items.append(item)
00057         return items

Here is the caller graph for this function:

Create date format selection. 

Definition at line 267 of file prefs.py.

00267 
00268     def _dtfmt_select(self):
00269         """ Create date format selection. """
00270         _ = self._
00271         try:
00272             dt_d_combined = '%s & %s' % (self.request.user.datetime_fmt, self.request.user.date_fmt)
00273             selected = [
00274                 k for k, v in self._date_formats.items()
00275                     if v == dt_d_combined][0]
00276         except IndexError:
00277             selected = ''
00278         options = [('', _('Default'))] + self._date_formats.items()
00279 
00280         return util.web.makeSelection('datetime_fmt', options, selected)
00281 

Create editor selection. 

Definition at line 305 of file prefs.py.

00305 
00306     def _editor_default_select(self):
00307         """ Create editor selection. """
00308         editor_default = self.request.user.valid and self.request.user.editor_default or self.cfg.editor_default
00309         options = [("<default>", "<%s>" % self._("Default"))]
00310         for editor in ['text', 'gui', ]:
00311             options.append((editor, editor))
00312         return util.web.makeSelection('editor_default', options, editor_default)

Create editor selection. 

Definition at line 313 of file prefs.py.

00313 
00314     def _editor_ui_select(self):
00315         """ Create editor selection. """
00316         editor_ui = self.request.user.valid and self.request.user.editor_ui or self.cfg.editor_ui
00317         options = [("<default>", "<%s>" % self._("Default")),
00318                    ("theonepreferred", self._("the one preferred")),
00319                    ("freechoice", self._("free choice")),
00320                   ]
00321         return util.web.makeSelection('editor_ui', options, editor_ui)
00322 

def MoinMoin.userprefs.prefs.Settings._lang_select (   self,
  enabled = True 
) [private]
Create language selection. 

Definition at line 282 of file prefs.py.

00282 
00283     def _lang_select(self, enabled=True):
00284         """ Create language selection. """
00285         from MoinMoin import i18n
00286         _ = self._
00287         cur_lang = self.request.user.valid and self.request.user.language or ''
00288         langs = i18n.wikiLanguages().items()
00289         langs.sort(lambda x, y: cmp(x[1]['x-language'], y[1]['x-language']))
00290         options = [('', _('<Browser setting>'))]
00291         for lang in langs:
00292             name = lang[1]['x-language']
00293             options.append((lang[0], name))
00294 
00295         return util.web.makeSelection('language', options, cur_lang, 1, False, enabled)

Definition at line 58 of file prefs.py.

00058 
00059     def _save_user_prefs(self):
00060         _ = self._
00061         form = self.request.form
00062         request = self.request
00063 
00064         if request.method != 'POST':
00065             return
00066 
00067         if not 'name' in request.user.auth_attribs:
00068             # Require non-empty name
00069             new_name = form.get('name', request.user.name)
00070 
00071             # Don't allow changing the name to an invalid one
00072             if not user.isValidName(request, new_name):
00073                 return 'error', _("""Invalid user name {{{'%s'}}}.
00074 Name may contain any Unicode alpha numeric character, with optional one
00075 space between words. Group page name is not allowed.""", wiki=True) % wikiutil.escape(new_name)
00076 
00077             # Is this an existing user trying to change information or a new user?
00078             # Name required to be unique. Check if name belong to another user.
00079             existing_id = user.getUserId(request, new_name)
00080             if existing_id is not None and existing_id != request.user.id:
00081                 return 'error', _("This user name already belongs to somebody else.")
00082 
00083             if not new_name:
00084                 return 'error', _("Empty user name. Please enter a user name.")
00085 
00086             # done sanity checking the name, set it
00087             request.user.name = new_name
00088 
00089 
00090         if not 'email' in request.user.auth_attribs:
00091             # try to get the email
00092             new_email = wikiutil.clean_input(form.get('email', request.user.email))
00093             new_email = new_email.strip()
00094 
00095             # Require email
00096             if not new_email and 'email' not in request.cfg.user_form_remove:
00097                 return 'error', _("Please provide your email address. If you lose your"
00098                                   " login information, you can get it by email.")
00099 
00100             # Email should be unique - see also MoinMoin/script/accounts/moin_usercheck.py
00101             if new_email and request.cfg.user_email_unique:
00102                 other = user.get_by_email_address(request, new_email)
00103                 if other is not None and other.id != request.user.id:
00104                     return 'error', _("This email already belongs to somebody else.")
00105 
00106             # done checking the email, set it
00107             request.user.email = new_email
00108 
00109 
00110         if not 'jid' in request.user.auth_attribs:
00111             # try to get the jid
00112             new_jid = wikiutil.clean_input(form.get('jid', '')).strip()
00113 
00114             jid_changed = request.user.jid != new_jid
00115             previous_jid = request.user.jid
00116 
00117             if new_jid and request.cfg.user_jid_unique:
00118                 other = user.get_by_jabber_id(request, new_jid)
00119                 if other is not None and other.id != request.user.id:
00120                     return 'error', _("This jabber id already belongs to somebody else.")
00121 
00122             if jid_changed:
00123                 set_event = events.JabberIDSetEvent(request, new_jid)
00124                 unset_event = events.JabberIDUnsetEvent(request, previous_jid)
00125                 events.send_event(unset_event)
00126                 events.send_event(set_event)
00127 
00128             # done checking the JID, set it
00129             request.user.jid = new_jid
00130 
00131 
00132         if not 'aliasname' in request.user.auth_attribs:
00133             # aliasname
00134             request.user.aliasname = wikiutil.clean_input(form.get('aliasname', ''))
00135 
00136         # editor size
00137         request.user.edit_rows = util.web.getIntegerInput(request, 'edit_rows',
00138                                                           request.user.edit_rows, 10, 60)
00139 
00140         # try to get the editor
00141         request.user.editor_default = form.get('editor_default', self.cfg.editor_default)
00142         request.user.editor_ui = form.get('editor_ui', self.cfg.editor_ui)
00143 
00144         # time zone
00145         request.user.tz_offset = util.web.getIntegerInput(request, 'tz_offset',
00146                                                           request.user.tz_offset, -84600, 84600)
00147 
00148         # datetime format
00149         try:
00150             dt_d_combined = Settings._date_formats.get(form['datetime_fmt'], '')
00151             request.user.datetime_fmt, request.user.date_fmt = dt_d_combined.split(' & ')
00152         except (KeyError, ValueError):
00153             request.user.datetime_fmt = '' # default
00154             request.user.date_fmt = '' # default
00155 
00156         # try to get the (optional) theme
00157         theme_name = form.get('theme_name', self.cfg.theme_default)
00158         if theme_name != request.user.theme_name:
00159             # if the theme has changed, load the new theme
00160             # so the user has a direct feedback
00161             # WARNING: this should be refactored (i.e. theme load
00162             # after userform handling), cause currently the
00163             # already loaded theme is just replaced (works cause
00164             # nothing has been emitted yet)
00165             request.user.theme_name = theme_name
00166             if load_theme_fallback(request, theme_name) > 0:
00167                 theme_name = wikiutil.escape(theme_name)
00168                 return 'error', _("The theme '%(theme_name)s' could not be loaded!") % locals()
00169 
00170         # try to get the (optional) preferred language
00171         request.user.language = form.get('language', '')
00172         if request.user.language == u'': # For language-statistics
00173             from MoinMoin import i18n
00174             request.user.real_language = i18n.get_browser_language(request)
00175         else:
00176             request.user.real_language = ''
00177 
00178         # I want to handle all inputs from user_form_fields, but
00179         # don't want to handle the cases that have already been coded
00180         # above.
00181         # This is a horribly fragile kludge that's begging to break.
00182         # Something that might work better would be to define a
00183         # handler for each form field, instead of stuffing them all in
00184         # one long and inextensible method.  That would allow for
00185         # plugins to provide methods to validate their fields as well.
00186         already_handled = ['name', 'email',
00187                            'aliasname', 'edit_rows', 'editor_default',
00188                            'editor_ui', 'tz_offset', 'datetime_fmt',
00189                            'theme_name', 'language', 'real_language', 'jid']
00190         for field in self.cfg.user_form_fields:
00191             key = field[0]
00192             if ((key in self.cfg.user_form_disable)
00193                 or (key in already_handled)):
00194                 continue
00195             default = self.cfg.user_form_defaults[key]
00196             value = form.get(key, default)
00197             setattr(request.user, key, value)
00198 
00199         # checkbox options
00200         for key, label in self.cfg.user_checkbox_fields:
00201             if key not in self.cfg.user_checkbox_disable and key not in self.cfg.user_checkbox_remove:
00202                 value = form.get(key, "0")
00203                 try:
00204                     value = int(value)
00205                 except ValueError:
00206                     pass
00207                 else:
00208                     setattr(request.user, key, value)
00209 
00210         # quicklinks for navibar
00211         request.user.quicklinks = self._decode_pagelist('quicklinks')
00212 
00213         # save data
00214         request.user.save()
00215         if request.user.disabled:
00216             # set valid to false so the current request won't
00217             # show the user as logged-in any more
00218             request.user.valid = False
00219 
00220         result = _("User preferences saved!")
00221         return result
00222 

Here is the call graph for this function:

Here is the caller graph for this function:

Create theme selection. 

Definition at line 296 of file prefs.py.

00296 
00297     def _theme_select(self):
00298         """ Create theme selection. """
00299         cur_theme = self.request.user.valid and self.request.user.theme_name or self.cfg.theme_default
00300         options = [("<default>", "<%s>" % self._("Default"))]
00301         for theme in wikiutil.getPlugins('theme', self.request.cfg):
00302             options.append((theme, theme))
00303 
00304         return util.web.makeSelection('theme_name', options, cur_theme)

def MoinMoin.userprefs.prefs.Settings._tz_select (   self,
  enabled = True 
) [private]
Create time zone selection. 

Definition at line 242 of file prefs.py.

00242 
00243     def _tz_select(self, enabled=True):
00244         """ Create time zone selection. """
00245         tz = 0
00246         if self.request.user.valid:
00247             tz = int(self.request.user.tz_offset)
00248 
00249         options = []
00250         now = time.time()
00251         for halfhour in range(-47, 48):
00252             offset = halfhour * 1800
00253             t = now + offset
00254 
00255             options.append((
00256                 str(offset),
00257                 '%s [%s%s:%s]' % (
00258                     time.strftime(self.cfg.datetime_fmt, util.timefuncs.tmtuple(t)),
00259                     "+-"[offset < 0],
00260                     "%02d" % (abs(offset) / 3600),
00261                     "%02d" % (abs(offset) % 3600 / 60),
00262                 ),
00263             ))
00264 
00265         return util.web.makeSelection('tz_offset', options, str(tz), 1, False, enabled)
00266 

def MoinMoin.userprefs.UserPrefBase.allowed (   self) [inherited]
    Not all preferences are applicable to all users,
    this method is called to determine whether the
    title should be listed or not and whether
    submissions are accepted.

Reimplemented in MoinMoin.userprefs.notification.Settings, MoinMoin.userprefs.changepass.Settings, MoinMoin.userprefs.suid.Settings, and MoinMoin.userprefs.oidserv.Settings.

Definition at line 60 of file __init__.py.

00060 
00061     def allowed(self):
00062         '''
00063             Not all preferences are applicable to all users,
00064             this method is called to determine whether the
00065             title should be listed or not and whether
00066             submissions are accepted.
00067         '''
00068         return self.request.user and self.request.user.valid

Create the complete HTML form code. 

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 323 of file prefs.py.

00323 
00324     def create_form(self):
00325         """ Create the complete HTML form code. """
00326         _ = self._
00327         request = self.request
00328         self._form = self.make_form()
00329 
00330         if request.user.valid:
00331             buttons = [('save', _('Save')), ('cancel', _('Cancel')), ]
00332             uf_remove = self.cfg.user_form_remove
00333             uf_disable = self.cfg.user_form_disable
00334             for attr in request.user.auth_attribs:
00335                 uf_disable.append(attr)
00336             for key, label, type, length, textafter in self.cfg.user_form_fields:
00337                 default = self.cfg.user_form_defaults[key]
00338                 if not key in uf_remove:
00339                     if key in uf_disable:
00340                         self.make_row(_(label),
00341                                   [html.INPUT(type=type, size=length, name=key, disabled="disabled",
00342                                    value=getattr(request.user, key)), ' ', _(textafter), ])
00343                     else:
00344                         self.make_row(_(label),
00345                                   [html.INPUT(type=type, size=length, name=key, value=getattr(request.user, key)), ' ', _(textafter), ])
00346 
00347             if not self.cfg.theme_force and not "theme_name" in self.cfg.user_form_remove:
00348                 self.make_row(_('Preferred theme'), [self._theme_select()])
00349 
00350             if not self.cfg.editor_force:
00351                 if not "editor_default" in self.cfg.user_form_remove:
00352                     self.make_row(_('Editor Preference'), [self._editor_default_select()])
00353                 if not "editor_ui" in self.cfg.user_form_remove:
00354                     self.make_row(_('Editor shown on UI'), [self._editor_ui_select()])
00355 
00356             if not "tz_offset" in self.cfg.user_form_remove:
00357                 self.make_row(_('Time zone'), [
00358                     _('Your time is'), ' ',
00359                     self._tz_select(),
00360                     html.BR(),
00361                     _('Server time is'), ' ',
00362                     time.strftime(self.cfg.datetime_fmt, util.timefuncs.tmtuple()),
00363                     ' (UTC)',
00364                 ])
00365 
00366             if not "datetime_fmt" in self.cfg.user_form_remove:
00367                 self.make_row(_('Date format'), [self._dtfmt_select()])
00368 
00369             if not "language" in self.cfg.user_form_remove:
00370                 self.make_row(_('Preferred language'), [self._lang_select()])
00371 
00372             # boolean user options
00373             bool_options = []
00374             checkbox_fields = self.cfg.user_checkbox_fields
00375             checkbox_fields.sort(lambda a, b: cmp(a[1](_), b[1](_)))
00376             for key, label in checkbox_fields:
00377                 if not key in self.cfg.user_checkbox_remove:
00378                     bool_options.extend([
00379                         html.INPUT(type="checkbox", name=key, value="1",
00380                             checked=getattr(request.user, key, 0),
00381                             disabled=key in self.cfg.user_checkbox_disable and True or None),
00382                         ' ', label(_), html.BR(),
00383                     ])
00384             self.make_row(_('General options'), bool_options, valign="top")
00385 
00386             self.make_row(_('Quick links'), [
00387                 html.TEXTAREA(name="quicklinks", rows="6", cols="50")
00388                     .append('\n'.join(request.user.getQuickLinks())),
00389             ], valign="top")
00390 
00391             self._form.append(html.INPUT(type="hidden", name="action", value="userprefs"))
00392             self._form.append(html.INPUT(type="hidden", name="handler", value="prefs"))
00393 
00394         # Add buttons
00395         button_cell = []
00396         for name, label in buttons:
00397             if not name in self.cfg.user_form_remove:
00398                 button_cell.extend([
00399                     html.INPUT(type="submit", name=name, value=label),
00400                     ' ',
00401                 ])
00402         self.make_row('', button_cell)
00403 
00404         return unicode(self._form)
def MoinMoin.userprefs.UserPrefBase.handle_form (   self,
  request 
) [inherited]
    When any of the created forms is submitted and the
    hidden fields are set correctly (see create_form)
    this method will be invoked to handle the user's
    input. Note that GET requests are also handed to
    this method, so if you require POST check that.

Definition at line 50 of file __init__.py.

00050 
00051     def handle_form(self, request):
00052         '''
00053             When any of the created forms is submitted and the
00054             hidden fields are set correctly (see create_form)
00055             this method will be invoked to handle the user's
00056             input. Note that GET requests are also handed to
00057             this method, so if you require POST check that.
00058         '''
00059         raise NotImplementedError

Definition at line 223 of file prefs.py.

00223 
00224     def handle_form(self):
00225         _ = self._
00226         form = self.request.form
00227 
00228         if 'cancel' in form:
00229             return
00230 
00231         if 'save' in form: # Save user profile
00232             return self._save_user_prefs()

Here is the call graph for this function:

def MoinMoin.userprefs.UserPrefBase.make_form (   self,
  explanation = None 
) [inherited]
    To have a consistent UI, use this method for most
    preferences forms and then call make_row(). See
    existing plugins, e.g. changepass.py.

Definition at line 69 of file __init__.py.

00069 
00070     def make_form(self, explanation=None):
00071         '''
00072             To have a consistent UI, use this method for most
00073             preferences forms and then call make_row(). See
00074             existing plugins, e.g. changepass.py.
00075         '''
00076         action = self.request.page.url(self.request)
00077         _form = html.FORM(action=action)
00078         _form.append(html.INPUT(type="hidden", name="action", value="userprefs"))
00079         _form.append(html.INPUT(type="hidden", name="handler", value=self.name))
00080 
00081         self._table = html.TABLE(border="0")
00082 
00083         # Use the user interface language and direction
00084         lang_attr = self.request.theme.ui_lang_attr()
00085         _form.append(html.Raw('<div class="userpref"%s>' % lang_attr))
00086         para = html.P()
00087         _form.append(para)
00088         if explanation:
00089             para.append(explanation)
00090 
00091         para.append(self._table)
00092         _form.append(html.Raw("</div>"))
00093 
00094         return _form

Here is the caller graph for this function:

def MoinMoin.userprefs.UserPrefBase.make_row (   self,
  label,
  cell,
  kw 
) [inherited]
   Create a row in the form table.

Definition at line 95 of file __init__.py.

00095 
00096     def make_row(self, label, cell, **kw):
00097         '''
00098            Create a row in the form table.
00099         '''
00100         self._table.append(html.TR().extend([
00101             html.TD(**kw).extend([html.B().append(label), '   ']),
00102             html.TD().extend(cell),
00103         ]))

Here is the caller graph for this function:


Member Data Documentation

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 33 of file prefs.py.

Initial value:
{ # datetime_fmt & date_fmt
        'iso': '%Y-%m-%d %H:%M:%S & %Y-%m-%d',
        'us': '%m/%d/%Y %I:%M:%S %p & %m/%d/%Y',
        'euro': '%d.%m.%Y %H:%M:%S & %d.%m.%Y',
        'rfc': '%a %b %d %H:%M:%S %Y & %a %b %d %Y',
    }

Definition at line 235 of file prefs.py.

Definition at line 327 of file prefs.py.

Definition at line 34 of file prefs.py.

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 37 of file prefs.py.

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 32 of file prefs.py.

Reimplemented from MoinMoin.userprefs.UserPrefBase.

Definition at line 36 of file prefs.py.


The documentation for this class was generated from the following file: