Attachment 'EventCalendar-091.py'

Download

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

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.