Back to index

plone3  3.1.7
calendar.py
Go to the documentation of this file.
00001 from StringIO import StringIO
00002 from time import localtime
00003 
00004 from plone.memoize import ram
00005 from plone.memoize.compress import xhtml_compress
00006 from plone.portlets.interfaces import IPortletDataProvider
00007 
00008 from zope.i18nmessageid import MessageFactory
00009 from zope.interface import implements
00010 
00011 from Acquisition import aq_inner
00012 from DateTime import DateTime
00013 from Products.CMFCore.utils import getToolByName
00014 from Products.CMFPlone import PloneMessageFactory as _
00015 from Products.CMFPlone.utils import safe_unicode
00016 from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
00017 from Products.PythonScripts.standard import url_quote_plus
00018 
00019 from plone.app.portlets import cache
00020 from plone.app.portlets.portlets import base
00021 
00022 PLMF = MessageFactory('plonelocales')
00023 
00024 
00025 class ICalendarPortlet(IPortletDataProvider):
00026     """A portlet displaying a calendar
00027     """
00028 
00029 
00030 class Assignment(base.Assignment):
00031     implements(ICalendarPortlet)
00032 
00033     title = _(u'Calendar')
00034 
00035 
00036 def _render_cachekey(fun, self):
00037     context = aq_inner(self.context)
00038     if not self.updated:
00039         self.update()
00040 
00041     if self.calendar.getUseSession():
00042         raise ram.DontCache()
00043     else:
00044         key = StringIO()
00045         print >> key, getToolByName(context, 'portal_url')()
00046         print >> key, cache.get_language(context, self.request)
00047         print >> key, self.calendar.getFirstWeekDay()
00048 
00049         year, month = self.getYearAndMonthToDisplay()
00050         print >> key, year
00051         print >> key, month
00052 
00053         start = DateTime('%s/%s/1' % (year, month))
00054         end = DateTime('%s/%s/1' % self.getNextMonth(year, month)) - 1
00055 
00056         def add(brain):
00057             key.write(brain.getPath())
00058             key.write('\n')
00059             key.write(brain.modified)
00060             key.write('\n\n')
00061 
00062         catalog = getToolByName(context, 'portal_catalog')
00063         brains = catalog(
00064             portal_type=self.calendar.getCalendarTypes(),
00065             review_state=self.calendar.getCalendarStates(),
00066             start={'query': end, 'range': 'max'},
00067             end={'query': start, 'range': 'min'})
00068 
00069         for brain in brains:
00070             add(brain)
00071 
00072         return key.getvalue()
00073 
00074 
00075 class Renderer(base.Renderer):
00076 
00077     _template = ViewPageTemplateFile('calendar.pt')
00078     updated = False
00079 
00080     def __init__(self, context, request, view, manager, data):
00081         base.Renderer.__init__(self, context, request, view, manager, data)
00082         self.updated = False
00083 
00084     def update(self):
00085         if self.updated:
00086             return
00087         self.updated = True
00088 
00089         context = aq_inner(self.context)
00090         self.calendar = getToolByName(context, 'portal_calendar')
00091         self._ts = getToolByName(context, 'translation_service')
00092         self.url_quote_plus = url_quote_plus
00093 
00094         self.now = localtime()
00095         self.yearmonth = yearmonth = self.getYearAndMonthToDisplay()
00096         self.year = year = yearmonth[0]
00097         self.month = month = yearmonth[1]
00098 
00099         self.showPrevMonth = yearmonth > (self.now[0]-1, self.now[1])
00100         self.showNextMonth = yearmonth < (self.now[0]+1, self.now[1])
00101 
00102         self.prevMonthYear, self.prevMonthMonth = self.getPreviousMonth(year, month)
00103         self.nextMonthYear, self.nextMonthMonth = self.getNextMonth(year, month)
00104 
00105         self.monthName = PLMF(self._ts.month_msgid(month),
00106                               default=self._ts.month_english(month))
00107 
00108     @ram.cache(_render_cachekey)
00109     def render(self):
00110         return xhtml_compress(self._template())
00111 
00112     def getEventsForCalendar(self):
00113         context = aq_inner(self.context)
00114         year = self.year
00115         month = self.month
00116         weeks = self.calendar.getEventsForCalendar(month, year)
00117         for week in weeks:
00118             for day in week:
00119                 daynumber = day['day']
00120                 if daynumber == 0:
00121                     continue
00122                 day['is_today'] = self.isToday(daynumber)
00123                 if day['event']:
00124                     cur_date = DateTime(year, month, daynumber)
00125                     localized_date = [self._ts.ulocalized_time(cur_date, context=context, request=self.request)]
00126                     day['eventstring'] = '\n'.join(localized_date+[self.getEventString(e) for e in day['eventslist']])
00127                     day['date_string'] = '%s-%s-%s' % (year, month, daynumber)
00128 
00129         return weeks
00130 
00131     def getEventString(self, event):
00132         start = event['start'] and ':'.join(event['start'].split(':')[:2]) or ''
00133         end = event['end'] and ':'.join(event['end'].split(':')[:2]) or ''
00134         title = safe_unicode(event['title']) or u'event'
00135 
00136         if start and end:
00137             eventstring = "%s-%s %s" % (start, end, title)
00138         elif start: # can assume not event['end']
00139             eventstring = "%s - %s" % (start, title)
00140         elif event['end']: # can assume not event['start']
00141             eventstring = "%s - %s" % (title, end)
00142         else: # can assume not event['start'] and not event['end']
00143             eventstring = title
00144 
00145         return eventstring
00146 
00147     def getYearAndMonthToDisplay(self):
00148         session = None
00149         request = self.request
00150 
00151         # First priority goes to the data in the REQUEST
00152         year = request.get('year', None)
00153         month = request.get('month', None)
00154 
00155         # Next get the data from the SESSION
00156         if self.calendar.getUseSession():
00157             session = request.get('SESSION', None)
00158             if session:
00159                 if not year:
00160                     year = session.get('calendar_year', None)
00161                 if not month:
00162                     month = session.get('calendar_month', None)
00163 
00164         # Last resort to today
00165         if not year:
00166             year = self.now[0]
00167         if not month:
00168             month = self.now[1]
00169 
00170         year, month = int(year), int(month)
00171 
00172         # Store the results in the session for next time
00173         if session:
00174             session.set('calendar_year', year)
00175             session.set('calendar_month', month)
00176 
00177         # Finally return the results
00178         return year, month
00179 
00180     def getPreviousMonth(self, year, month):
00181         if month==0 or month==1:
00182             month, year = 12, year - 1
00183         else:
00184             month-=1
00185         return (year, month)
00186 
00187     def getNextMonth(self, year, month):
00188         if month==12:
00189             month, year = 1, year + 1
00190         else:
00191             month+=1
00192         return (year, month)
00193 
00194     def getWeekdays(self):
00195         """Returns a list of Messages for the weekday names."""
00196         weekdays = []
00197         # list of ordered weekdays as numbers
00198         for day in self.calendar.getDayNumbers():
00199             weekdays.append(PLMF(self._ts.day_msgid(day, format='s'),
00200                                  default=self._ts.weekday_english(day, format='a')))
00201 
00202         return weekdays
00203 
00204     def isToday(self, day):
00205         """Returns True if the given day and the current month and year equals
00206            today, otherwise False.
00207         """
00208         return self.now[2]==day and self.now[1]==self.month and \
00209                self.now[0]==self.year
00210 
00211     def getReviewStateString(self):
00212         states = self.calendar.getCalendarStates()
00213         return ''.join(map(lambda x : 'review_state=%s&amp;' % self.url_quote_plus(x), states))
00214 
00215     def getQueryString(self):
00216         request = self.request
00217         query_string = request.get('orig_query',
00218                                    request.get('QUERY_STRING', None))
00219         if len(query_string) == 0:
00220             query_string = ''
00221         else:
00222             query_string = '%s&amp;' % query_string
00223         return query_string
00224 
00225 
00226 class AddForm(base.NullAddForm):
00227 
00228     def create(self):
00229         return Assignment()