示例#1
0
def getNames(cfg):
    if not hasattr(cfg.cache, "macro_names"):
        lnames = names[:]
        lnames.extend(i18n.wikiLanguages().keys())
        lnames.extend(wikiutil.getPlugins("macro", cfg))
        cfg.cache.macro_names = lnames  # remember it
    return cfg.cache.macro_names
示例#2
0
    def mainloop(self):
        self.init_request()
        request = self.request

        from_address = unicode(self.options.from_address or "*****@*****.**")
        subject = unicode(self.options.subject or "MoinMoin i18n notification")
        text_template = unicode(sys.stdin.read())

        languages = i18n.wikiLanguages()
        langs = languages.keys()
        langs.remove('en')  # nothing to do for english, so remove it
        #langs = ['de', ] # for testing

        if len(text_template) > 10:  # do not send mails w/o real content
            for lang in langs:
                to_address = languages[lang]['last-translator']
                rc = None
                if to_address and '***vacant***' not in to_address:
                    text = text_template % locals()
                    rc = sendmail(request, [to_address],
                                  subject,
                                  text,
                                  mail_from=from_address)
                    print lang, repr(from_address), repr(
                        to_address), subject, repr(rc)
示例#3
0
def getNames(cfg):
    if not hasattr(cfg.cache, 'macro_names'):
        lnames = names[:]
        lnames.extend(i18n.wikiLanguages().keys())
        lnames.extend(wikiutil.getPlugins('macro', cfg))
        cfg.cache.macro_names = lnames  # remember it
    return cfg.cache.macro_names
示例#4
0
    def buildPageSets(self):
        """ Calculates which pages should go into which package. """
        request = self.request

        all_pages = set(request.rootpage.getPageList())
        packaged_pages = set()

        languages = i18n.wikiLanguages()
        pageset_names = i18n.strings.pagesets
        pageSets = {}
        for lang in languages:
            def trans(text, request=request, lang=lang, **kw):
                return i18n.getText(text, request, lang, **kw)

            try:
                lang_long = languages[lang]['x-language-in-english']
                lang_long = lang_long.replace('/', '_').replace(' ', '_')
            except KeyError:
                lang_long = lang

            for pageset_name in pageset_names:
                pageset_orig = set(getattr(i18n.strings, pageset_name))
                pageset_trans = set([trans(pn) for pn in pageset_orig])
                key = u"%s--%s" % (lang_long, pageset_name)
                pageset = pageset_trans
                if lang != 'en':
                    pageset -= pageset_orig
                if pageset:
                    print key, len(pageset)
                    pageSets[key] = pageset
                    packaged_pages |= pageset

        not_packaged_pages = all_pages - packaged_pages
        pageSets['00_needs_fixing'] = not_packaged_pages
        return pageSets
示例#5
0
    def execute(self, macro_name, args):
        """ Get and execute a macro

        Try to get a plugin macro, or a builtin macro or a language
        macro, or just raise ImportError.
        """
        self.name = macro_name
        try:
            str(macro_name)
        except UnicodeEncodeError:
            _ = self._
            return self.formatter.text(
                _('<<%(macro_name)s: invalid macro name>>') % {
                    'macro_name': macro_name,
                })
        try:
            call = wikiutil.importPlugin(self.cfg,
                                         'macro',
                                         macro_name,
                                         function='macro_%s' % macro_name)
            execute = lambda _self, _args: wikiutil.invoke_extension_function(
                _self.request, call, _args, [_self])
        except wikiutil.PluginAttributeError:
            # fall back to old execute() method, no longer recommended
            execute = wikiutil.importPlugin(self.cfg, 'macro', macro_name)
        except wikiutil.PluginMissingError:
            try:
                call = getattr(self, 'macro_%s' % macro_name)
                execute = lambda _self, _args: wikiutil.invoke_extension_function(
                    _self.request, call, _args, [])
            except AttributeError:
                if macro_name in i18n.wikiLanguages():
                    execute = self.__class__._m_lang
                else:
                    raise ImportError("Cannot load macro %s" % macro_name)
        try:
            return execute(self, args)
        except Exception, err:
            # we do not want that a faulty macro aborts rendering of the page
            # and makes the wiki UI unusable (by emitting a Server Error),
            # thus, in case of exceptions, we just log the problem and return
            # some standard text.
            try:
                page_spec = " (page: '%s')" % self.formatter.page.page_name
            except:
                page_spec = ""
            logging.exception("Macro %s%s raised an exception:" %
                              (self.name, page_spec))
            _ = self.request.getText
            return self.formatter.text(
                _('<<%(macro_name)s: execution failed [%(error_msg)s] (see also the log)>>'
                  ) %
                {
                    'macro_name': self.name,
                    'error_msg': err.args[
                        0],  # note: str(err) or unicode(err) does not work for py2.4/5/6
                })
            import traceback
            logging.info("Stack:\n" + traceback.format_stack())
