Attachment 'EventCalendar-090.py'

Download

   1 """
   2     EventCalendar.py  Version 0.90  2005. 11. 15.
   3                                                                                                            
   4     This macro gives a list of the events recorded in the sub-pages in the form of monthly view and list view.
   5                                                                                                            
   6     @copyright: 2005 by Seungik Lee <seungiklee<at>gmail.com>  http://cds.icu.ac.kr/~silee/
   7     @license: GPL
   8 
   9     For more information, please visit http://moinmoin.wikiwikiweb.de/MacroMarket/EventCalendar
  10 
  11     Usage: 
  12         To list the events in a page, just insert [[EventCalendar]]
  13         To insert an event, enclose the information about the event with 'eventcal' in the page or its subpages.
  14         
  15             E.g., 
  16                 {{{#!eventcal
  17                     = [Title] =
  18                     [Start Date] ... [End Date]
  19                     [Start Time] ... [End Time]
  20                 }}}
  21             
  22             [Title] should be enclosed with heading marker ('='), double quatation mark ("), wiki italic or bold ('', ''')
  23                 Title can be omitted and it will be titled as 'No Title'
  24                 e.g., == Title ==, === Title ===, "Title", ''Title'', '''Title'''
  25             
  26             [Start|End Date] should be in YYYY/MM/DD or YYYY-MM-DD. End date can be omitted.
  27                 e.g, 2005/10/20, 2005-10-20
  28             
  29             [Start|End Time] should be in HH:MM in 24-hour format. Both of start|end Time can be omitted but not either of them.
  30                 e.g., 08:00, 12:00, 18:00
  31             
  32             In the parsing block of eventcal, it pops out first two date formatted text (startdate and enddate), 
  33             two time formatted text (starttime, endtime), and quoted or heading titie. 
  34             
  35             It ignores further occurrence of the targeted string. 
  36             The order of each fields (date, time, title) does not matter .
  37             The start date|time should precede the end date|time in the occurrence respectively.
  38         
  39         Use 'eventcal.py' to get a parsed format of the event which will be shown at the EventCalendar macro.
  40         To insert an administrative event, just click the [New Event] and input the information. It will be stored in a text file.
  41         
  42     Features:
  43         Monthly, List, Item view of events 
  44         Handles daily and timely events 
  45         Uses wiki subpages for storing normal event data 
  46         Fields included: Title, Start/End Date/Time, Reference Page in wiki 
  47 
  48     Notes:
  49         'MonthCalendar.py' developed by Thomas Waldmann <ThomasWaldmann@gmx.de> has inspired this macro.
  50         Much buggy.. :please report bugs and suggest your ideas.
  51         If you missed to add css for EventCalender, monthly view may not readable.
  52             Insert the EventCalendar css classes into the common.css of appropriate theme.
  53 
  54 """
  55 
  56 from MoinMoin import wikiutil, config
  57 from MoinMoin.Page import Page
  58 from MoinMoin.parser import wiki
  59 import re, calendar, time, datetime
  60 import codecs, os, urllib, StringIO
  61 
  62 
  63 # The following line sets the calendar to have either Sunday or Monday as
  64 # the first day of the week. Only SUNDAY or MONDAY (case sensitive) are
  65 # valid here.  All other values will not make good calendars.
  66 # XXX change here ----------------vvvvvv
  67 calendar.setfirstweekday(calendar.SUNDAY)
  68 
  69 class Globs:
  70     month_style_us = 1  # 1: October 2005; 2: 2005 / 10
  71     adminmsg=''
  72     pagepath = ''
  73     admin=''
  74     baseurl=''
  75     subname=''
  76     wkend = ''
  77     months = ''
  78     wkdays = ''
  79     today = ''
  80     request=''
  81     cal_action=''
  82     adjustimage = 0
  83 
  84 
  85 class Params:
  86     pagedepth = 0
  87     pagename = ''
  88     menubar = 0
  89     messages = 0
  90     monthlywidth = ''
  91     simplewidth = ''
  92     firstview = ''
  93     curdate = ''
  94     bgcolor = ''
  95 
  96 def execute(macro, args):
  97     
  98     # INITIALIZATION ----------------------------------------
  99     setglobalvalues(macro)
 100     getparams(args)
 101     setinternalvalues(macro)
 102     
 103     # allowed actions
 104     allowed_action = ['monthly', 'list', 'simple']
 105     default_action = Params.firstview
 106     
 107     # Internal variables
 108     cal_action = ''
 109     form_vals = {}
 110 
 111     # PROCESSING ARGUEMENTS ----------------------------------------
 112     if args:
 113         args=macro.request.getText(args)
 114 
 115     for item in macro.form.items():
 116         if not form_vals.has_key(item[0]):
 117 	    try:
 118 		    form_vals[item[0]]=item[1][0]
 119 	    except AttributeError:
 120 	        pass
 121     
 122     # PROCESSING ACTIONS ----------------------------------------
 123     cal_action = form_vals.get('calaction', default_action)
 124     
 125     if not cal_action in allowed_action:
 126         cal_action = default_action
 127     
 128     form_vals['calaction'] = cal_action
 129 
 130     # CONTROL FUNCTIONS ----------------------------------------
 131     
 132     html = []
 133     html_result = ''
 134     
 135     request = macro.request
 136     formatter = macro.formatter
 137     
 138     Globs.cal_action = cal_action
 139     
 140     # redirect to the appropriate view
 141     if cal_action == 'monthly':
 142         html_result = showcalendar(macro, form_vals)
 143         
 144     if cal_action == 'list':
 145         html_result = showeventlist(macro, form_vals)
 146 
 147     if cal_action == 'simple':
 148         html_result = showsimplecalendar(macro, form_vals)
 149     
 150     
 151     # format output
 152     html.append( showmessage() )
 153     html.append( html_result )
 154     html.append( showmenubar(form_vals) )
 155     
 156     return formatter.rawHTML(u''.join(html))
 157 
 158 
 159 def setinternalvalues(macro):
 160     # do nothing now    
 161     nothing = ''
 162 
 163 def getparams(args):
 164     # process arguments
 165     
 166     params = {}
 167     if args:
 168         # Arguments are comma delimited key=value pairs
 169         sargs = args.split(',')
 170     
 171         for item in sargs:
 172             sitem = item.split('=')
 173         
 174             if len(sitem) == 2:
 175                 key, value = sitem[0], sitem[1]
 176                 params[key.strip()] = value.strip()
 177 
 178     # page name: the page which the events will be resolved from
 179     # default: the page itself which the macro locates
 180     Params.pagename = params.get('pagename', Globs.pagename)
 181     
 182     # page depth: how much depth from the pagename when reading events
 183     # default: 0
 184     try:
 185         Params.pagedepth = int(params.get('pagedepth', 0))
 186     except ValueError:
 187         Params.pagedepth = 0
 188 
 189     # menu bar: shows menubar or not (1: show, 0: no menubar)
 190     # default: 1
 191     try:
 192         Params.menubar = int(params.get('menubar', 1))
 193     except ValueError:
 194         Params.menubar = 1
 195         
 196     # message: shows messages or not (1: show, 0: no message)
 197     # default: 1
 198     try:
 199         Params.messages = int(params.get('messages', 1))
 200     except ValueError:
 201         Params.messages = 1
 202     
 203     # calendar width in pixel or percent (monthly)
 204     # default: 600px
 205     Params.monthlywidth = params.get('monthlywidth', '600')
 206     if Params.monthlywidth:
 207         # Params.monthlywidth = Params.monthlywidth.replace('%', '%%')
 208         Params.monthlywidth = ' width="%s" ' % Params.monthlywidth
 209         
 210     # calendar width in pixel or percent (simply)
 211     # default: 150px
 212     Params.simplewidth = params.get('simplewidth', '150')
 213     if Params.simplewidth:
 214         # Params.simplewidth = Params.simplewidth.replace('%', '%%')
 215         Params.simplewidth = ' width="%s" ' % Params.simplewidth
 216     
 217     # calendar view: monthly, list, simple
 218     # default: 'monthly'
 219     Params.firstview = params.get('firstview', 'monthly')
 220 
 221     # calendar date: in YYYYMM format (in monthly, simple view)
 222     # default: current month
 223     Params.curdate = params.get('curdate', '')
 224 
 225     # default bgcolor
 226     Params.bgcolor = '#ddffdd'
 227 
 228 def setglobalvalues(macro):
 229     
 230     request = macro.request
 231     
 232     # Useful variables
 233     Globs.baseurl = macro.request.getBaseURL() + '/'
 234     Globs.pagename = macro.formatter.page.page_name
 235     Globs.request = request
 236     Globs.formatter = macro.formatter
 237     
 238     # This fixes the subpages bug. subname is now used instead of pagename when creating certain urls
 239     Globs.subname = Globs.pagename.split('/')[-1]
 240 
 241     pagepath = macro.formatter.page.getPagePath()
 242     Globs.pagepath = macro.formatter.page.getPagePath()
 243     
 244     # Figure out if we have delete privs
 245     try:
 246         # If a user can delete the page containing the EventCalendar, then they are considered a EventCalendar administrator
 247         if macro.request.user.may.delete(macro.formatter.page.page_name):
 248             Globs.admin = 'true'
 249     except AttributeError:
 250         pass
 251     
 252     # european / US differences
 253     months = ('January','February','March','April','May','June','July','August','September','October','November','December')
 254     
 255     # Set things up for Monday or Sunday as the first day of the week
 256     if calendar.firstweekday() == calendar.MONDAY:
 257         wkend = 6
 258         wkdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
 259     elif calendar.firstweekday() == calendar.SUNDAY:
 260         wkend = 0
 261         wkdays = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
 262     
 263     Globs.months = months
 264     Globs.wkdays = wkdays
 265     Globs.wkend = wkend
 266 
 267     year, month, day, h, m, s, wd, yd, ds = request.user.getTime(time.time())
 268     Globs.today = datetime.date(year, month, day)
 269 
 270 
 271 def showReferPageParsed(event, targettext='refer'):
 272     request = Globs.request
 273     pagename = Params.pagename
 274     
 275     refer = event['refer']
 276     title = event['title']
 277     targettext = event[targettext]
 278     startdate = event['startdate']
 279     
 280     bookmark = u'%s%s' % (title.replace(' ', ''), startdate)
 281     bookmark = urllib.quote_plus(bookmark.encode(config.charset))
 282     targetlink = Page(request, refer).link_to(request, text=targettext.strip(), querystr='action=show', anchor=bookmark)
 283     
 284     return targetlink
 285 
 286 
 287 
 288 def getquerystring(form_vals, req_fields):
 289     
 290     m_query = []
 291     tmp_form_vals = form_vals
 292     
 293     # format querystring
 294     # action should be poped out
 295     for field in req_fields:
 296         if tmp_form_vals.has_key(field):
 297             m_query.append(u'%s=%s' % (field, tmp_form_vals[field]) )
 298     
 299     if 'prevcalaction' in req_fields:
 300         if not tmp_form_vals.has_key('prevcalaction'):
 301             m_query.append(u'%s=%s' % ('prevcalaction', tmp_form_vals['calaction']) )
 302             
 303     m_query = u'&'.join(m_query)
 304     return m_query
 305 
 306 # bottom menu bar
 307 def showmenubar(form_vals):
 308     
 309     cal_action = Globs.cal_action
 310     
 311     if not Params.menubar: return ''
 312 
 313     if cal_action == 'simple':
 314         menuwidth = Params.simplewidth
 315     elif cal_action == 'monthly':
 316         menuwidth = Params.monthlywidth
 317     else:
 318         menuwidth = ''
 319     
 320     left_menu_selected = []
 321     right_menu_selected = []
 322     
 323     # Go Today
 324     year, month, day = gettodaydate()
 325     mnu_curmonthcal = u'<a href="?calaction=%s&caldate=%d%02d">[Today]</a>' % (cal_action, year, month)
 326     
 327     # List View
 328     mnu_listview = u'<a href="?calaction=list">[List]</a>'
 329     
 330     # Monthly View
 331     mnu_monthview = u'<a href="?calaction=monthly&%s">[Monthly]</a>' % getquerystring(form_vals, ['caldate'])
 332     
 333     # Simple Calendar View
 334     mnu_simpleview = u'<a href="?calaction=simple&%s">[Simple]</a>' % getquerystring(form_vals, ['caldate'])
 335 
 336     html = [
 337         u'\r\n',
 338         u'<table class="eventcalendar_menubar" %s>',
 339         u'  <tr>',
 340         u'  <td class="eventcalendar_menubar" align="left">%s</td>',
 341         u'  <td class="eventcalendar_menubar" align="right">%s</td>',
 342         u'  </tr>',
 343         u'</table>',
 344         ]
 345         
 346     if cal_action == 'list':
 347         left_menu_selected.append(mnu_monthview)
 348         left_menu_selected.append(mnu_simpleview)
 349 
 350     elif cal_action == 'simple':
 351         left_menu_selected.append(mnu_monthview)
 352         left_menu_selected.append(mnu_listview)
 353         right_menu_selected.append(mnu_curmonthcal)
 354 
 355     else:
 356         left_menu_selected.append(mnu_listview)
 357         left_menu_selected.append(mnu_simpleview)
 358         right_menu_selected.append(mnu_curmonthcal)
 359 
 360     left_menu_selected = u'\r\n'.join(left_menu_selected)
 361     right_menu_selected = u'\r\n'.join(right_menu_selected)
 362     
 363     html = u'\r\n'.join(html)
 364     html = html % (menuwidth, left_menu_selected, right_menu_selected)
 365 
 366     return html
 367         
 368 
 369 def getdatefield(str_date):
 370     str_year = ''
 371     str_month = ''
 372     str_day = ''
 373     
 374     if len(str_date) == 6:
 375         # year+month
 376         str_year = str_date[:4]
 377         str_month = str_date[4:]
 378         str_day = '1'
 379 
 380     elif len(str_date) == 8:
 381         # year+month+day
 382         str_year = str_date[:4]
 383         str_month = str_date[4:6]
 384         str_day = str_date[6:]
 385     
 386     elif len(str_date) == 10:
 387         # year+?+month+?+day
 388         str_year = str_date[:4]
 389         str_month = str_date[5:7]
 390         str_day = str_date[8:]
 391     
 392     else:
 393         raise ValueError
 394     
 395     # It raises exception if the input date is incorrect
 396     temp = datetime.date(int(str_year), int(str_month), int(str_day))
 397 
 398     return temp.year, temp.month, temp.day
 399 
 400 
 401 def gettimefield(str_time):
 402     str_hour = ''
 403     str_min = ''
 404     
 405     if len(str_time) == 4:
 406         # hour+minute
 407         str_hour = str_time[:2]
 408         str_min = str_time[2:]
 409     
 410     elif len(str_time) == 5:
 411         # hour+?+minute
 412         str_hour = str_time[:2]
 413         str_min = str_time[3:]
 414         
 415     else:
 416         raise ValueError
 417     
 418     # It raises exception if the input date is incorrect
 419     temp = datetime.time(int(str_hour), int(str_min))
 420 
 421     return temp.hour, temp.minute
 422 
 423 def showmessage():
 424     if not Params.messages: return ''
 425     
 426     if Globs.adminmsg:
 427         return u'<table class="eventcalendar_msg"><tr><td class="eventcalendar_msg">%s</td></tr></table>' % Globs.adminmsg
 428     else:
 429         return ''
 430 
 431 def gettodaydate():
 432     today = Globs.today
 433     return today.year, today.month, today.day    
 434 
 435 
 436 def cal_listhead():
 437 
 438     html = [
 439         u'  <tr>',
 440         u'      <td class="list_head">Title</td>',
 441         u'      <td class="list_head">Start Date</td>',
 442         u'      <td class="list_head">Start Time</td>',
 443         u'      <td class="list_head">End Date</td>',
 444         u'      <td class="list_head">End Time</td>',
 445         u'      <td class="list_head">Reference</td>',
 446         u'  </tr>',
 447         ]
 448         
 449     return u'\r\n'.join(html)
 450 
 451 
 452 def showeventlist(macro, form_vals):
 453     
 454     request = macro.request
 455     formatter = macro.formatter
 456     
 457     html_event_rows = []
 458     html_list_header = cal_listhead()
 459     
 460     # read all the events from data file
 461     events, cal_events = loadEvents(macro)
 462     
 463     # sort events
 464     sorted_eventids = events.keys()
 465     sorted_eventids.sort(cmp=lambda x,y: cmp(events[x]['startdate'], events[y]['startdate']))
 466     
 467     for eid in sorted_eventids:
 468         html_event_rows.append( listshow_event(events[eid], form_vals) )
 469     
 470     html_event_rows = u'\r\n'.join(html_event_rows)
 471     
 472     html_list_table = [
 473         u'\r\n<div id="eventlist">',
 474         u'<table class="eventlist">',
 475         u'%s' % html_list_header,
 476         u'%s' % html_event_rows,
 477         u'</table>',
 478         u'</div>',
 479         ]
 480     html_list_table = u'\r\n'.join(html_list_table)
 481         
 482     return html_list_table
 483         
 484 
 485 def listshow_event(event, form_vals):
 486     
 487     syear, smonth, sday = getdatefield(event['startdate'])
 488     eyear, emonth, eday = getdatefield(event['enddate'])
 489     
 490     time_info = 1
 491     try:
 492         shour, smin = gettimefield(event['starttime'])
 493         ehour, emin = gettimefield(event['endtime'])
 494     except ValueError:
 495         time_info = 0
 496     
 497         
 498     if time_info:
 499         html = [
 500             u'  <tr>',
 501             u'  <td class="list_entry">%s%s</td>' % (geticonurl(event['icon']), converttext(event['title'])),
 502             u'  <td class="list_entry">%d %02d/%02d</td>' % (syear, smonth, sday),
 503             u'  <td class="list_entry">%02d:%02d</td>' % (shour, smin),
 504             u'  <td class="list_entry">%d %02d/%02d</td>' % (eyear, emonth, eday),
 505             u'  <td class="list_entry">%02d:%02d</td>' % (ehour, emin),
 506             u'  <td class="list_entry">%s</td>' % showReferPageParsed(event, 'refer'),
 507             u'  </tr>',
 508             ]
 509     
 510     else:
 511         html = [
 512             u'  <tr>',
 513             u'  <td class="list_entry">%s%s</td>' % (geticonurl(event['icon']), converttext(event['title'])),
 514             u'  <td class="list_entry">%d %02d/%02d</td>' % (syear, smonth, sday),
 515             u'  <td class="list_entry">&nbsp;</td>',
 516             u'  <td class="list_entry">%d %02d/%02d</td>' % (eyear, emonth, eday),
 517             u'  <td class="list_entry">&nbsp;</td>',
 518             u'  <td class="list_entry">%s</td>' % showReferPageParsed(event, 'refer'),
 519             u'  </tr>',
 520             ]
 521         
 522     return u'\r\n'.join(html)
 523 
 524 
 525 def geticonurl(icon):
 526     if not icon:
 527         return ''
 528     
 529     request = Globs.request
 530     formatter = Globs.formatter
 531     
 532     
 533     out = StringIO.StringIO()
 534     request.redirect(out)
 535     wikiizer = wiki.Parser(icon, request)
 536     wikiizer.format(formatter)
 537     iconurl = out.getvalue()
 538     request.redirect()
 539     del out
 540     
 541     if Globs.adjustimage:
 542         regex_icon_height = r'height="[0-9]+"'
 543         pattern = re.compile(regex_icon_height, re.UNICODE + re.IGNORECASE)
 544         iconurl = pattern.sub('height="10"', iconurl)
 545         
 546         regex_icon_width = r'width="[0-9]+"'
 547         pattern = re.compile(regex_icon_width, re.UNICODE + re.IGNORECASE)
 548         iconurl = pattern.sub('', iconurl)
 549         
 550     iconurl = iconurl.replace('<p>', '')
 551     iconurl = iconurl.replace('</p>', '')
 552     
 553     return iconurl
 554 
 555 def showcalendar(macro, form_vals):
 556     
 557     request = macro.request
 558     formatter = macro.formatter
 559     
 560     if form_vals.has_key('caldate'):
 561         try:
 562             year, month, str_temp = getdatefield(form_vals['caldate'])
 563         except ValueError:
 564             message('Invalid target date: e.g., "200510"')
 565             year, month, dy = gettodaydate()
 566     elif Params.curdate:
 567         try:
 568             year, month, str_temp = getdatefield(Params.curdate)
 569         except ValueError:
 570             message('Invalid target date: e.g., "200510"')
 571             year, month, dy = gettodaydate()
 572             
 573     else:
 574         year, month, dy = gettodaydate()
 575     
 576     html = showeventcalendar(macro, year, month)
 577     
 578     return u''.join(html)
 579     
 580 def showsimplecalendar(macro, form_vals):
 581     
 582     request = macro.request
 583     formatter = macro.formatter
 584     
 585     if form_vals.has_key('caldate'):
 586         try:
 587             year, month, str_temp = getdatefield(form_vals['caldate'])
 588         except ValueError:
 589             message('Invalid target date: e.g., "200510"')
 590             year, month, dy = gettodaydate()
 591     elif Params.curdate:
 592         try:
 593             year, month, str_temp = getdatefield(Params.curdate)
 594         except ValueError:
 595             message('Invalid target date: e.g., "200510"')
 596             year, month, dy = gettodaydate()
 597     else:
 598         year, month, dy = gettodaydate()
 599     
 600     html = showsimpleeventcalendar(macro, year, month)
 601     
 602     return u''.join(html)
 603 
 604 
 605 # load events from wiki pages
 606 def loadEvents(macro, datefrom='', dateto=''):
 607     
 608     events, cal_events = loadEventsFromWikiPage(macro, datefrom, dateto)
 609     
 610     Globs.events = events
 611     Globs.cal_events = cal_events
 612     
 613     return events, cal_events
 614 
 615 # count events from wiki pages for simple view
 616 def countEvents(macro, datefrom='', dateto=''):
 617     
 618     cal_events = countEventsFromWikiPage(macro, datefrom, dateto)
 619     
 620     Globs.cal_events = cal_events
 621     
 622     return cal_events
 623 
 624 # sort cal_events by length of days
 625 def comp_cal_events(xid, yid):
 626     events = Globs.events
 627     
 628     if events[xid]['date_len'] > events[yid]['date_len']:
 629         return -1
 630     elif events[xid]['date_len'] == events[yid]['date_len']:
 631         if events[xid]['date_len'] == 1:
 632             return cmp(events[xid]['starttime'], events[yid]['starttime'])
 633         else:
 634             return 0
 635     else:
 636         return 1
 637         
 638 
 639 
 640 def loadEventsFromWikiPage(macro, datefrom, dateto):
 641     
 642     events = {}
 643     cal_events = {}
 644     
 645     request = macro.request
 646     depth = Params.pagedepth
 647     parent = Params.pagename
 648     
 649     try:
 650         datefrom, dateto = int(datefrom), int(dateto)
 651     except ValueError:
 652         datefrom, dateto = 0, 0
 653     
 654     # reads events from child pages
 655     children = getPages(request, '^%s/' % parent)
 656     
 657     # append the page itself
 658     children.append(parent)
 659     
 660     id = 0
 661     for child in children:
 662         shortname = child[len(parent):]
 663         # possibly limit depth
 664         if shortname.count('/') > depth:
 665             continue
 666         
 667         p = Page(request, child)
 668         page_content = p.get_raw_body()
 669         
 670         for evtrecord in getEventRecordFromPage(page_content):
 671             try:
 672                 e_start_date, e_start_time, e_end_date, e_end_time, e_title, e_view, e_bgcolor, e_icon = geteventfield(evtrecord)
 673             except ValueError:
 674                 # message('An event data is corrupted: invalid event format')
 675                 continue
 676             
 677             try:
 678                 e_start_year, e_start_month, e_start_day = getdatefield(e_start_date)
 679                 e_end_year, e_end_month, e_end_day = getdatefield(e_end_date)
 680             except ValueError:
 681                 # message('An event data is corrupted: invalid date format')
 682                 continue
 683             
 684             if e_start_time and e_end_time:
 685                 try:
 686                     e_start_time_hour, e_start_time_min = gettimefield(e_start_time)
 687                     e_end_time_min, e_end_time_min = gettimefield(e_end_time)
 688                 except ValueError:
 689                     # message('An event data is corrupted: invalid time format')
 690                     continue
 691             
 692             e_ref = p.page_name
 693             
 694             if not e_start_date:
 695                 # message('An event data is corrupted: invalid time format')
 696                 continue
 697             
 698             if datefrom and dateto:
 699                 if int(e_end_date) < datefrom or int(e_start_date) > dateto:
 700                     continue
 701             
 702             id += 1
 703             e_id = u'evt%d' % id
 704             
 705             # store event information
 706             events[e_id] = {}
 707             events[e_id]['id'] = e_id
 708             events[e_id]['startdate'] = e_start_date
 709             events[e_id]['starttime'] = e_start_time
 710             events[e_id]['enddate'] = e_end_date
 711             events[e_id]['endtime'] = e_end_time
 712             events[e_id]['title'] = e_title
 713             events[e_id]['refer'] = e_ref
 714             events[e_id]['bgcolor'] = e_bgcolor
 715             events[e_id]['icon'] = e_icon
 716             events[e_id]['date_len'] = diffday(e_start_date, e_end_date) + 1
 717             # events[e_id]['view'] = e_view
 718             
 719             # message('event %s: %s' % (e_id, events[e_id]))
 720             
 721             # records event information for each date b/w start and end
 722             cur_datetime = datetime.date(e_start_year, e_start_month, e_start_day)
 723             day_delta = datetime.timedelta(days=1)
 724             
 725             while 1:
 726                 tmp_record_date = formatDate(cur_datetime.year, cur_datetime.month, cur_datetime.day)
 727                 
 728                 if datefrom and dateto:
 729                     if int(tmp_record_date) < datefrom:
 730                         cur_datetime = cur_datetime + day_delta
 731                         continue
 732                     elif int(tmp_record_date) > dateto:
 733                         break
 734                         
 735                 if not cal_events.has_key(tmp_record_date):
 736                     cal_events[tmp_record_date] = []
 737                 cal_events[tmp_record_date].append(e_id)
 738                 
 739                 if tmp_record_date == e_end_date:
 740                     break
 741                 
 742                 cur_datetime = cur_datetime + day_delta
 743     
 744     return events, cal_events
 745 
 746 
 747 def countEventsFromWikiPage(macro, datefrom, dateto):
 748     
 749     cal_events = {}
 750     
 751     request = macro.request
 752     depth = Params.pagedepth
 753     parent = Params.pagename
 754     
 755     try:
 756         datefrom, dateto = int(datefrom), int(dateto)
 757     except ValueError:
 758         datefrom, dateto = 0, 0
 759     
 760     # reads events from child pages
 761     children = getPages(request, '^%s/' % parent)
 762     
 763     # append the page itself
 764     children.append(parent)
 765     
 766     id = 0
 767     for child in children:
 768         shortname = child[len(parent):]
 769         # possibly limit depth
 770         if shortname.count('/') > depth:
 771             continue
 772         
 773         p = Page(request, child)
 774         page_content = p.get_raw_body()
 775         
 776         for evtrecord in getEventRecordFromPage(page_content):
 777             try:
 778                 e_start_date, e_start_time, e_end_date, e_end_time, e_title, e_view, e_bgcolor, e_icon = geteventfield(evtrecord)
 779             except ValueError:
 780                 # message('An event data is corrupted: invalid event format')
 781                 continue
 782             
 783             try:
 784                 e_start_year, e_start_month, e_start_day = getdatefield(e_start_date)
 785                 e_end_year, e_end_month, e_end_day = getdatefield(e_end_date)
 786             except ValueError:
 787                 # message('An event data is corrupted: invalid date format')
 788                 continue
 789             
 790             if e_start_time and e_end_time:
 791                 try:
 792                     e_start_time_hour, e_start_time_min = gettimefield(e_start_time)
 793                     e_end_time_min, e_end_time_min = gettimefield(e_end_time)
 794                 except ValueError:
 795                     # message('An event data is corrupted: invalid time format')
 796                     continue
 797             
 798             e_ref = p.page_name
 799             
 800             if not e_start_date:
 801                 # message('An event data is corrupted: invalid time format')
 802                 continue
 803             
 804             if datefrom and dateto:
 805                 if int(e_end_date) < datefrom or int(e_start_date) > dateto:
 806                     continue
 807                     
 808             id += 1
 809             e_id = u'evt%d' % id
 810             
 811             # records event information for each date b/w start and end
 812             cur_datetime = datetime.date(e_start_year, e_start_month, e_start_day)
 813             day_delta = datetime.timedelta(days=1)
 814             
 815             while 1:
 816                 tmp_record_date = formatDate(cur_datetime.year, cur_datetime.month, cur_datetime.day)
 817                 
 818                 if datefrom and dateto:
 819                     if int(tmp_record_date) < datefrom:
 820                         cur_datetime = cur_datetime + day_delta
 821                         continue
 822                     elif int(tmp_record_date) > dateto:
 823                         break
 824                         
 825                 if not cal_events.has_key(tmp_record_date):
 826                     cal_events[tmp_record_date] = []
 827                 cal_events[tmp_record_date].append(e_id)
 828                 
 829                 if tmp_record_date == e_end_date:
 830                     break
 831                 
 832                 cur_datetime = cur_datetime + day_delta
 833     
 834     return cal_events
 835 
 836 
 837 def getEventRecordFromPage(pagecontent):
 838     
 839     eventrecords = []
 840     eventitem = {}
 841     
 842     # format specified page
 843     regex_eventcal = r'^#FORMAT eventcal(\s*.*)'
 844     pattern = re.compile(regex_eventcal, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 845     match = pattern.findall(pagecontent)
 846     
 847     if match:
 848         
 849         regex_params = r'^#FORMAT eventcal(\s*.*)$'
 850         pattern = re.compile(regex_params, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 851         match_option = pattern.findall(pagecontent)
 852         
 853         if match_option:
 854             view, bgcolor, icon = parseparamsinline(match_option[0])
 855         else:
 856             view, bgcolor, icon = '', '', ''
 857 
 858         regex_eventcal = r'[\{]{3}#!eventcal[^\n]*.(\s*.*?[^\}]+)[\}]{3}'
 859         pattern_eventcal = re.compile(regex_eventcal, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 860         
 861         # ignores #!eventcal blocks
 862         pagecontent = pattern_eventcal.sub(r'\n##eventcal\n\1\n##eventcal\n', pagecontent)
 863 
 864         # split events
 865         linesall = pagecontent.split(u'##eventcal\n')
 866         
 867         for eventtext in linesall:
 868             
 869             eventitem = {}
 870             eventtexttemp = eventtext.strip()
 871             if not eventtexttemp: 
 872                 continue
 873             
 874             eventitem['view'] = view
 875             eventitem['bgcolor'] = bgcolor
 876             eventitem['icon'] = icon
 877             eventitem['text'] = eventtext
 878             
 879             eventrecords.append(eventitem)
 880     
 881     else:
 882     
 883         # parsing block
 884         # regex_eventcal = r'[\{]{3}#!eventcal[^\n]*(\s*.*?[^\}]+)[\}]{3}'
 885         # regex_eventcal = r'[\{]{3}(#!eventcal[^\n]*[\s*.*?[^\}]+]+[\}]{3}'
 886         regex_eventcal = r'[\{]{3}(#!eventcal[^\n]*\s*.*?[^\}]+)[\}]{3}'
 887         pattern = re.compile(regex_eventcal, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 888         match = pattern.findall(pagecontent)
 889         
 890         if match:
 891             
 892             for blocktext in match:
 893                 
 894                 regex_params = r'^#!eventcal(\s*.*)$'
 895                 pattern = re.compile(regex_params, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 896                 match_option = pattern.findall(blocktext)
 897                             
 898                 if match_option:
 899                     view, bgcolor, icon = parseparamsinline(match_option[0])
 900                 else:
 901                     view, bgcolor, icon = '', '', ''
 902                 
 903                 # split events
 904                 linesall = blocktext.split(u'##eventcal\n')
 905                 
 906                 for eventtext in linesall:
 907                     
 908                     eventitem = {}
 909                     eventtext = eventtext.strip()
 910                     if not eventtext: 
 911                         continue
 912                     
 913                     eventitem['view'] = view
 914                     eventitem['bgcolor'] = bgcolor
 915                     eventitem['icon'] = icon
 916                     eventitem['text'] = eventtext
 917                     
 918                     eventrecords.append(eventitem)
 919         
 920     return eventrecords
 921     
 922 
 923 def parseparamsinline(lines):
 924     
 925     option_args = {}
 926     
 927     for arg in lines.split():
 928         try:
 929             key, value = arg.split('=')
 930             option_args[key.strip()] = value.strip()
 931         except ValueError:
 932             pass
 933             
 934     bgcolor = option_args.get('bgcolor', '')
 935     icon = option_args.get('icon', '')
 936     view = option_args.get('view', '')
 937     
 938     return view, bgcolor, icon
 939 
 940 def geteventfield(eventitem):
 941     
 942     lines = eventitem['text']
 943     view = eventitem['view']
 944     bgcolor = eventitem['bgcolor']
 945     icon = eventitem['icon']
 946     
 947     # need help on regular expressions for more efficient/flexible form
 948     regex_date = r'(\d{4}[/-]\d{2}[/-]\d{2})'
 949     regex_time = r'(\d{2}[:]\d{2})'
 950     regex_title = r'["]+(\s*.*?)["]+|[\']{2,}(\s*.*?)[\']{2,}|^[=]+(\s*.*?)[=]+$'
 951     regex_bgcolor = r'^##bgcolor (\s*.*?)$'
 952     regex_icon = r'^##icon (\s*.*?)$'
 953     regex_view= r'^##view (\s*.*?)$'
 954     
 955     # compile regular expression objects
 956     pattern_date = re.compile(regex_date, re.UNICODE)
 957     pattern_time = re.compile(regex_time, re.UNICODE)
 958     pattern_title = re.compile(regex_title, re.UNICODE + re.DOTALL + re.MULTILINE)
 959     pattern_bgcolor = re.compile(regex_bgcolor, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 960     pattern_icon = re.compile(regex_icon, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 961     pattern_view = re.compile(regex_view, re.UNICODE + re.MULTILINE + re.IGNORECASE)
 962     
 963     # retrieve date
 964     match = pattern_date.findall(lines)
 965     
 966     if not len(match):
 967         # message('at least one date field should be specified')
 968         # self.printoutput('Parse Error', msg, '')
 969         # ERROR
 970         return '','','','','','','',''
 971     
 972     # month, day only should be handled
 973     
 974     startdate = match[0]
 975     if len(match) > 1:
 976         enddate = match[1]
 977     else:
 978         enddate = ''
 979     
 980     # retrieve time
 981     match = pattern_time.findall(lines)
 982     
 983     if len(match) >= 2:
 984         starttime = match[0]
 985         endtime = match[1]
 986     elif len(match) == 0:
 987         starttime = ''
 988         endtime = ''
 989     else:
 990         # message('no or 2 time field should be specified')
 991         # ERROR
 992         return '','','','','','','',''
 993         
 994     # retrieve title
 995     match = pattern_title.search(lines)
 996     
 997     if not match:
 998         title = 'No title'
 999     else:
1000         for item in match.groups():
1001             if item:
1002                 title = item
1003                 break
1004 
1005     # retrieve bgcolor
1006     match = pattern_bgcolor.search(lines)
1007     if match:
1008         bgcolor = match.group(0)[10:]
1009     
1010     # retrieve icon
1011     match = pattern_icon.search(lines)
1012     if match:
1013         icon = match.group(0)[7:]
1014         
1015     # retrieve view
1016     match = pattern_view.search(lines)
1017     if match:
1018         view = match.group(0)[7:]
1019 
1020     # if no time, it's 1-day event
1021     if not enddate:
1022         enddate = startdate
1023     
1024     # check the validity of date/time
1025     try:
1026         syear, smonth, sday = getdatefield(startdate)
1027         eyear, emonth, eday = getdatefield(enddate)
1028     except ValueError:
1029         # message('invalid date format: %s, %s' % (startdate, enddate))
1030         return '','','','','','','',''
1031     
1032     if startdate and enddate:
1033         if datetime.date(syear, smonth, sday) > datetime.date(eyear, emonth, eday):
1034             # message('startdate should precede enddate')
1035             return '','','','','','','',''
1036     
1037     # format date
1038     startdate = u'%4d%02d%02d' %(syear, smonth, sday)
1039     enddate = u'%4d%02d%02d' %(eyear, emonth, eday)
1040     
1041     if (starttime and endtime):
1042         try:
1043             shour, smin = gettimefield(starttime)
1044             ehour, emin = gettimefield(endtime)
1045         except ValueError:
1046             # message('invalid time format: %s, %s' % (startdate, enddate))
1047             return '','','','','','','',''
1048         
1049         if startdate == enddate:
1050             if datetime.time(shour, smin) > datetime.time(ehour, emin):
1051                 # message('starttime should precede endtime')
1052                 return '','','','','','','',''
1053                 
1054         # format time
1055         starttime = u'%02d%02d' %(shour, smin)
1056         endtime = u'%02d%02d' %(ehour, emin)
1057     
1058     return startdate, starttime, enddate, endtime, title, view, bgcolor, icon
1059 
1060 
1061 
1062 def converttext(targettext):
1063     # Converts some special characters of html to plain-text style
1064     # What else to handle?
1065 
1066     targettext = targettext.replace(u'&', '&amp')
1067     targettext = targettext.replace(u'>', '&gt;')
1068     targettext = targettext.replace(u'<', '&lt;')
1069     targettext = targettext.replace(u'\n', '<br>')
1070     targettext = targettext.replace(u'"', '&quot;')
1071     targettext = targettext.replace(u'\t', '&nbsp;&nbsp;&nbsp;&nbsp')
1072     targettext = targettext.replace(u'  ', '&nbsp;&nbsp;')
1073         
1074     return targettext
1075 
1076 # monthly view
1077 def showeventcalendar(macro, year, month):
1078     
1079     request = macro.request
1080     formatter = macro.formatter
1081     _ = request.getText
1082     
1083     wkend = Globs.wkend
1084     months= Globs.months
1085     wkdays = Globs.wkdays
1086     
1087     # get the calendar
1088     monthcal = calendar.monthcalendar(year, month)
1089 
1090     # shows current year & month
1091     html_header_curyearmonth = calhead_yearmonth(year, month, 'head_yearmonth')
1092     
1093     r7 = range(7)
1094     
1095     # shows header of week days
1096     html_header_weekdays = []
1097     
1098     for wkday in r7:
1099         wday = _(wkdays[wkday])
1100         html_header_weekdays.append( calhead_weekday(wday, 'head_weekday') )
1101     html_header_weekdays = '    <tr>\r\n%s\r\n</tr>\r\n' % u'\r\n'.join(html_header_weekdays)
1102  
1103     # pending events for next row
1104     next_pending = []
1105     
1106     # gets previous, next month
1107     day_delta = datetime.timedelta(days=-1)
1108     cur_month = datetime.date(year, month, 1)
1109     prev_month = cur_month + day_delta
1110     
1111     day_delta = datetime.timedelta(days=15)
1112     cur_month_end = datetime.date(year, month, 25)
1113     next_month = cur_month_end + day_delta
1114     
1115     prev_monthcal = calendar.monthcalendar(prev_month.year, prev_month.month)
1116     next_monthcal = calendar.monthcalendar(next_month.year, next_month.month)
1117     
1118     # shows days
1119     html_week_rows = []
1120     
1121     # set ranges of events
1122     datefrom = u'%04d%02d22' % (prev_month.year, prev_month.month)
1123     dateto = u'%04d%02d06' % (next_month.year, next_month.month)
1124     
1125     # read all the events from data file
1126     events, cal_events = loadEvents(macro, datefrom, dateto)
1127     # message(u'total # of events: %d' % len(events))
1128     
1129     # sort cal_events
1130     for eachdate in cal_events.keys():
1131         # cal_events[eachdate].sort(cmp=lambda x,y: cmp(events[y]['date_len'], events[x]['date_len']))
1132         cal_events[eachdate].sort(comp_cal_events)
1133     
1134     for week in monthcal:
1135         
1136         # day head rows
1137         html_headday_cols = []
1138         html_events_rows = []
1139         
1140         for wkday in r7:
1141              
1142             day = week[wkday]
1143             
1144             if not day:
1145                 if week == monthcal[0]:
1146                     nb_day = prev_monthcal[-1][wkday]
1147                 else:
1148                     nb_day = next_monthcal[0][wkday]
1149                     
1150                 html_headday_cols.append( calhead_day_nbmonth(nb_day) )
1151             else:
1152                 html_headday_cols.append( calhead_day(year, month, day, wkday) )
1153         
1154         html_headday_row = '    <tr>\r\n%s\r\n</tr>\r\n' % u'\r\n'.join(html_headday_cols)
1155         html_week_rows.append(html_headday_row)
1156         
1157         # dummy rows
1158         html_headdummy_cols = []
1159         
1160         for wkday in r7:
1161             day = week[wkday]
1162             if not day:
1163                 html_headdummy_cols.append( calshow_blankbox('head_dummy_nbmonth') )
1164             else:
1165                 html_headdummy_cols.append( calshow_blankbox('head_dummy') )
1166         
1167         html_headdummy_cols = u'\r\n'.join(html_headdummy_cols)
1168         html_week_rows.append(' <tr>\r\n%s </tr>\r\n' % html_headdummy_cols)
1169         
1170         # pending events for next row
1171         pending = next_pending
1172         next_pending = []
1173         
1174         # show events
1175         while 1: 
1176             event_left = 7
1177             colspan = -1
1178             html_events_cols = []
1179 
1180             for wkday in r7:
1181              
1182                 day = week[wkday]
1183                 
1184                 if not day:
1185                     if week == monthcal[0]:
1186                         cur_date = formatDate(prev_month.year, prev_month.month, prev_monthcal[-1][wkday])
1187                     else:
1188                         cur_date = formatDate(next_month.year, next_month.month, next_monthcal[0][wkday])
1189                 else:
1190                     cur_date = formatDate(year, month, day)
1191 
1192                 # if an event is already displayed with colspan
1193                 if colspan > 0:
1194                     colspan -= 1
1195                     if cal_events.has_key(cur_date) and lastevent in cal_events[cur_date]:
1196                         cal_events[cur_date].remove(lastevent)
1197                     
1198                     continue
1199                     
1200                 # if there is any event for this date
1201                 if cal_events.has_key(cur_date):
1202                     if len(cal_events[cur_date]) > 0:
1203                         
1204                         if wkday == 0 and len(pending) > 0:
1205                             todo_event_id = pending.pop(0)
1206                             if todo_event_id in cal_events[cur_date]:
1207                                 cur_event = events[todo_event_id]
1208                                 temp_len = diffday(cur_date, cur_event['enddate']) + 1
1209                                 
1210                                 # calculate colspan value
1211                                 if (7-wkday) < temp_len:
1212                                     colspan = 7 - wkday
1213                                     next_pending.append(cur_event['id'])
1214                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, 'append_pending', cur_date) )
1215 
1216                                 else:
1217                                     colspan = temp_len
1218                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, 'append', cur_date) )
1219                                 
1220                                 
1221                                 cal_events[cur_date].remove(todo_event_id)
1222 
1223                                 colspan -= 1
1224                                 lastevent = todo_event_id
1225                             else:
1226                                 message('FATAL ERROR')
1227                             continue
1228                             
1229                         # if the start date of the event is current date    
1230                         
1231                         for e_id in cal_events[cur_date]:
1232                             if events[e_id]['startdate'] == cur_date:
1233                                 cur_event = events[cal_events[cur_date].pop(cal_events[cur_date].index(e_id))]
1234                                 
1235                                 # calculate colspan value
1236                                 if (7-wkday) < cur_event['date_len']:
1237                                     colspan = 7 - wkday
1238                                     next_pending.append(cur_event['id'])
1239                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, 'pending', cur_date) )
1240 
1241                                 else:
1242                                     colspan = cur_event['date_len']
1243                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, '', cur_date) )
1244                                 
1245                                 colspan -= 1
1246                                 lastevent = cur_event['id']
1247                                 break
1248                             
1249                         # if the start date of the event is NOT current date
1250                         else:
1251                             if day == 0 and wkday == 0 and week == monthcal[0]:
1252                                 cur_event = events[cal_events[cur_date].pop(0)]
1253                                 temp_len = diffday(cur_date, cur_event['enddate']) + 1
1254                                 
1255                                 # calculate colspan value
1256                                 if (7-wkday) < temp_len:
1257                                     colspan = 7 - wkday
1258                                     next_pending.append(cur_event['id'])
1259                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, 'append_pending', cur_date) )
1260                                 else:
1261                                     colspan = temp_len
1262                                     html_events_cols.append( calshow_eventbox(cur_event, colspan, 'append', cur_date) )
1263                                 
1264                                 
1265                                 colspan -= 1
1266                                 lastevent = cur_event['id']
1267                             else:
1268                                 if not day:
1269                                     html_events_cols.append( calshow_blankbox('cal_nbmonth') )
1270                                 else:
1271                                     html_events_cols.append( calshow_blankbox('cal_noevent') )
1272                                 event_left -= 1
1273                                 
1274                     else:
1275                         if not day:
1276                             html_events_cols.append( calshow_blankbox('cal_nbmonth') )
1277                         else:
1278                             html_events_cols.append( calshow_blankbox('cal_noevent') )
1279                         
1280                         event_left -= 1        
1281                 
1282                 # if there is NO event for this date
1283                 else:
1284                     if not day:
1285                         html_events_cols.append( calshow_blankbox('cal_nbmonth') )
1286                     else:
1287                         html_events_cols.append( calshow_blankbox('cal_noevent') )
1288                         
1289                     event_left -= 1
1290             
1291             # if no event for this entry
1292             if not event_left:
1293                 # ignore the previous entry
1294                 break
1295             else:
1296                 html_events_rows.append(' <tr>\r\n%s </tr>\r\n' % u'\r\n'.join(html_events_cols))
1297             
1298         # show dummy blank slots for week height
1299         left_blank_rows = 2 - len(html_events_rows)
1300         
1301         # message('%d: left_blank_rows=%d' % (day, left_blank_rows))
1302         
1303         # remove the followings
1304         if left_blank_rows > 0 and 0:
1305             for i in range(left_blank_rows):
1306                 html_events_cols = []
1307                 for wkday in r7:
1308                     day = week[wkday]
1309                     if not day:
1310                         html_events_cols.append( calshow_blankbox('cal_nbmonth') )
1311                     else:
1312                         html_events_cols.append( calshow_blankbox('cal_noevent') )
1313                 
1314                 html_events_rows.append(' <tr>\r\n%s </tr>\r\n' % u'\r\n'.join(html_events_cols))
1315         
1316         
1317         # close the week slots
1318         html_events_cols = []
1319         for wkday in r7:
1320             day = week[wkday]
1321             if not day:
1322                 html_events_cols.append( calshow_blankbox('cal_last_nbmonth') )
1323             else:
1324                 html_events_cols.append( calshow_blankbox('cal_last_noevent') )
1325     
1326         html_events_rows.append(' <tr>\r\n%s </tr>\r\n' % u'\r\n'.join(html_events_cols))
1327         
1328         html_events_rows = u'\r\n'.join(html_events_rows)
1329         html_week_rows.append(html_events_rows)
1330             
1331     html_calendar_rows = u'\r\n'.join(html_week_rows)
1332     
1333     html_cal_table = [
1334         u'\r\n<div id="eventcalendar">',
1335         u'<table class="eventcalendar" %s>' % Params.monthlywidth,
1336         u'%s' % html_header_curyearmonth,
1337         u'%s' % html_header_weekdays,
1338         u'%s' % html_calendar_rows,
1339         u'</table>',
1340         u'</div>',
1341         ]
1342     html_cal_table = u'\r\n'.join(html_cal_table)
1343         
1344     return html_cal_table
1345 
1346 # simple view
1347 def showsimpleeventcalendar(macro, year, month):
1348     
1349     request = macro.request
1350     formatter = macro.formatter
1351     _ = request.getText
1352     
1353     wkend = Globs.wkend
1354     months= Globs.months
1355     wkdays = Globs.wkdays
1356     
1357     # get the calendar
1358     monthcal = calendar.monthcalendar(year, month)
1359 
1360     # shows current year & month
1361     html_header_curyearmonth = calhead_yearmonth(year, month, 'simple_yearmonth')
1362     
1363     r7 = range(7)
1364     
1365     # shows header of week days
1366     html_header_weekdays = []
1367     
1368     for wkday in r7:
1369         wday = wkdays[wkday]
1370         html_header_weekdays.append( calhead_weekday(wday, 'simple_weekday') )
1371     html_header_weekdays = '    <tr>\r\n%s\r\n</tr>\r\n' % u'\r\n'.join(html_header_weekdays)
1372  
1373     # gets previous, next month
1374     day_delta = datetime.timedelta(days=-1)
1375     cur_month = datetime.date(year, month, 1)
1376     prev_month = cur_month + day_delta
1377     
1378     day_delta = datetime.timedelta(days=15)
1379     cur_month_end = datetime.date(year, month, 25)
1380     next_month = cur_month_end + day_delta
1381     
1382     prev_monthcal = calendar.monthcalendar(prev_month.year, prev_month.month)
1383     next_monthcal = calendar.monthcalendar(next_month.year, next_month.month)
1384     
1385     # shows days
1386     html_week_rows = []
1387     
1388     # set ranges of events
1389     datefrom = u'%04d%02d22' % (prev_month.year, prev_month.month)
1390     dateto = u'%04d%02d06' % (next_month.year, next_month.month)
1391     
1392     # read all the events from data file
1393     cal_events = countEvents(macro, datefrom, dateto)
1394     
1395     for week in monthcal:
1396         
1397         # day head rows
1398         html_headday_cols = []
1399         html_events_rows = []
1400         
1401         for wkday in r7:
1402              
1403             day = week[wkday]
1404             
1405             if not day:
1406                 if week == monthcal[0]:
1407                     nb_day = prev_monthcal[-1][wkday]
1408                 else:
1409                     nb_day = next_monthcal[0][wkday]
1410                     
1411                 html_headday_cols.append( simple_eventbox(year, month, day, nb_day, 'simple_nb') )
1412             else:
1413                 cur_date = formatDate(year, month, day)
1414                 if cal_events.has_key(cur_date):
1415                     html_headday_cols.append( simple_eventbox(year, month, day, wkday, 'simple_event') )
1416                 else:
1417                     html_headday_cols.append( simple_eventbox(year, month, day, wkday, 'simple_noevent') )
1418         
1419         html_headday_row = '    <tr>\r\n%s\r\n</tr>\r\n' % u'\r\n'.join(html_headday_cols)
1420         html_week_rows.append(html_headday_row)
1421             
1422     html_calendar_rows = u'\r\n'.join(html_week_rows)
1423     
1424     html_cal_table = [
1425         u'\r\n<div id="eventcalendar">',
1426         u'<table class="simplecalendar" %s>' % Params.simplewidth,
1427         u'%s' % html_header_curyearmonth,
1428         u'%s' % html_header_weekdays,
1429         u'%s' % html_calendar_rows,
1430         u'</table>',
1431         u'</div>',
1432         ]
1433     html_cal_table = u'\r\n'.join(html_cal_table)
1434         
1435     return html_cal_table
1436 
1437 
1438 # show weekday
1439 def calhead_yearmonth(year, month, headclass):
1440     
1441     months = Globs.months
1442     monthstyle_us = Globs.month_style_us
1443     cal_action = Globs.cal_action
1444     
1445     nextyear, nextmonth = yearmonthplusoffset(year, month, 1)
1446     prevyear, prevmonth = yearmonthplusoffset(year, month, -1)
1447     
1448     prevlink = u'?calaction=%s&caldate=%d%02d' % (cal_action, prevyear, prevmonth)
1449     nextlink = u'?calaction=%s&caldate=%d%02d' % (cal_action, nextyear, nextmonth)
1450     
1451     if monthstyle_us:
1452         stryearmonth = u'%s %d' % (months[month-1], year)
1453     else:
1454         stryearmonth = u'%d / %02d' % (year, month)
1455     
1456     html = [
1457         u'  <tr>',
1458         u'      <td class="%s"><a href="%s">&lt;</a></td>' % (headclass, prevlink),
1459         u'      <td colspan="5" class="%s">%s</td>' % (headclass, stryearmonth),
1460         u'      <td class="%s"><a href="%s">&gt;</a></td>' % (headclass, nextlink),
1461         u'  </tr>',
1462         ]
1463         
1464     return u'\r\n'.join(html)
1465 
1466 # show days in simple
1467 def simple_eventbox(year, month, day, wkday, boxclass):
1468     wkend = Globs.wkend
1469     if wkday == wkend:
1470         html_text = u'<font color="#aa7744">%s</font>' % day
1471     else:
1472         html_text = u'%s' % day
1473     
1474     cyear, cmonth, cday = gettodaydate()
1475     
1476     if boxclass == 'simple_nb':
1477         html = u'  <td class="%s">&nbsp;</td>\r\n' % boxclass
1478     else:
1479         if cyear == year and cmonth == month and cday == day:
1480             html = u'  <td class="%s_today">%s</td>\r\n' % (boxclass, html_text)
1481         else:
1482             html = u'  <td class="%s">%s</td>\r\n' % (boxclass, html_text)
1483        
1484     return html
1485 
1486 
1487 # show weekday
1488 def calhead_weekday(wday, headclass):
1489     if headclass == 'simple_weekday':
1490         html = u'       <td class="%s">%s</td>\r\n' % (headclass, wday[0])
1491     else:
1492         html = u'       <td class="%s">%s</td>\r\n' % (headclass, wday)
1493 
1494     return html
1495 
1496 
1497 # show days of current month
1498 def calhead_day(year, month, day, wkday):
1499     wkend = Globs.wkend
1500     if wkday == wkend:
1501         html_text = u'<font color="#FF3300">%s</font>' % day
1502     else:
1503         html_text = u'%s' % day
1504     
1505     cyear, cmonth, cday = gettodaydate()
1506     
1507     if cyear == year and cmonth == month and cday == day:
1508         html = u'  <td class="head_day_today">&nbsp;%s</td>\r\n' % html_text
1509     else:
1510         html = u'  <td class="head_day">&nbsp;%s</td>\r\n' % html_text
1511        
1512     return html
1513 
1514 
1515 # show days of previous or next month
1516 def calhead_day_nbmonth(day):
1517     html = u'  <td class="head_day_nbmonth">&nbsp;%s</td>\r\n' % day
1518     return html
1519 
1520     
1521 # show blank calendar box
1522 def calshow_blankbox(classname):
1523     html = u'  <td class="%s">&nbsp;</td>' % classname
1524     return html
1525 
1526 # show eventbox
1527 def calshow_eventbox(event, colspan, status, cur_date):
1528     if status:
1529         status = u'_%s' % status
1530     
1531     title = event['title']
1532     eid = event['id']
1533     startdate = event['startdate']
1534     enddate = event['enddate']
1535     starttime = event['starttime']
1536     endtime = event['endtime']
1537     icon = event['icon']
1538     bgcolor = event['bgcolor']
1539     
1540     year, month, day = getdatefield(cur_date)
1541     
1542     if bgcolor:
1543         bgcolor = 'background-color: %s;' % bgcolor
1544     else:
1545         bgcolor = 'background-color: %s;' % Params.bgcolor
1546     
1547     if (startdate == enddate) and starttime:
1548         shour, smin = gettimefield(starttime)
1549         
1550         link = [
1551             u'<table width="100%%" style="border-width: 0px; padding: 0px; margin: 0px;"><tr>\r\n',
1552             u'<td width="10" nowrap style="border-width: 0px; padding: 0px; margin: 0px; text-align: left; vertical-align: top; font-size: 7pt; color: #000000;">%02d:%02d&nbsp;</td>\r\n' % (shour, smin),
1553             # u'<td>&nbsp;</td>',
1554             u'<td style="border-width: 0px; padding: 0px; margin: 0px; text-align: left; vertical-align: top;font-size: 8pt;">',
1555             u'%s%s' % (geticonurl(event['icon']), showReferPageParsed(event, 'title')),
1556             u'</td>\r\n</tr></table>',
1557             ]
1558         link = u''.join(link)
1559     else:
1560         link = u'%s%s' % (geticonurl(event['icon']), showReferPageParsed(event, 'title'))
1561     
1562     
1563     html = [
1564         u'  <td class="cal_eventbox" colspan="%d"><table class="cal_event">' % colspan,
1565         u'      <tr><td id="cal_event_%s" class="cal_event%s" style="%s">%s</td></tr>' % (eid, status, bgcolor, link),
1566         u'      </table></td>',
1567         ]
1568         
1569     return u'\r\n'.join(html)
1570         
1571 
1572 
1573 # date format should be like '20051004' for 2005, Oct., 04
1574 def diffday(date1, date2):
1575     
1576     try:
1577         year1, month1, day1 = getdatefield(date1)
1578         year2, month2, day2 = getdatefield(date2)
1579         tmp_diff = datetime.date(year2, month2, day2) - datetime.date(year1, month1, day1)
1580     except ValueError:
1581         message('An event data is corrupted: invalid date format')
1582         return 0
1583 
1584     return tmp_diff.days
1585 
1586 
1587 def formatDate(year, month, day):
1588     # returns like: '20051004'
1589     return u'%4d%02d%02d' % (year, month, day)
1590 
1591 def cliprgb(r,g,b): # don't use 255!
1592     if r < 0:   r=0
1593     if r > 254: r=254
1594     if b < 0:   b=0
1595     if b > 254: b=254
1596     if g < 0:   g=0
1597     if g > 254: g=254
1598     return r, g, b
1599 
1600 
1601 def message(astring):
1602     Globs.adminmsg += u'%s<br>\r\n' % astring
1603 
1604 def yearmonthplusoffset(year, month, offset):
1605     month = month+offset
1606     # handle offset and under/overflows - quick and dirty, yes!
1607     while month < 1:
1608         month = month + 12
1609         year = year - 1
1610     while month > 12:
1611         month = month - 12
1612         year = year + 1
1613     return year, month
1614 
1615 def getPages(request, filter_regex=None):
1616     """ Return a (filtered) list of pages names.
1617     """
1618     filter = None
1619     if filter_regex:
1620         filter = re.compile(filter_regex).match
1621     pages = request.rootpage.getPageList(filter=filter)
1622     return pages
1623     
1624     
1625 def cutstring(strcut, intlen):
1626     if len(strcut) > intlen:
1627         newlen = intlen - 3
1628         strtemp = strcut[:newlen] + '...'
1629     else:
1630         strtemp = strcut
1631         
1632     return strtemp

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] (2005-10-31 18:42:02, 65.4 KB) [[attachment:EventCalendar-080.py]]
  • [get | view] (2005-11-22 17:40:26, 55.4 KB) [[attachment:EventCalendar-090.py]]
  • [get | view] (2006-01-15 16:25:08, 57.2 KB) [[attachment:EventCalendar-091.py]]
  • [get | view] (2006-01-17 08:02:06, 75.4 KB) [[attachment:EventCalendar-092.py]]
  • [get | view] (2006-01-18 03:54:33, 75.6 KB) [[attachment:EventCalendar-093.py]]
  • [get | view] (2006-02-25 09:00:17, 74.8 KB) [[attachment:EventCalendar-094-easytime.py]]
  • [get | view] (2006-02-06 04:39:13, 76.2 KB) [[attachment:EventCalendar-094.py]]
  • [get | view] (2006-04-17 13:21:03, 122.7 KB) [[attachment:EventCalendar-096.py]]
  • [get | view] (2006-05-12 15:26:40, 150.6 KB) [[attachment:EventCalendar-098.py]]
  • [get | view] (2008-11-05 16:58:27, 3.2 KB) [[attachment:EventCalendar-099-01.py.patch]]
  • [get | view] (2006-05-23 09:50:33, 152.3 KB) [[attachment:EventCalendar-099.py]]
  • [get | view] (2008-02-14 05:18:57, 1.0 KB) [[attachment:EventCalendar-099.py.patch]]
  • [get | view] (2009-07-15 23:35:13, 151.1 KB) [[attachment:EventCalendar-099a.py]]
  • [get | view] (2013-01-21 02:05:25, 152.4 KB) [[attachment:EventCalendar-099b.py]]
  • [get | view] (2006-11-30 15:51:59, 1.8 KB) [[attachment:defaults-099-01.patch]]
  • [get | view] (2005-10-31 18:35:06, 5.0 KB) [[attachment:eventcal-080.css]]
  • [get | view] (2005-10-31 18:35:01, 11.3 KB) [[attachment:eventcal-080.py]]
  • [get | view] (2005-11-22 17:40:51, 6.8 KB) [[attachment:eventcal-090.css]]
  • [get | view] (2005-11-22 17:40:40, 18.1 KB) [[attachment:eventcal-090.py]]
  • [get | view] (2006-04-17 13:22:09, 8.9 KB) [[attachment:eventcal-096.css]]
  • [get | view] (2006-02-08 02:31:50, 1.4 KB) [[attachment:eventcalendar-094-01.patch]]
  • [get | view] (2006-11-30 15:52:26, 12.2 KB) [[attachment:label_priority-099-01.patch]]
  • [get | view] (2006-11-16 17:06:28, 1.1 KB) [[attachment:pagelinks-099-01.patch]]
  • [get | view] (2006-11-16 17:06:52, 2.9 KB) [[attachment:pagelist-099-01.patch]]
  • [get | view] (2006-03-29 07:37:02, 118.7 KB) [[attachment:snap-daily.jpg]]
  • [get | view] (2006-01-18 03:52:49, 23.2 KB) [[attachment:snap-list.jpg]]
  • [get | view] (2006-01-18 03:52:40, 37.4 KB) [[attachment:snap-monthly.jpg]]
  • [get | view] (2006-03-29 07:35:54, 43.8 KB) [[attachment:snap-simple.jpg]]
  • [get | view] (2006-01-18 03:53:04, 29.4 KB) [[attachment:snap-upcoming.jpg]]
  • [get | view] (2006-03-29 07:36:43, 161.0 KB) [[attachment:snap-weekly.jpg]]
  • [get | view] (2007-06-12 19:51:39, 55.0 KB) [[attachment:time_bug.PNG]]
 All files | Selected Files: delete move to page copy to page

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