aboutsummaryrefslogtreecommitdiffstats
path: root/bin/config_list
blob: caf4fc11d9783e17a2ad79d55895f5f91f63002c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#! @PYTHON@
#
# Copyright (C) 1998-2018 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.

"""Configure a list from a text file description.

Usage: config_list [options] listname

Options:
    --inputfile filename
    -i filename
        Configure the list by assigning each module-global variable in the
        file to an attribute on the list object, then saving the list.  The
        named file is loaded with execfile() and must be legal Python code.
        Any variable that isn't already an attribute of the list object is
        ignored (a warning message is printed).  See also the -c option.

        A special variable named `mlist' is put into the globals during the
        execfile, which is bound to the actual MailList object.  This lets you
        do all manner of bizarre thing to the list object, but BEWARE!  Using
        this can severely (and possibly irreparably) damage your mailing list!

    --outputfile filename
    -o filename
        Instead of configuring the list, print out a list's configuration
        variables in a format suitable for input using this script.  In this
        way, you can easily capture the configuration settings for a
        particular list and imprint those settings on another list.  filename
        is the file to output the settings to.  If filename is `-', standard
        out is used.

    --checkonly
    -c
        With this option, the modified list is not actually changed.  Only
        useful with -i.

    --verbose
    -v
        Print the name of each attribute as it is being changed.  Only useful
        with -i.

    --help
    -h
        Print this help message and exit.

The options -o and -i are mutually exclusive.

"""

import sys
import re
import time
import getopt
from types import TupleType

import paths
from Mailman import mm_cfg
from Mailman import MailList
from Mailman import Utils
from Mailman import Errors
from Mailman import i18n

_ = i18n._
C_ = i18n.C_

NL = '\n'
nonasciipat = re.compile(r'[\x80-\xff]')



def usage(code, msg=''):
    if code:
        fd = sys.stderr
    else:
        fd = sys.stdout
    print >> fd, C_(__doc__)
    if msg:
        print >> fd, msg
    sys.exit(code)



def do_output(listname, outfile):
    closep = 0
    try:
        if outfile == '-':
            outfp = sys.stdout
        else:
            outfp = open(outfile, 'w')
            closep = 1
        # Open the specified list unlocked, since we're only reading it.
        try:
            mlist = MailList.MailList(listname, lock=0)
        except Errors.MMListError:
            usage(1, C_('No such list: %(listname)s'))
        # Preamble for the config info. PEP263 charset and capture time.
        language = mlist.preferred_language
        charset = Utils.GetCharSet(language)
        i18n.set_language(language)
        if not charset:
            charset = 'us-ascii'
        when = time.ctime(time.time())
        print >> outfp, C_('''\
# -*- python -*-
# -*- coding: %(charset)s -*-
## "%(listname)s" mailing list configuration settings
## captured on %(when)s
''')
        # get all the list config info.  all this stuff is accessible via the
        # web interface
        for k in mm_cfg.ADMIN_CATEGORIES:
            subcats = mlist.GetConfigSubCategories(k)
            if subcats is None:
                do_list_categories(mlist, k, None, outfp)
            else:
                for subcat in [t[0] for t in subcats]:
                    do_list_categories(mlist, k, subcat, outfp)
    finally:
        if closep:
            outfp.close()


def do_list_categories(mlist, k, subcat, outfp):
    info = mlist.GetConfigInfo(k, subcat)
    label, gui = mlist.GetConfigCategories()[k]
    if info is None:
        return
    charset = Utils.GetCharSet(mlist.preferred_language)
    print >> outfp, '##', k.capitalize(), C_('options')
    print >> outfp, '#'
    # First, massage the descripton text, which could have obnoxious
    # leading whitespace on second and subsequent lines due to
    # triple-quoted string nonsense in the source code.
    desc = NL.join([s.lstrip() for s in info[0].split('\n')])
    # Print out the category description
    desc = Utils.wrap(desc)
    for line in desc.split('\n'):
        print >> outfp, '#', line
    print >> outfp
    for data in info[1:]:
        if not isinstance(data, TupleType):
            continue
        varname = data[0]
        # Variable could be volatile
        if varname[0] == '_':
            continue
        vtype = data[1]
        # First, massage the descripton text, which could have
        # obnoxious leading whitespace on second and subsequent lines
        # due to triple-quoted string nonsense in the source code.
        desc = NL.join([s.lstrip() for s in data[-1].split('\n')])
        # Now strip out all HTML tags
        desc = re.sub('<.*?>', '', desc)
        # And convert &lt;/&gt; to <>
        desc = re.sub('&lt;', '<', desc)
        desc = re.sub('&gt;', '>', desc)
        # Print out the variable description.
        desc = Utils.wrap(desc)
        for line in desc.split('\n'):
            print >> outfp, '#', line
        # munge the value based on its type
        value = None
        if hasattr(gui, 'getValue'):
            value = gui.getValue(mlist, vtype, varname, data[2])
        if value is None and not varname.startswith('_'):
            value = getattr(mlist, varname)
        if vtype in (mm_cfg.String, mm_cfg.Text, mm_cfg.FileUpload):
            print >> outfp, varname, '=',
            lines = value.splitlines()
            if not lines:
                print >> outfp, "''"
            elif len(lines) == 1:
                if charset <> 'us-ascii' and nonasciipat.search(lines[0]):
                    # This is more readable for non-english list.
                    print >> outfp, '"' + lines[0].replace('"', '\\"') + '"'
                else:
                    print >> outfp, repr(lines[0])
            else:
                if charset == 'us-ascii' and nonasciipat.search(value):
                    # Normally, an english list should not have non-ascii char.
                    print >> outfp, repr(NL.join(lines))
                else:
                    outfp.write(' """')
                    outfp.write(NL.join(lines).replace('"', '\\"'))
                    outfp.write('"""\n')
        elif vtype in (mm_cfg.Radio, mm_cfg.Toggle):
            print >> outfp, '#'
            print >> outfp, '#', C_('legal values are:')
            # TBD: This is disgusting, but it's special cased
            # everywhere else anyway...
            if varname == 'subscribe_policy' and \
                   not mm_cfg.ALLOW_OPEN_SUBSCRIBE:
                i = 1
            else:
                i = 0
            for choice in data[2]:
                print >> outfp, '#   ', i, '= "%s"' % choice
                i += 1
            print >> outfp, varname, '=', repr(value)
        else:
            print >> outfp, varname, '=', repr(value)
        print >> outfp