示例#6
0
def used_languages(request):
    from MoinMoin.util.dataset import TupleDataset, Column
    from MoinMoin.widget.browser import DataBrowserWidget

    _ = request.getText

    data = get_data(request)

    total = 0.0
    for cnt, lang in data:
        total += cnt

    languages = TupleDataset()
    languages.columns = [
        Column('language', label=_("Language"), align='left'),
        Column('value', label='%', align='right')
    ]

    cnt_printed = 0
    data = data[:10]

    # Preparing "<Browser setting>"
    browserlang = _('<Browser setting>')
    browserlang = browserlang[1:len(browserlang) - 1].capitalize()
    if total:
        for cnt, lang in data:
            try:
                if lang == u'browser':
                    languages.addRow(
                        (browserlang, "%(percent).2f%% (%(count)d)" % {
                            'percent': 100.0 * cnt / total,
                            'count': cnt
                        }))
                else:
                    lang = i18n.wikiLanguages()[lang]['x-language-in-english']
                    languages.addRow((lang, "%(percent).2f%% (%(count)d)" % {
                        'percent': 100.0 * cnt / total,
                        'count': cnt
                    }))
                cnt_printed += cnt
            except UnicodeError:
                pass
        if total > cnt_printed:
            languages.addRow((_('Others'), "%(percent).2f%% (%(count)d)" % {
                'percent': 100.0 * (total - cnt_printed) / total,
                'count': total - cnt_printed
            }))

    else:  # If we don't have any users, we can safely assume that the only real user is the visitor (who is normally ignored, though) who is using "Browser setting"
        languages.addRow((browserlang, "100% (1)"))

    table = DataBrowserWidget(request)
    table.setData(languages)
    return table.render(method="GET")
示例#7
0
文件: prefs.py 项目: steveyen/moingo
    def _lang_select(self):
        """ Create language selection. """
        from MoinMoin import i18n
        _ = self._
        cur_lang = self.request.user.valid and self.request.user.language or ''
        langs = i18n.wikiLanguages().items()
        langs.sort(lambda x, y: cmp(x[1]['x-language'], y[1]['x-language']))
        options = [('', _('<Browser setting>'))]
        for lang in langs:
            name = lang[1]['x-language']
            options.append((lang[0], name))

        return util.web.makeSelection('language', options, cur_lang)
示例#8
0
    def _lang_select(self, enabled=True):
        """ Create language selection. """
        from MoinMoin import i18n
        _ = self._
        cur_lang = self.request.user.valid and self.request.user.language or ''
        langs = i18n.wikiLanguages().items()
        langs.sort(lambda x, y: cmp(x[1]['x-language'], y[1]['x-language']))
        options = [('', _('<Browser setting>'))]
        for lang in langs:
            name = lang[1]['x-language']
            options.append((lang[0], name))

        return util.web.makeSelection('language', options, cur_lang, 1, False, enabled)
