try: from StringIO import StringIO except ImportError: from io import StringIO ## for Python 3 import re import time import string from trac.wiki.macros import WikiMacroBase from trac.wiki.formatter import format_to_html class BlogMacro(WikiMacroBase): """ Blog macro 0.3-alpha [[BR]] Usage sample 1: {{{[[Blog(blog/%)]]}}} [[BR]] Usage sample 2: {{{[[Blog(2004%,blog/%)]]}}} [[BR]] """ month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def expand_macro(self, formatter, name, content): if formatter.req.args.get( 'macro.blog.rendering', '0' ) == '1': return "" formatter.req.args['macro.blog.rendering'] = '1' pagename = formatter.req.args.get('page', 'WikiStart') # we can accept two optional parameters: year and month, if not provided, will use today's timeToday = time.localtime() year = int( formatter.req.args.get( "year", str( timeToday.tm_year ) ) ) month = int( formatter.req.args.get( "month", str( timeToday.tm_mon ) ) ) with self.env.db_query as db: years = {} # years = { # 2004: { # 1: 1, # 2: 3, # }, # 2005: { # 2: 4, # 3: 3, # }, # } toc = [] # the TOC body = [] # the body bIndex = 0 toc.append( '' ) # remember: TOC and body are reversed before joining for blogPattern in content.split( ',' ): blogPattern = blogPattern.strip() if blogPattern.startswith("/"): blogPattern = blogPattern.lstrip("/") sql = "SELECT DISTINCT name from wiki where name like '%s' order by time" % blogPattern csName = db.cursor() # the matched wiki name csName.execute( sql ) while 1: rowName = csName.fetchone() if rowName == None: break name = rowName[0] sql = "SELECT text,time,author from wiki where name = '%s' order by version desc limit 1" % name csText = db.cursor() # the wiki text and time and author csText.execute( sql ) while 1: rowText = csText.fetchone() if rowText == None: break rowTextTime = rowText[1] / 1000000 timeParts = time.localtime(rowTextTime) if not timeParts.tm_year in years.keys(): years[timeParts.tm_year] = {timeParts.tm_mon: 1} else: if not timeParts.tm_mon in years[timeParts.tm_year].keys(): years[timeParts.tm_year][timeParts.tm_mon] = 1 else: years[timeParts.tm_year][timeParts.tm_mon] += 1 if timeParts.tm_year != year or timeParts.tm_mon != month: break #~ env.log.debug( 'rendering %s' % pagename ) #text = wiki_to_html( rowText[0], self.env, None, db, 0 ) text = format_to_html( self.env, formatter.context, rowText[0] ) timeStr = time.ctime(rowTextTime) author = rowText[2] # get the wiki title from its output matchedTitle = re.search( r"<(h\d+).*?>(.*?)\1>", text ) title = name if matchedTitle != None: title = matchedTitle.group(2).strip() bIndex+=1 toc.append( '
Blog of %d/%d
' % (year, month) ) # Reverse TOC and body to put the most recent items at the top toc.reverse() body.reverse() out = StringIO() #~ out.write( 'Blog by Date:
' ) out.write('