def getPropertyMap(mlist):
    guibyprop = {}
    categories = mlist.GetConfigCategories()
    for category, (label, gui) in categories.items():
        if not hasattr(gui, 'GetConfigInfo'):
            continue
        subcats = mlist.GetConfigSubCategories(category)
        if subcats is None:
            subcats = [(None, None)]
        for subcat, sclabel in subcats:
            for element in gui.GetConfigInfo(mlist, category, subcat):
                if not isinstance(element, TupleType):
                    continue
                propname = element[0]
                wtype = element[1]
                guibyprop[propname] = (gui, wtype)
    return guibyprop


class FakeDoc:
    # Fake the error reporting API for the htmlformat.Document class
    def addError(self, s, tag=None, *args):
        if tag:
            print >> sys.stderr, tag
        print >> sys.stderr, s % args

    def set_language(self, val):
        pass


def do_input(listname, infile, checkonly, verbose):
    fakedoc = FakeDoc()
    # open the specified list locked, unless checkonly is set
    try:
        mlist = MailList.MailList(listname, lock=not checkonly)
    except Errors.MMListError, e:
        usage(1, C_('No such list "%(listname)s"\n%(e)s'))
    savelist = 0
    guibyprop = getPropertyMap(mlist)
    try:
        globals = {'mlist': mlist}
        # Any exception that occurs in execfile() will cause the list to not
        # be saved, but any other problems are not save-fatal.
        execfile(infile, globals)
        savelist = 1
        for k, v in globals.items():
            if k in ('mlist', '__builtins__'):
                continue
            if not hasattr(mlist, k):
                print >> sys.stderr, C_('attribute "%(k)s" ignored')
                continue
            if verbose:
                print >> sys.stderr, C_('attribute "%(k)s" changed')
            missing = []
            gui, wtype = guibyprop.get(k, (missing, missing))
            if gui is missing:
                # This isn't an official property of the list, but that's
                # okay, we'll just restore it the old fashioned way
                print >> sys.stderr, C_(
                                     'Non-standard property restored: %(k)s')
                setattr(mlist, k, v)
            else:
                # BAW: This uses non-public methods.  This logic taken from
                # the guts of GUIBase.handleForm().
                try:
                    validval = gui._getValidValue(mlist, k, wtype, v)
                except ValueError:
                    print >> sys.stderr, C_(
                                         'Invalid value for property: %(k)s')
                except Errors.EmailAddressError:
                    print >> sys.stderr, C_(
                        'Bad email address for option %(k)s: %(v)s')
                else:
                    # BAW: Horrible hack, but then this is special cased
                    # everywhere anyway. :(  Privacy._setValue() knows that
                    # when ALLOW_OPEN_SUBSCRIBE is false, the web values are
                    # 0, 1, 2 but these really should be 1, 2, 3, so it adds
                    # one.  But we really do provide [0..3] so we need to undo
                    # the hack that _setValue adds. :( :(
                    if k == 'subscribe_policy' and \
                           not mm_cfg.ALLOW_OPEN_SUBSCRIBE:
                        validval -= 1
                    # BAW: Another horrible hack.  This one is just too hard
                    # to fix in a principled way in Mailman 2.1
                    elif k == 'new_member_options':
                        # Because this is a Checkbox, _getValidValue()
                        # transforms the value into a list of one item.
                        validval = validval[0]
                        validval = [bitfield for bitfield, bitval
                                    in mm_cfg.OPTINFO.items()
                                    if validval & bitval]
                    gui._setValue(mlist, k, validval, fakedoc)
            # BAW: when to do gui._postValidate()???
    finally:
        if savelist and not checkonly:
            mlist.Save()
        mlist.Unlock()



def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], 'ci:o:vh',
            ['checkonly', 'inputfile=', 'outputfile=', 'verbose', 'help'])
    except getopt.error, msg:
        usage(1, msg)

    # defaults
    infile = None
    outfile = None
    checkonly = 0
    verbose = 0
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-o', '--outputfile'):
            outfile = arg
        elif opt in ('-i', '--inputfile'):
            infile = arg
        elif opt in ('-c', '--checkonly'):
            checkonly = 1
        elif opt in ('-v', '--verbose'):
            verbose = 1

    # sanity check
    if infile is not None and outfile is not None:
        usage(1, C_('Only one of -i or -o is allowed'))
    if infile is None and outfile is None:
        usage(1, C_('One of -i or -o is required'))

    # get the list name
    if len(args) <> 1:
        usage(1, C_('List name is required'))
    listname = args[0].lower().strip()

    if outfile:
        do_output(listname, outfile)
    else:
        do_input(listname, infile, checkonly, verbose)



if __name__ == '__main__':
    main()