示例#9
0
    def execute(self, macro_name, args):
        """ Get and execute a macro

        Try to get a plugin macro, or a builtin macro or a language
        macro, or just raise ImportError.
        """
        self.name = macro_name
        try:
            str(macro_name)
        except UnicodeEncodeError:
            _ = self._
            return self.formatter.text(_("<<%(macro_name)s: invalid macro name>>") % {"macro_name": macro_name})
        try:
            call = wikiutil.importPlugin(self.cfg, "macro", macro_name, function="macro_%s" % macro_name)
            execute = lambda _self, _args: wikiutil.invoke_extension_function(_self.request, call, _args, [_self])
        except wikiutil.PluginAttributeError:
            # fall back to old execute() method, no longer recommended
            execute = wikiutil.importPlugin(self.cfg, "macro", macro_name)
        except wikiutil.PluginMissingError:
            try:
                call = getattr(self, "macro_%s" % macro_name)
                execute = lambda _self, _args: wikiutil.invoke_extension_function(_self.request, call, _args, [])
            except AttributeError:
                if macro_name in i18n.wikiLanguages():
                    execute = self.__class__._m_lang
                else:
                    raise ImportError("Cannot load macro %s" % macro_name)
        try:
            return execute(self, args)
        except Exception, err:
            # we do not want that a faulty macro aborts rendering of the page
            # and makes the wiki UI unusable (by emitting a Server Error),
            # thus, in case of exceptions, we just log the problem and return
            # some standard text.
            try:
                page_spec = " (page: '%s')" % self.formatter.page.page_name
            except:
                page_spec = ""
            logging.exception("Macro %s%s raised an exception:" % (self.name, page_spec))
            _ = self.request.getText
            return self.formatter.text(
                _("<<%(macro_name)s: execution failed [%(error_msg)s] (see also the log)>>")
                % {
                    "macro_name": self.name,
                    "error_msg": err.args[0],  # note: str(err) or unicode(err) does not work for py2.4/5/6
                }
            )
            import traceback

            logging.info("Stack:\n" + traceback.format_stack())
示例#10
0
def _openidrp_sreg_extract_values(info):
    # Pull SREG data here instead of asking user
    sreg_resp = SRegResponse.fromSuccessResponse(info)
    sreg = {
        'nickname': '',
        'email': '',
        'fullname': '',
        'dob': '0000-00-00',
        'gender': '',
        'postcode': '',
        'country': '',
        'language': '',
        'timezone': ''
    }
    if sreg_resp:
        if sreg_resp.get('nickname'):
            sreg['nickname'] = sreg_resp.get('nickname')
        if sreg_resp.get('fullname'):
            sreg['fullname'] = sreg_resp.get('fullname')
        if sreg_resp.get('email'):
            sreg['email'] = sreg_resp.get('email')
        # Language must be a valid value
        # check the MoinMoin list, or restrict to first 2 chars
        if sreg_resp.get('language'):
            # convert unknown codes to 2 char format
            langs = i18n.wikiLanguages().items()
            sreg['language'] = sreg_resp.get('language')
            lang_found = False
            for lang in langs:
                if lang[0] == sreg['language']:
                    lang_found = True
            if not lang_found:
                if langs[sreg['language'][0:2]]:
                    sreg['language'] = sreg['language'][0:2]
        # Timezone must be converted to offset in seconds
        if sreg_resp.get('timezone'):
            try:
                user_tz = timezone(sreg_resp.get('timezone').encode('ascii'))
            except pytz.UnknownTimeZoneError:
                pass  # don't use
            else:
                if user_tz:
                    user_utcoffset = user_tz.utcoffset(datetime.utcnow())
                    sreg[
                        'timezone'] = user_utcoffset.days * 24 * 60 * 60 + user_utcoffset.seconds
                else:
                    # XXX when does user_tz get falsy? if it does, shouldn't we just 'pass'?
                    sreg['timezone'] = 0
    return sreg
示例#11
0
def used_languages(request):
    from MoinMoin.util.dataset import TupleDataset, Column
    from MoinMoin.widget.browser import DataBrowserWidget

    _ = request.getText

    data = get_data(request)

    total = 0.0
    for cnt, lang in data:
        total += cnt


    languages = TupleDataset()
    languages.columns = [Column('language', label=_("Language"), align='left'),
                         Column('value', label='%', align='right')]

    cnt_printed = 0
    data = data[:10]

    # Preparing "<Browser setting>"
    browserlang = _('<Browser setting>')
    browserlang = browserlang[1:len(browserlang) - 1].capitalize()
    if total:
        for cnt, lang in data:
            try:
                if lang == u'browser':
                    languages.addRow((browserlang, "%(percent).2f%% (%(count)d)" % {
                        'percent': 100.0 * cnt / total,
                        'count': cnt}))
                else:
                    lang = i18n.wikiLanguages()[lang]['x-language-in-english']
                    languages.addRow((lang, "%(percent).2f%% (%(count)d)" % {
                        'percent': 100.0 * cnt / total,
                        'count': cnt}))
                cnt_printed += cnt
            except UnicodeError:
                pass
        if total > cnt_printed:
            languages.addRow((_('Others'), "%(percent).2f%% (%(count)d)" % {
                'percent': 100.0 * (total - cnt_printed) / total,
                'count': total - cnt_printed}))

    else: # If we don't have any users, we can safely assume that the only real user is the visitor (who is normally ignored, though) who is using "Browser setting"
        languages.addRow((browserlang, "100% (1)"))

    table = DataBrowserWidget(request)
    table.setData(languages)
    return table.render(method="GET")
