Attachment 'IncludeUpcoming2-v0.3.py'

Download

   1 # -*- coding: iso-8859-1 -*-
   2 """
   3     MoinMoin - IncludeUpcoming2 macro
   4 
   5     This macro includes the formatted content of the given page(s). See
   6         http://moinmo.in/HelpOnMacros/Include
   7     for detailed docs.
   8     
   9     @copyright: 2000-2004 by Jürgen Hermann <jh@web.de>
  10     @copyright: 2000-2001 by Richard Jones <richard@bizarsoftware.com.au>
  11     @license: GNU GPL, see COPYING for details.
  12 
  13     This macro has been slightly modified for displaying upcoming events.
  14 
  15     Look for updates here:
  16         http://moinmo.in/MacroMarket/IncludeUpcoming
  17 
  18     History:
  19      * 05.03.2008: Version 0.2 (MarcelHäfner)
  20                    - fixed the "wikiutil.AbsPageName" call for MoinMoin 1.6.1 
  21 
  22      * 07.03.2008: Version 0.3 (MarcelHäfner)
  23                    - a few changes for my purpose
  24                    - removed the features for "levelstack" because it creates 
  25                      "wrong" nested html code. somebody may can fix and not 
  26                      just remove this, like i did.
  27                    - titleonly now use only one <dl> in the start and one 
  28                      </dl> in the end.
  29                    - while using titleonly it will add a div with css 
  30                      "include-title".
  31 """
  32 
  33 #Dependencies = ["pages"] # included page
  34 Dependencies = ["time"] # works around MoinMoinBugs/TableOfContentsLacksLinks
  35 
  36 import re, StringIO
  37 from MoinMoin import wikiutil
  38 from MoinMoin.Page import Page
  39 from MoinMoin.util import web
  40 
  41 _sysmsg = '<p><strong class="%s">%s</strong></p>'
  42 
  43 ## keep in sync with TableOfContents macro!
  44 _arg_heading = r'(?P<heading>,)\s*(|(?P<hquote>[\'"])(?P<htext>.+?)(?P=hquote))'
  45 _arg_level = r',\s*(?P<level>\d*)'
  46 _arg_from = r'(,\s*from=(?P<fquote>[\'"])(?P<from>.+?)(?P=fquote))?'
  47 _arg_to = r'(,\s*to=(?P<tquote>[\'"])(?P<to>.+?)(?P=tquote))?'
  48 _arg_sort = r'(,\s*sort=(?P<sort>(ascending|descending)))?'
  49 _arg_items = r'(,\s*items=(?P<items>\d+))?'
  50 _arg_skipitems = r'(,\s*skipitems=(?P<skipitems>\d+))?'
  51 _arg_titlesonly = r'(,\s*(?P<titlesonly>titlesonly))?'
  52 _arg_editlink = r'(,\s*(?P<editlink>editlink))?'
  53 _args_re_pattern = r'^(?P<name>[^,]+)(%s(%s)?%s%s%s%s%s%s%s)?$' % (
  54     _arg_heading, _arg_level, _arg_from, _arg_to, _arg_sort, _arg_items,
  55     _arg_skipitems, _arg_titlesonly, _arg_editlink)
  56 
  57 _title_re = r"^(?P<heading>\s*(?P<hmarker>=+)\s.*\s(?P=hmarker))$"
  58 
  59 def extract_titles(body, title_re):
  60     titles = []
  61     for title, _ in title_re.findall(body):
  62         h = title.strip()
  63         level = 1
  64         while h[level:level+1] == '=': level = level+1
  65         depth = min(5,level)
  66         title_text = h[level:-level].strip()
  67         titles.append((title_text, level))
  68     return titles
  69 
  70 def degrade_titles(body, level):
  71     rval = ""
  72     for linea in body.split('\n'):
  73         if len(linea) >=4:
  74             if linea[0]=="=" and linea[-1]=="=":
  75                 rval = rval + level*"=" + linea + level*"="
  76                 continue
  77         rval = rval + linea + '\n'
  78     return rval
  79 
  80 def execute(macro, text, args_re=re.compile(_args_re_pattern), title_re=re.compile(_title_re, re.M), called_by_toc=0):
  81     import datetime
  82     request = macro.request
  83     _ = request.getText
  84 
  85     # return immediately if getting links for the current page
  86     if request.mode_getpagelinks:
  87         return ''
  88 
  89     # parse and check arguments
  90     args = text and args_re.match(text)
  91     if not args:
  92         return (_sysmsg % ('error', _('Invalid include arguments "%s"!')) % (text,))
  93 
  94     # prepare including page
  95     result = []
  96     print_mode = macro.form.has_key('action') and macro.form['action'][0] in ("print", "format")
  97     this_page = macro.formatter.page
  98     if not hasattr(this_page, '_macroInclude_pagelist'):
  99         this_page._macroInclude_pagelist = {}
 100 
 101     # get list of pages to include
 102     inc_name = wikiutil.AbsPageName(this_page.page_name, args.group('name'))
 103 
 104     pagelist = [inc_name]
 105     todaystr = datetime.date.today()
 106     #inc_name = u"^%s/%4d-%02d-.." % (inc_name, todaystr.year, todaystr.month)
 107     inc_name = u"^%s/....-..-.." % inc_name
 108     if inc_name.startswith("^"):
 109         try:
 110             inc_match = re.compile(inc_name)
 111         except re.error:
 112             pass # treat as plain page name
 113         else:
 114             # Get user filtered readable page list
 115             pagelist = request.rootpage.getPageList(filter=inc_match.match)
 116             tmppglist = []
 117             todayint = (
 118                10000*int(todaystr.year)+
 119                  100*int(todaystr.month)+
 120                      int(todaystr.day)
 121             )
 122             for mypg in pagelist:
 123                pagedateint = (
 124                  10000*int(mypg[-10:-6])+
 125                    100*int(mypg[-5:-3])+
 126                        int(mypg[-2:])
 127                )
 128                if pagedateint >= todayint:
 129                  tmppglist.append(mypg)
 130             pagelist = tmppglist
 131 
 132     # sort and limit page list
 133     pagelist.sort()
 134     sort_dir = args.group('sort')
 135     if sort_dir == 'descending':
 136         pagelist.reverse()
 137     max_items = args.group('items')
 138     if max_items:
 139         pagelist = pagelist[:int(max_items)]
 140 
 141     skipitems = 0
 142     if args.group("skipitems"):
 143         skipitems = int(args.group("skipitems"))
 144     titlesonly = args.group('titlesonly')
 145     editlink = args.group('editlink')
 146 
 147     # need if you ojnly want one dl in your list
 148     if titlesonly:
 149         result.append(macro.formatter.div(1, css_class="include-title"))
 150         result.append(macro.formatter.definition_list(1))
 151 
 152     # iterate over pages
 153     for inc_name in pagelist:
 154         if not request.user.may.read(inc_name):
 155             continue
 156         if this_page._macroInclude_pagelist.has_key(inc_name):
 157             result.append(u'<p><strong class="error">Recursive include of "%s" forbidden</strong></p>' % (inc_name,))
 158             continue
 159         if skipitems:
 160             skipitems -= 1
 161             continue
 162         fmt = macro.formatter.__class__(request, is_included=True)
 163         fmt._base_depth = macro.formatter._base_depth
 164         inc_page = Page(request, inc_name, formatter=fmt)
 165         if not inc_page.exists():
 166             continue
 167         inc_page._macroInclude_pagelist = this_page._macroInclude_pagelist
 168 
 169         # check for "from" and "to" arguments (allowing partial includes)
 170         body = inc_page.get_raw_body() + '\n'
 171         from_pos = 0
 172         to_pos = -1
 173         from_re = args.group('from')
 174         if from_re:
 175             try:
 176                 from_match = re.compile(from_re, re.M).search(body)
 177             except re.error, e:
 178                 ##result.append("*** fe=%s ***" % e)
 179                 from_match = re.compile(re.escape(from_re), re.M).search(body)
 180             if from_match:
 181                 from_pos = from_match.end()
 182             else:
 183                 result.append(_sysmsg % ('warning', 'Include: ' + _('Nothing found for "%s"!')) % from_re)
 184         to_re = args.group('to')
 185         if to_re:
 186             try:
 187                 to_match = re.compile(to_re, re.M).search(body, from_pos)
 188             except re.error:
 189                 to_match = re.compile(re.escape(to_re), re.M).search(body, from_pos)
 190             if to_match:
 191                 to_pos = to_match.start()
 192             else:
 193                 result.append(_sysmsg % ('warning', 'Include: ' + _('Nothing found for "%s"!')) % to_re)
 194 
 195         if titlesonly:
 196             newbody = []
 197             for title, level in extract_titles(body[from_pos:to_pos], title_re):
 198                 result.append(macro.formatter.definition_term(1))
 199                 result.append(inc_name[-10:])
 200                 result.append(macro.formatter.definition_term(0))
 201                 result.append(macro.formatter.definition_desc(1))
 202                 result.append(inc_page.link_to(request, title))
 203                 result.append(macro.formatter.definition_desc(0))
 204             continue
 205 
 206         if from_pos or to_pos!=-1:
 207             thisbody = body[from_pos:to_pos]
 208             thisbody = degrade_titles(thisbody,2)
 209             inc_page.set_raw_body(thisbody, modified=True)
 210         ##result.append("*** f=%s t=%s ***" % (from_re, to_re))
 211         ##result.append("*** f=%d t=%d ***" % (from_pos, to_pos))
 212 
 213         if called_by_toc:
 214             result.append(inc_page.get_raw_body())
 215             continue
 216 
 217         if not hasattr(request, "_Include_backto"):
 218             request._Include_backto = this_page.page_name
 219 
 220         # do headings
 221         level = None
 222         if args.group('heading') and args.group('hquote'):
 223             heading = args.group('htext') or inc_page.split_title(request)
 224             level = 1
 225             if args.group('level'):
 226                 level = int(args.group('level'))
 227             if print_mode:
 228                 result.append(macro.formatter.heading(1, level) +
 229                               macro.formatter.text(heading) +
 230                               macro.formatter.heading(0, level))
 231             else:
 232                 import sha
 233                 from MoinMoin import config
 234                 # this heading id might produce duplicate ids,
 235                 # if the same page is included multiple times
 236                 # Encode stuf we feed into sha module.
 237                 pntt = (inc_name + heading).encode(config.charset)
 238                 hid = "head-" + sha.new(pntt).hexdigest()
 239                 request._page_headings.setdefault(pntt, 0)
 240                 request._page_headings[pntt] += 1
 241                 if request._page_headings[pntt] > 1:
 242                     hid += '-%d'%(request._page_headings[pntt],)
 243                 result.append(
 244                     #macro.formatter.heading(1, level, hid,
 245                     #    icons=edit_icon.replace('<img ', '<img align="right" ')) +
 246                     macro.formatter.heading(1, level, id=hid) +
 247                     inc_page.link_to(request, heading, css_class="include-heading-link") +
 248                     macro.formatter.heading(0, level)
 249                 )
 250 
 251         # set or increment include marker
 252         this_page._macroInclude_pagelist[inc_name] = \
 253             this_page._macroInclude_pagelist.get(inc_name, 0) + 1
 254 
 255         # output the included page
 256         strfile = StringIO.StringIO()
 257         request.redirect(strfile)
 258         try:
 259             cid = request.makeUniqueID("Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name))
 260             inc_page.send_page(request, content_only=1, content_id=cid,
 261                                omit_footnotes=True)
 262             result.append(macro.formatter.table(1,style='width: 100%'))
 263             result.append(macro.formatter.table_row(1,style='background-color: #ADB9CC'))
 264             result.append(macro.formatter.table_cell(1))
 265             result.append(inc_name[-10:])
 266             result.append(macro.formatter.table_cell(0))
 267             result.append(macro.formatter.table_row(0))
 268             result.append(macro.formatter.table_row(1, style='background-color: #ffeeee'))
 269             result.append(macro.formatter.table_cell(1))
 270             result.append(strfile.getvalue())
 271             result.append(macro.formatter.table_cell(0))
 272             result.append(macro.formatter.table_row(0))
 273             result.append(macro.formatter.table(0))
 274         finally:
 275             request.redirect()
 276 
 277         # decrement or remove include marker
 278         if this_page._macroInclude_pagelist[inc_name] > 1:
 279             this_page._macroInclude_pagelist[inc_name] = \
 280                 this_page._macroInclude_pagelist[inc_name] - 1
 281         else:
 282             del this_page._macroInclude_pagelist[inc_name]
 283 
 284         # if no heading and not in print mode, then output a helper link
 285         if editlink and not (level or print_mode):
 286             result.extend([
 287                 macro.formatter.div(1, css_class="include-link"),
 288                 inc_page.link_to(request, '[%s]' % (inc_name,), css_class="include-page-link"),
 289                 inc_page.link_to(request, '[%s]' % (_('edit'),), css_class="include-edit-link", querystr={'action': 'edit', 'backto': request._Include_backto}),
 290                 macro.formatter.div(0),
 291             ])
 292         # XXX page.link_to is wrong now, it escapes the edit_icon html as it escapes normal text
 293 
 294     # end tag for the dl
 295     if titlesonly:
 296         result.append(macro.formatter.definition_list(0))
 297         result.append(macro.formatter.div(0))
 298 
 299     # return include text
 300     return ''.join(result)

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2006-11-29 09:44:25, 10.7 KB) [[attachment:IncludeUpcoming-v0.0.py]]
  • [get | view] (2006-12-02 15:22:52, 11.9 KB) [[attachment:IncludeUpcoming-v0.1.py]]
  • [get | view] (2008-03-05 19:50:09, 12.0 KB) [[attachment:IncludeUpcoming-v0.2.py]]
  • [get | view] (2008-03-07 21:49:48, 12.0 KB) [[attachment:IncludeUpcoming2-v0.3.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.