示例#12
0
    def __init__(self, parser):
        self.parser = parser
        #self.form --> gone, please use self.request.{form,args,values}
        self.request = self.parser.request
        self.formatter = self.request.formatter
        self._ = self.request.getText
        self.cfg = self.request.cfg

        # Initialized on execute
        self.name = None

        # we need the lang macros to execute when html is generated,
        # to have correct dir and lang html attributes
        # note: i18n needs to be initialized first before .wikiLanguages() will work
        for lang in i18n.wikiLanguages():
            self.Dependencies[lang] = []
示例#13
0
    def __init__(self, parser):
        self.parser = parser
        # self.form --> gone, please use self.request.{form,args,values}
        self.request = self.parser.request
        self.formatter = self.request.formatter
        self._ = self.request.getText
        self.cfg = self.request.cfg

        # Initialized on execute
        self.name = None

        # we need the lang macros to execute when html is generated,
        # to have correct dir and lang html attributes
        # note: i18n needs to be initialized first before .wikiLanguages() will work
        for lang in i18n.wikiLanguages():
            self.Dependencies[lang] = []
示例#14
0
    def mainloop(self):
        self.init_request()
        request = self.request

        # clean page scope cache entries
        keys = [
            'text_html',
            'pagelinks',
            'hitcounts',
        ]
        pages = request.rootpage.getPageList(user='')
        for pagename in pages:
            arena = Page(request, pagename)
            for key in keys:
                caching.CacheEntry(request, arena, key, scope='item').remove()

        # clean wiki scope cache entries
        arena_key_list = [
            ('charts', 'hitcounts'),
            ('charts', 'pagehits'),
            ('charts', 'useragents'),
        ]
        for arena, key in arena_key_list:
            caching.CacheEntry(request, arena, key, scope='wiki').remove()

        # clean dict and groups related cache
        arena_scope_list = [
            ('pagedicts', 'wiki'),
            ('pagegroups', 'wiki'),
            ('users', 'userdir'),
        ]
        for arena, scope in arena_scope_list:
            for key in caching.get_cache_list(request, arena, scope):
                caching.CacheEntry(request, arena, key, scope=scope).remove()

        # clean drafts of users
        uids = user.getUserList(request)
        for key in uids:
            caching.CacheEntry(request, 'drafts', key, scope='wiki').remove()

        # clean language cache files
        caching.CacheEntry(request, 'i18n', 'meta', scope='wiki').remove()
        wiki_languages = i18n.wikiLanguages().keys()
        for key in wiki_languages:
            caching.CacheEntry(request, 'i18n', key, scope='wiki').remove()
示例#15
0
    def mainloop(self):
        self.init_request()
        request = self.request

        from_address = unicode(self.options.from_address or "*****@*****.**")
        subject = unicode(self.options.subject or "MoinMoin i18n notification")
        text_template = unicode(sys.stdin.read())

        languages = i18n.wikiLanguages()
        langs = languages.keys()
        langs.remove('en') # nothing to do for english, so remove it
        #langs = ['de', ] # for testing

        if len(text_template) > 10: # do not send mails w/o real content
            for lang in langs:
                to_address = languages[lang]['last-translator']
                rc = None
                if to_address and '***vacant***' not in to_address:
                    text = text_template % locals()
                    rc = sendmail(request, [to_address], subject, text, mail_from=from_address)
                    print lang, repr(from_address), repr(to_address), subject, repr(rc)
def _openidrp_sreg_extract_values(info):
    # Pull SREG data here instead of asking user
    sreg_resp = SRegResponse.fromSuccessResponse(info)
    sreg = {'nickname': '', 'email': '', 'fullname': '',
            'dob': '0000-00-00', 'gender': '', 'postcode': '',
            'country': '', 'language': '', 'timezone': ''}
    if sreg_resp:
        if sreg_resp.get('nickname'):
            sreg['nickname'] = sreg_resp.get('nickname')
        if sreg_resp.get('fullname'):
            sreg['fullname'] = sreg_resp.get('fullname')
        if sreg_resp.get('email'):
            sreg['email'] = sreg_resp.get('email')
        # Language must be a valid value
        # check the MoinMoin list, or restrict to first 2 chars
        if sreg_resp.get('language'):
            # convert unknown codes to 2 char format
            langs = i18n.wikiLanguages().items()
            sreg['language'] = sreg_resp.get('language')
            lang_found = False
            for lang in langs:
                if lang[0] == sreg['language']:
                    lang_found = True
            if not lang_found:
                if langs[sreg['language'][0:2]]:
                    sreg['language'] = sreg['language'][0:2]
        # Timezone must be converted to offset in seconds
        if sreg_resp.get('timezone'):
            try:
                user_tz = timezone(sreg_resp.get('timezone').encode('ascii'))
            except pytz.UnknownTimeZoneError:
                pass # don't use
            else:
                if user_tz:
                    user_utcoffset = user_tz.utcoffset(datetime.utcnow())
                    sreg['timezone'] = user_utcoffset.days * 24 * 60 * 60 + user_utcoffset.seconds
                else:
                    # XXX when does user_tz get falsy? if it does, shouldn't we just 'pass'?
                    sreg['timezone'] = 0
    return sreg
示例#17
0
    def mainloop(self):
        self.init_request()
        request = self.request

        # clean page scope cache entries
        keys = ['text_html', 'pagelinks', 'hitcounts', ]
        pages = request.rootpage.getPageList(user='')
        for pagename in pages:
            arena = Page(request, pagename)
            for key in keys:
                caching.CacheEntry(request, arena, key, scope='item').remove()

        # clean wiki scope cache entries
        arena_key_list = [
            ('charts', 'hitcounts'),
            ('charts', 'pagehits'),
            ('charts', 'useragents'),
            ('user', 'name2id'),
        ]
        for arena, key in arena_key_list:
            caching.CacheEntry(request, arena, key, scope='wiki').remove()

        # clean dict and groups related cache
        arena_scope_list =  [('pagedicts', 'wiki'),
                             ('pagegroups', 'wiki'),
        ]
        for arena, scope in arena_scope_list:
            for key in caching.get_cache_list(request, arena, scope):
                caching.CacheEntry(request, arena, key, scope=scope).remove()

        # clean drafts of users
        uids = user.getUserList(request)
        for key in uids:
            caching.CacheEntry(request, 'drafts', key, scope='wiki').remove()

        # clean language cache files
        caching.CacheEntry(request, 'i18n', 'meta', scope='wiki').remove()
        wiki_languages = i18n.wikiLanguages().keys()
        for key in wiki_languages:
            caching.CacheEntry(request, 'i18n', key, scope='wiki').remove()
示例#18
0
    def mainloop(self):
        self.init_request()
        request = self.request

        # clean page scope cache entries
        keys = ["text_html", "pagelinks", "hitcounts"]
        pages = request.rootpage.getPageList(user="")
        for pagename in pages:
            arena = Page(request, pagename)
            for key in keys:
                caching.CacheEntry(request, arena, key, scope="item").remove()

        # clean wiki scope cache entries
        arena_key_list = [
            ("charts", "hitcounts"),
            ("charts", "pagehits"),
            ("charts", "useragents"),
            ("user", "name2id"),
        ]
        for arena, key in arena_key_list:
            caching.CacheEntry(request, arena, key, scope="wiki").remove()

        # clean dict and groups related cache
        arena_scope_list = [("pagedicts", "wiki"), ("pagegroups", "wiki")]
        for arena, scope in arena_scope_list:
            for key in caching.get_cache_list(request, arena, scope):
                caching.CacheEntry(request, arena, key, scope=scope).remove()

        # clean drafts of users
        uids = user.getUserList(request)
        for key in uids:
            caching.CacheEntry(request, "drafts", key, scope="wiki").remove()

        # clean language cache files
        caching.CacheEntry(request, "i18n", "meta", scope="wiki").remove()
        wiki_languages = i18n.wikiLanguages().keys()
        for key in wiki_languages:
            caching.CacheEntry(request, "i18n", key, scope="wiki").remove()
示例#19
0
    def execute(self, macro_name, args):
        """ Get and execute a macro

        Try to get a plugin macro, or a builtin macro or a language
        macro, or just raise ImportError.
        """
        self.name = macro_name
        try:
            call = wikiutil.importPlugin(self.cfg, 'macro', macro_name,
                                         function='macro_%s' % macro_name)
            execute = lambda _self, _args: _self._wrap(call, _args, [self])
        except wikiutil.PluginAttributeError:
            # fall back to old execute() method, no longer recommended
            execute = wikiutil.importPlugin(self.cfg, 'macro', macro_name)
        except wikiutil.PluginMissingError:
            try:
                call = getattr(self, 'macro_%s' % macro_name)
                execute = lambda _self, _args: _self._wrap(call, _args)
            except AttributeError:
                if macro_name in i18n.wikiLanguages():
                    execute = self.__class__._m_lang
                else:
                    raise ImportError("Cannot load macro %s" % macro_name)
        return execute(self, args)
示例#20
0
    def buildPageSets(self):
        """ Calculates which pages should go into which package. """
        request = self.request

        all_pages = set(request.rootpage.getPageList())
        packaged_pages = set()

        languages = i18n.wikiLanguages()
        pageset_names = i18n.strings.pagesets
        pageSets = {}
        for lang in languages:

            def trans(text, request=request, lang=lang, **kw):
                return i18n.getText(text, request, lang, **kw)

            try:
                lang_long = languages[lang]['x-language-in-english']
                lang_long = lang_long.replace('/', '_').replace(' ', '_')
            except KeyError:
                lang_long = lang

            for pageset_name in pageset_names:
                pageset_orig = set(getattr(i18n.strings, pageset_name))
                pageset_trans = set([trans(pn) for pn in pageset_orig])
                key = u"%s--%s" % (lang_long, pageset_name)
                pageset = pageset_trans
                if lang != 'en':
                    pageset -= pageset_orig
                if pageset:
                    print key, len(pageset)
                    pageSets[key] = pageset
                    packaged_pages |= pageset

        not_packaged_pages = all_pages - packaged_pages
        pageSets['00_needs_fixing'] = not_packaged_pages
        return pageSets
示例#21
0
    You can run the script multiple times if needed.

@copyright: 2004 Nir Soffer <nirs AT freeshell DOT org>
@license: GPL, see COPYING for details
"""

import codecs
import os, sys

# Insert THIS moin dir first into sys path, or you would run another
# version of moin!
sys.path.insert(0, '../..')

from MoinMoin import i18n
valid_languages = i18n.wikiLanguages()


def listdir(path):
    """ Return list of files in path, filtering certain files """
    names = [
        name for name in os.listdir(path) if not name.startswith('.')
        and not name.endswith('.pickle') and name != 'CVS'
    ]
    return names


def repairText(text):
    """ Repair page text

    We change only this type of lines that currently are in moinmaster
示例#22
0
文件: user.py 项目: liugehao/wiki
    def __init__(self, request, id=None, name="", password=None, auth_username="", **kw):
        """ Initialize User object

        TODO: when this gets refactored, use "uid" not builtin "id"

        @param request: the request object
        @param id: (optional) user ID
        @param name: (optional) user name
        @param password: (optional) user password (unicode)
        @param auth_username: (optional) already authenticated user name
                              (e.g. when using http basic auth) (unicode)
        @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
                               changeable by preferences, default: ().
                               First tuple element was used for authentication.
        """
        self._cfg = request.cfg
        self.valid = 0
        self.id = id
        self.auth_username = auth_username
        self.auth_method = kw.get('auth_method', 'internal')
        self.auth_attribs = kw.get('auth_attribs', ())
        self.bookmarks = {} # interwikiname: bookmark

        # create some vars automatically
        self.__dict__.update(self._cfg.user_form_defaults)

        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.recoverpass_key = ""

        if password:
            self.enc_password = encodePassword(self._cfg, password)

        #self.edit_cols = 80
        self.tz_offset = int(float(self._cfg.tz_offset) * 3600)
        self.language = ""
        self.real_language = "" # In case user uses "Browser setting". For language-statistics
        self._stored = False
        self.date_fmt = ""
        self.datetime_fmt = ""
        self.quicklinks = self._cfg.quicklinks_default
        self.subscribed_pages = self._cfg.subscribed_pages_default
        self.email_subscribed_events = self._cfg.email_subscribed_events_default
        self.jabber_subscribed_events = self._cfg.jabber_subscribed_events_default
        self.theme_name = self._cfg.theme_default
        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

        # we got an already authenticated username:
        check_password = None
        if not self.id and self.auth_username:
            self.id = getUserId(request, self.auth_username)
            if not password is None:
                check_password = password
        if self.id:
            self.load_from_id(check_password)
        elif self.name:
            self.id = getUserId(self._request, self.name)
            if self.id:
                # no password given should fail
                self.load_from_id(password or u'')
        # Still no ID - make new user
        if not self.id:
            self.id = self.make_id()
            if password is not None:
                self.enc_password = encodePassword(self._cfg, password)

        # "may" so we can say "if user.may.read(pagename):"
        if self._cfg.SecurityPolicy:
            self.may = self._cfg.SecurityPolicy(self)
        else:
            from MoinMoin.security import Default
            self.may = Default(self)

        if self.language and not self.language in i18n.wikiLanguages():
            self.language = 'en'
示例#23
0
文件: user.py 项目: aahlad/soar
    def __init__(self,
                 request,
                 id=None,
                 name="",
                 password=None,
                 auth_username="",
                 **kw):
        """ Initialize User object

        TODO: when this gets refactored, use "uid" not builtin "id"

        @param request: the request object
        @param id: (optional) user ID
        @param name: (optional) user name
        @param password: (optional) user password (unicode)
        @param auth_username: (optional) already authenticated user name
                              (e.g. when using http basic auth) (unicode)
        @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
                               changeable by preferences, default: ().
                               First tuple element was used for authentication.
        """
        self._cfg = request.cfg
        self.valid = 0
        self.id = id
        self.auth_username = auth_username
        self.auth_method = kw.get('auth_method', 'internal')
        self.auth_attribs = kw.get('auth_attribs', ())
        self.bookmarks = {}  # interwikiname: bookmark

        # create some vars automatically
        self.__dict__.update(self._cfg.user_form_defaults)

        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.recoverpass_key = ""

        if password:
            self.enc_password = encodePassword(password)

        #self.edit_cols = 80
        self.tz_offset = int(float(self._cfg.tz_offset) * 3600)
        self.language = ""
        self.real_language = ""  # In case user uses "Browser setting". For language-statistics
        self._stored = False
        self.date_fmt = ""
        self.datetime_fmt = ""
        self.quicklinks = self._cfg.quicklinks_default
        self.subscribed_pages = self._cfg.subscribed_pages_default
        self.email_subscribed_events = self._cfg.email_subscribed_events_default
        self.jabber_subscribed_events = self._cfg.jabber_subscribed_events_default
        self.theme_name = self._cfg.theme_default
        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

        # we got an already authenticated username:
        check_password = None
        if not self.id and self.auth_username:
            self.id = getUserId(request, self.auth_username)
            if not password is None:
                check_password = password
        if self.id:
            self.load_from_id(check_password)
        elif self.name:
            self.id = getUserId(self._request, self.name)
            if self.id:
                # no password given should fail
                self.load_from_id(password or u'')
        # Still no ID - make new user
        if not self.id:
            self.id = self.make_id()
            if password is not None:
                self.enc_password = encodePassword(password)

        # "may" so we can say "if user.may.read(pagename):"
        if self._cfg.SecurityPolicy:
            self.may = self._cfg.SecurityPolicy(self)
        else:
            from MoinMoin.security import Default
            self.may = Default(self)

        if self.language and not self.language in i18n.wikiLanguages():
            self.language = 'en'
示例#24
0
    You can run the script multiple times if needed.

@copyright: 2004 Nir Soffer <nirs AT freeshell DOT org>
@license: GPL, see COPYING for details
"""

import codecs
import os, sys

# Insert THIS moin dir first into sys path, or you would run another
# version of moin!
sys.path.insert(0, '../..')

from MoinMoin import i18n
valid_languages = i18n.wikiLanguages()


def listdir(path):
    """ Return list of files in path, filtering certain files """
    names = [name for name in os.listdir(path)
             if not name.startswith('.') and
             not name.endswith('.pickle') and
             name != 'CVS']
    return names


def repairText(text):
    """ Repair page text

    We change only this type of lines that currently are in moinmaster