paul@10 | 1 | # -*- coding: iso-8859-1 -*- |
paul@10 | 2 | """ |
paul@10 | 3 | MoinMoin - EventAggregator library |
paul@10 | 4 | |
paul@137 | 5 | @copyright: 2008, 2009, 2010, 2011 by Paul Boddie <paul@boddie.org.uk> |
paul@10 | 6 | @copyright: 2000-2004 Juergen Hermann <jh@web.de>, |
paul@10 | 7 | 2005-2008 MoinMoin:ThomasWaldmann. |
paul@10 | 8 | @license: GNU GPL (v2 or later), see COPYING.txt for details. |
paul@10 | 9 | """ |
paul@10 | 10 | |
paul@10 | 11 | from MoinMoin.Page import Page |
paul@10 | 12 | from MoinMoin import search, version |
paul@24 | 13 | from MoinMoin import wikiutil |
paul@10 | 14 | import calendar |
paul@11 | 15 | import datetime |
paul@24 | 16 | import time |
paul@10 | 17 | import re |
paul@122 | 18 | import bisect |
paul@185 | 19 | import operator |
paul@10 | 20 | |
paul@69 | 21 | try: |
paul@69 | 22 | set |
paul@69 | 23 | except NameError: |
paul@69 | 24 | from sets import Set as set |
paul@69 | 25 | |
paul@100 | 26 | try: |
paul@100 | 27 | import pytz |
paul@100 | 28 | except ImportError: |
paul@100 | 29 | pytz = None |
paul@100 | 30 | |
paul@137 | 31 | escape = wikiutil.escape |
paul@137 | 32 | |
paul@109 | 33 | __version__ = "0.7" |
paul@10 | 34 | |
paul@22 | 35 | # Date labels. |
paul@22 | 36 | |
paul@22 | 37 | month_labels = ["January", "February", "March", "April", "May", "June", |
paul@22 | 38 | "July", "August", "September", "October", "November", "December"] |
paul@22 | 39 | weekday_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
paul@22 | 40 | |
paul@10 | 41 | # Regular expressions where MoinMoin does not provide the required support. |
paul@10 | 42 | |
paul@10 | 43 | category_regexp = None |
paul@47 | 44 | |
paul@47 | 45 | # Page parsing. |
paul@47 | 46 | |
paul@84 | 47 | definition_list_regexp = re.compile(ur'(?P<wholeterm>^(?P<optcomment>#*)\s+(?P<term>.*?):: )(?P<desc>.*?)$', re.UNICODE | re.MULTILINE) |
paul@158 | 48 | category_membership_regexp = re.compile(ur"^\s*(?:(Category\S+)(?:\s+(Category\S+))*)\s*$", re.MULTILINE | re.UNICODE) |
paul@47 | 49 | |
paul@47 | 50 | # Value parsing. |
paul@47 | 51 | |
paul@93 | 52 | country_code_regexp = re.compile(ur'(?:^|\W)(?P<code>[A-Z]{2})(?:$|\W+$)', re.UNICODE) |
paul@202 | 53 | location_normalised_regexp = re.compile( |
paul@202 | 54 | ur"(?:\d+\w*\s+)?" # preceding postcode (optional) |
paul@202 | 55 | ur"(?P<location>" # start of group of interest |
paul@202 | 56 | ur"\w[\w\s-]+?" # area or town |
paul@202 | 57 | ur"(?:,(?:\s*[\w-]+)+)?" # country (optional) |
paul@202 | 58 | ur")$", re.UNICODE) |
paul@92 | 59 | |
paul@92 | 60 | month_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})' |
paul@92 | 61 | date_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})' |
paul@92 | 62 | time_regexp_str = ur'(?P<hour>[0-2][0-9]):(?P<minute>[0-5][0-9])(?::(?P<second>[0-6][0-9]))?' |
paul@98 | 63 | timezone_offset_str = ur'(?P<offset>(UTC)?(?:(?P<sign>[-+])(?P<hours>[0-9]{2})(?::?(?P<minutes>[0-9]{2}))?))' |
paul@98 | 64 | timezone_olson_str = ur'(?P<olson>[a-zA-Z]+(?:/[-_a-zA-Z]+){1,2})' |
paul@98 | 65 | timezone_utc_str = ur'UTC' |
paul@98 | 66 | timezone_regexp_str = ur'(?P<zone>' + timezone_offset_str + '|' + timezone_olson_str + '|' + timezone_utc_str + ')' |
paul@92 | 67 | datetime_regexp_str = date_regexp_str + ur'(?:\s+' + time_regexp_str + ur'(?:\s+' + timezone_regexp_str + ur')?)?' |
paul@92 | 68 | |
paul@92 | 69 | month_regexp = re.compile(month_regexp_str, re.UNICODE) |
paul@92 | 70 | date_regexp = re.compile(date_regexp_str, re.UNICODE) |
paul@92 | 71 | time_regexp = re.compile(time_regexp_str, re.UNICODE) |
paul@92 | 72 | datetime_regexp = re.compile(datetime_regexp_str, re.UNICODE) |
paul@100 | 73 | timezone_olson_regexp = re.compile(timezone_olson_str, re.UNICODE) |
paul@94 | 74 | timezone_offset_regexp = re.compile(timezone_offset_str, re.UNICODE) |
paul@92 | 75 | |
paul@19 | 76 | verbatim_regexp = re.compile(ur'(?:' |
paul@19 | 77 | ur'<<Verbatim\((?P<verbatim>.*?)\)>>' |
paul@19 | 78 | ur'|' |
paul@19 | 79 | ur'\[\[Verbatim\((?P<verbatim2>.*?)\)\]\]' |
paul@19 | 80 | ur'|' |
paul@191 | 81 | ur'!(?P<verbatim3>.*?)(\s|$)?' |
paul@191 | 82 | ur'|' |
paul@19 | 83 | ur'`(?P<monospace>.*?)`' |
paul@19 | 84 | ur'|' |
paul@19 | 85 | ur'{{{(?P<preformatted>.*?)}}}' |
paul@19 | 86 | ur')', re.UNICODE) |
paul@10 | 87 | |
paul@10 | 88 | # Utility functions. |
paul@10 | 89 | |
paul@10 | 90 | def getCategoryPattern(request): |
paul@10 | 91 | global category_regexp |
paul@10 | 92 | |
paul@10 | 93 | try: |
paul@10 | 94 | return request.cfg.cache.page_category_regexact |
paul@10 | 95 | except AttributeError: |
paul@10 | 96 | |
paul@10 | 97 | # Use regular expression from MoinMoin 1.7.1 otherwise. |
paul@10 | 98 | |
paul@10 | 99 | if category_regexp is None: |
paul@10 | 100 | category_regexp = re.compile(u'^%s$' % ur'(?P<all>Category(?P<key>(?!Template)\S+))', re.UNICODE) |
paul@10 | 101 | return category_regexp |
paul@10 | 102 | |
paul@92 | 103 | def int_or_none(x): |
paul@92 | 104 | if x is None: |
paul@92 | 105 | return x |
paul@92 | 106 | else: |
paul@92 | 107 | return int(x) |
paul@92 | 108 | |
paul@118 | 109 | def sort_none_first(x, y): |
paul@118 | 110 | if x is None: |
paul@118 | 111 | return -1 |
paul@118 | 112 | elif y is None: |
paul@118 | 113 | return 1 |
paul@118 | 114 | else: |
paul@118 | 115 | return cmp(x, y) |
paul@118 | 116 | |
paul@195 | 117 | def sort_start_first(x, y): |
paul@195 | 118 | x_ts = x.as_limits() |
paul@195 | 119 | if x_ts is not None: |
paul@195 | 120 | x_start, x_end = x_ts |
paul@195 | 121 | y_ts = y.as_limits() |
paul@195 | 122 | if y_ts is not None: |
paul@195 | 123 | y_start, y_end = y_ts |
paul@195 | 124 | start_order = cmp(x_start, y_start) |
paul@195 | 125 | if start_order == 0: |
paul@195 | 126 | return cmp(x_end, y_end) |
paul@195 | 127 | else: |
paul@195 | 128 | return start_order |
paul@195 | 129 | return 0 |
paul@195 | 130 | |
paul@184 | 131 | def sign(x): |
paul@184 | 132 | if x < 0: |
paul@184 | 133 | return -1 |
paul@184 | 134 | else: |
paul@184 | 135 | return 1 |
paul@184 | 136 | |
paul@109 | 137 | # Utility classes and associated functions. |
paul@109 | 138 | |
paul@109 | 139 | class Form: |
paul@109 | 140 | |
paul@109 | 141 | """ |
paul@109 | 142 | A wrapper preserving MoinMoin 1.8.x (and earlier) behaviour in a 1.9.x |
paul@109 | 143 | environment. |
paul@109 | 144 | """ |
paul@109 | 145 | |
paul@109 | 146 | def __init__(self, form): |
paul@109 | 147 | self.form = form |
paul@109 | 148 | |
paul@110 | 149 | def get(self, name, default=None): |
paul@109 | 150 | values = self.form.getlist(name) |
paul@109 | 151 | if not values: |
paul@110 | 152 | return default |
paul@109 | 153 | else: |
paul@109 | 154 | return values |
paul@109 | 155 | |
paul@109 | 156 | def __getitem__(self, name): |
paul@109 | 157 | return self.form.getlist(name) |
paul@109 | 158 | |
paul@109 | 159 | class ActionSupport: |
paul@109 | 160 | |
paul@112 | 161 | """ |
paul@112 | 162 | Work around disruptive MoinMoin changes in 1.9, and also provide useful |
paul@112 | 163 | convenience methods. |
paul@112 | 164 | """ |
paul@109 | 165 | |
paul@109 | 166 | def get_form(self): |
paul@109 | 167 | return get_form(self.request) |
paul@109 | 168 | |
paul@112 | 169 | def _get_selected(self, value, input_value): |
paul@112 | 170 | |
paul@112 | 171 | """ |
paul@112 | 172 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 173 | otherwise) if 'value' matches 'input_value'. |
paul@112 | 174 | """ |
paul@112 | 175 | |
paul@112 | 176 | return input_value is not None and value == input_value and 'selected="selected"' or '' |
paul@112 | 177 | |
paul@112 | 178 | def _get_selected_for_list(self, value, input_values): |
paul@112 | 179 | |
paul@112 | 180 | """ |
paul@112 | 181 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 182 | otherwise) if 'value' matches one of the 'input_values'. |
paul@112 | 183 | """ |
paul@112 | 184 | |
paul@112 | 185 | return value in input_values and 'selected="selected"' or '' |
paul@112 | 186 | |
paul@112 | 187 | def _get_input(self, form, name, default=None): |
paul@112 | 188 | |
paul@112 | 189 | """ |
paul@112 | 190 | Return the input from 'form' having the given 'name', returning either |
paul@112 | 191 | the input converted to an integer or the given 'default' (optional, None |
paul@112 | 192 | if not specified). |
paul@112 | 193 | """ |
paul@112 | 194 | |
paul@112 | 195 | value = form.get(name, [None])[0] |
paul@112 | 196 | if not value: # true if 0 obtained |
paul@112 | 197 | return default |
paul@112 | 198 | else: |
paul@112 | 199 | return int(value) |
paul@112 | 200 | |
paul@114 | 201 | def get_month_lists(self, default_as_current=0): |
paul@112 | 202 | |
paul@112 | 203 | """ |
paul@112 | 204 | Return two lists of HTML element definitions corresponding to the start |
paul@112 | 205 | and end month selection controls, with months selected according to any |
paul@112 | 206 | values that have been specified via request parameters. |
paul@112 | 207 | """ |
paul@112 | 208 | |
paul@112 | 209 | _ = self._ |
paul@112 | 210 | form = self.get_form() |
paul@112 | 211 | |
paul@112 | 212 | # Initialise month lists. |
paul@112 | 213 | |
paul@112 | 214 | start_month_list = [] |
paul@112 | 215 | end_month_list = [] |
paul@112 | 216 | |
paul@114 | 217 | start_month = self._get_input(form, "start-month", default_as_current and getCurrentMonth().month() or None) |
paul@112 | 218 | end_month = self._get_input(form, "end-month", start_month) |
paul@112 | 219 | |
paul@112 | 220 | # Prepare month lists, selecting specified months. |
paul@112 | 221 | |
paul@114 | 222 | if not default_as_current: |
paul@114 | 223 | start_month_list.append('<option value=""></option>') |
paul@114 | 224 | end_month_list.append('<option value=""></option>') |
paul@114 | 225 | |
paul@112 | 226 | for month in range(1, 13): |
paul@136 | 227 | month_label = escape(_(getMonthLabel(month))) |
paul@112 | 228 | selected = self._get_selected(month, start_month) |
paul@112 | 229 | start_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 230 | selected = self._get_selected(month, end_month) |
paul@112 | 231 | end_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 232 | |
paul@112 | 233 | return start_month_list, end_month_list |
paul@112 | 234 | |
paul@114 | 235 | def get_year_defaults(self, default_as_current=0): |
paul@112 | 236 | |
paul@112 | 237 | "Return defaults for the start and end years." |
paul@112 | 238 | |
paul@112 | 239 | form = self.get_form() |
paul@112 | 240 | |
paul@114 | 241 | start_year_default = form.get("start-year", [default_as_current and getCurrentYear() or ""])[0] |
paul@114 | 242 | end_year_default = form.get("end-year", [default_as_current and start_year_default or ""])[0] |
paul@112 | 243 | |
paul@112 | 244 | return start_year_default, end_year_default |
paul@112 | 245 | |
paul@127 | 246 | def get_day_defaults(self, default_as_current=0): |
paul@127 | 247 | |
paul@127 | 248 | "Return defaults for the start and end days." |
paul@127 | 249 | |
paul@127 | 250 | form = self.get_form() |
paul@127 | 251 | |
paul@127 | 252 | start_day_default = form.get("start-day", [default_as_current and getCurrentDate().day() or ""])[0] |
paul@127 | 253 | end_day_default = form.get("end-day", [default_as_current and start_day_default or ""])[0] |
paul@127 | 254 | |
paul@127 | 255 | return start_day_default, end_day_default |
paul@127 | 256 | |
paul@109 | 257 | def get_form(request): |
paul@109 | 258 | |
paul@109 | 259 | "Work around disruptive MoinMoin changes in 1.9." |
paul@109 | 260 | |
paul@109 | 261 | if hasattr(request, "values"): |
paul@109 | 262 | return Form(request.values) |
paul@109 | 263 | else: |
paul@109 | 264 | return request.form |
paul@109 | 265 | |
paul@180 | 266 | class send_headers_cls: |
paul@110 | 267 | |
paul@110 | 268 | """ |
paul@110 | 269 | A wrapper to preserve MoinMoin 1.8.x (and earlier) request behaviour in a |
paul@110 | 270 | 1.9.x environment. |
paul@110 | 271 | """ |
paul@110 | 272 | |
paul@110 | 273 | def __init__(self, request): |
paul@110 | 274 | self.request = request |
paul@110 | 275 | |
paul@110 | 276 | def __call__(self, headers): |
paul@110 | 277 | for header in headers: |
paul@110 | 278 | parts = header.split(":") |
paul@110 | 279 | self.request.headers.add(parts[0], ":".join(parts[1:])) |
paul@110 | 280 | |
paul@136 | 281 | def escattr(s): |
paul@136 | 282 | return escape(s, 1) |
paul@136 | 283 | |
paul@67 | 284 | # Textual representations. |
paul@67 | 285 | |
paul@67 | 286 | def getHTTPTimeString(tmtuple): |
paul@67 | 287 | return "%s, %02d %s %04d %02d:%02d:%02d GMT" % ( |
paul@129 | 288 | getDayLabel(tmtuple.tm_wday), |
paul@67 | 289 | tmtuple.tm_mday, |
paul@129 | 290 | getMonthLabel(tmtuple.tm_mon), |
paul@67 | 291 | tmtuple.tm_year, |
paul@67 | 292 | tmtuple.tm_hour, |
paul@67 | 293 | tmtuple.tm_min, |
paul@67 | 294 | tmtuple.tm_sec |
paul@67 | 295 | ) |
paul@67 | 296 | |
paul@67 | 297 | def getSimpleWikiText(text): |
paul@67 | 298 | |
paul@67 | 299 | """ |
paul@67 | 300 | Return the plain text representation of the given 'text' which may employ |
paul@67 | 301 | certain Wiki syntax features, such as those providing verbatim or monospaced |
paul@67 | 302 | text. |
paul@67 | 303 | """ |
paul@67 | 304 | |
paul@67 | 305 | # NOTE: Re-implementing support for verbatim text and linking avoidance. |
paul@67 | 306 | |
paul@67 | 307 | return "".join([s for s in verbatim_regexp.split(text) if s is not None]) |
paul@67 | 308 | |
paul@67 | 309 | def getEncodedWikiText(text): |
paul@67 | 310 | |
paul@67 | 311 | "Encode the given 'text' in a verbatim representation." |
paul@67 | 312 | |
paul@67 | 313 | return "<<Verbatim(%s)>>" % text |
paul@67 | 314 | |
paul@67 | 315 | def getPrettyTitle(title): |
paul@67 | 316 | |
paul@67 | 317 | "Return a nicely formatted version of the given 'title'." |
paul@67 | 318 | |
paul@67 | 319 | return title.replace("_", " ").replace("/", u" ? ") |
paul@67 | 320 | |
paul@67 | 321 | def getMonthLabel(month): |
paul@67 | 322 | |
paul@67 | 323 | "Return an unlocalised label for the given 'month'." |
paul@67 | 324 | |
paul@67 | 325 | return month_labels[month - 1] # zero-based labels |
paul@67 | 326 | |
paul@67 | 327 | def getDayLabel(weekday): |
paul@67 | 328 | |
paul@67 | 329 | "Return an unlocalised label for the given 'weekday'." |
paul@67 | 330 | |
paul@67 | 331 | return weekday_labels[weekday] |
paul@67 | 332 | |
paul@189 | 333 | def getNormalisedLocation(location): |
paul@189 | 334 | |
paul@189 | 335 | """ |
paul@189 | 336 | Attempt to return a normalised 'location' of the form "<town>, <country>" or |
paul@189 | 337 | "<town>". |
paul@189 | 338 | """ |
paul@189 | 339 | |
paul@189 | 340 | match = location_normalised_regexp.search(location) |
paul@189 | 341 | if match: |
paul@202 | 342 | return match.group("location") |
paul@189 | 343 | else: |
paul@189 | 344 | return None |
paul@189 | 345 | |
paul@201 | 346 | def getLocationPosition(location, locations): |
paul@201 | 347 | |
paul@201 | 348 | """ |
paul@201 | 349 | Attempt to return the position of the given 'location' using the 'locations' |
paul@201 | 350 | dictionary provided. If no position can be found, return a latitude of None |
paul@201 | 351 | and a longitude of None. |
paul@201 | 352 | """ |
paul@201 | 353 | |
paul@201 | 354 | latitude, longitude = None, None |
paul@201 | 355 | |
paul@201 | 356 | if location is not None: |
paul@201 | 357 | try: |
paul@201 | 358 | latitude, longitude = map(getMapReference, locations[location].split()) |
paul@201 | 359 | except (KeyError, ValueError): |
paul@201 | 360 | pass |
paul@201 | 361 | |
paul@201 | 362 | return latitude, longitude |
paul@201 | 363 | |
paul@19 | 364 | # Action support functions. |
paul@19 | 365 | |
paul@67 | 366 | def getPageRevision(page): |
paul@67 | 367 | |
paul@67 | 368 | "Return the revision details dictionary for the given 'page'." |
paul@67 | 369 | |
paul@67 | 370 | # From Page.edit_info... |
paul@67 | 371 | |
paul@67 | 372 | if hasattr(page, "editlog_entry"): |
paul@67 | 373 | line = page.editlog_entry() |
paul@67 | 374 | else: |
paul@67 | 375 | line = page._last_edited(page.request) # MoinMoin 1.5.x and 1.6.x |
paul@67 | 376 | |
paul@89 | 377 | # Similar to Page.mtime_usecs behaviour... |
paul@89 | 378 | |
paul@89 | 379 | if line: |
paul@89 | 380 | timestamp = line.ed_time_usecs |
paul@89 | 381 | mtime = wikiutil.version2timestamp(long(timestamp)) # must be long for py 2.2.x |
paul@89 | 382 | comment = line.comment |
paul@89 | 383 | else: |
paul@89 | 384 | mtime = 0 |
paul@89 | 385 | comment = "" |
paul@89 | 386 | |
paul@89 | 387 | return {"timestamp" : time.gmtime(mtime), "comment" : comment} |
paul@67 | 388 | |
paul@67 | 389 | # Category discovery and searching. |
paul@67 | 390 | |
paul@19 | 391 | def getCategories(request): |
paul@19 | 392 | |
paul@19 | 393 | """ |
paul@19 | 394 | From the AdvancedSearch macro, return a list of category page names using |
paul@19 | 395 | the given 'request'. |
paul@19 | 396 | """ |
paul@19 | 397 | |
paul@19 | 398 | # This will return all pages with "Category" in the title. |
paul@19 | 399 | |
paul@19 | 400 | cat_filter = getCategoryPattern(request).search |
paul@19 | 401 | return request.rootpage.getPageList(filter=cat_filter) |
paul@19 | 402 | |
paul@19 | 403 | def getCategoryMapping(category_pagenames, request): |
paul@19 | 404 | |
paul@19 | 405 | """ |
paul@19 | 406 | For the given 'category_pagenames' return a list of tuples of the form |
paul@19 | 407 | (category name, category page name) using the given 'request'. |
paul@19 | 408 | """ |
paul@19 | 409 | |
paul@19 | 410 | cat_pattern = getCategoryPattern(request) |
paul@19 | 411 | mapping = [] |
paul@19 | 412 | for pagename in category_pagenames: |
paul@19 | 413 | name = cat_pattern.match(pagename).group("key") |
paul@19 | 414 | if name != "Category": |
paul@19 | 415 | mapping.append((name, pagename)) |
paul@19 | 416 | mapping.sort() |
paul@19 | 417 | return mapping |
paul@19 | 418 | |
paul@67 | 419 | def getCategoryPages(pagename, request): |
paul@29 | 420 | |
paul@67 | 421 | """ |
paul@67 | 422 | Return the pages associated with the given category 'pagename' using the |
paul@67 | 423 | 'request'. |
paul@67 | 424 | """ |
paul@10 | 425 | |
paul@10 | 426 | query = search.QueryParser().parse_query('category:%s' % pagename) |
paul@117 | 427 | results = search.searchPages(request, query, "page_name") |
paul@10 | 428 | |
paul@10 | 429 | cat_pattern = getCategoryPattern(request) |
paul@10 | 430 | pages = [] |
paul@10 | 431 | for page in results.hits: |
paul@10 | 432 | if not cat_pattern.match(page.page_name): |
paul@10 | 433 | pages.append(page) |
paul@10 | 434 | return pages |
paul@10 | 435 | |
paul@168 | 436 | def getAllCategoryPages(category_names, request): |
paul@168 | 437 | |
paul@168 | 438 | """ |
paul@168 | 439 | Return all pages belonging to the categories having the given |
paul@168 | 440 | 'category_names', using the given 'request'. |
paul@168 | 441 | """ |
paul@168 | 442 | |
paul@168 | 443 | pages = [] |
paul@168 | 444 | pagenames = set() |
paul@168 | 445 | |
paul@168 | 446 | for category_name in category_names: |
paul@168 | 447 | |
paul@168 | 448 | # Get the pages and page names in the category. |
paul@168 | 449 | |
paul@168 | 450 | pages_in_category = getCategoryPages(category_name, request) |
paul@168 | 451 | |
paul@168 | 452 | # Visit each page in the category. |
paul@168 | 453 | |
paul@168 | 454 | for page_in_category in pages_in_category: |
paul@168 | 455 | pagename = page_in_category.page_name |
paul@168 | 456 | |
paul@168 | 457 | # Only process each page once. |
paul@168 | 458 | |
paul@168 | 459 | if pagename in pagenames: |
paul@168 | 460 | continue |
paul@168 | 461 | else: |
paul@168 | 462 | pagenames.add(pagename) |
paul@168 | 463 | |
paul@168 | 464 | pages.append(page_in_category) |
paul@168 | 465 | |
paul@168 | 466 | return pages |
paul@168 | 467 | |
paul@168 | 468 | def getPagesFromResults(result_pages, request): |
paul@168 | 469 | |
paul@168 | 470 | "Return genuine pages for the given 'result_pages' using the 'request'." |
paul@168 | 471 | |
paul@168 | 472 | return [Page(request, page.page_name) for page in result_pages] |
paul@168 | 473 | |
paul@168 | 474 | # Interfaces. |
paul@168 | 475 | |
paul@168 | 476 | class ActsAsTimespan: |
paul@168 | 477 | pass |
paul@168 | 478 | |
paul@67 | 479 | # The main activity functions. |
paul@67 | 480 | |
paul@67 | 481 | class EventPage: |
paul@67 | 482 | |
paul@67 | 483 | "An event page." |
paul@67 | 484 | |
paul@67 | 485 | def __init__(self, page): |
paul@67 | 486 | self.page = page |
paul@69 | 487 | self.events = None |
paul@67 | 488 | self.body = None |
paul@67 | 489 | self.categories = None |
paul@67 | 490 | |
paul@67 | 491 | def copyPage(self, page): |
paul@67 | 492 | |
paul@67 | 493 | "Copy the body of the given 'page'." |
paul@67 | 494 | |
paul@67 | 495 | self.body = page.getBody() |
paul@67 | 496 | |
paul@67 | 497 | def getPageURL(self, request): |
paul@67 | 498 | |
paul@67 | 499 | "Using 'request', return the URL of this page." |
paul@24 | 500 | |
paul@117 | 501 | return request.getQualifiedURL(self.page.url(request, relative=0)) |
paul@67 | 502 | |
paul@67 | 503 | def getFormat(self): |
paul@67 | 504 | |
paul@67 | 505 | "Get the format used on this page." |
paul@24 | 506 | |
paul@117 | 507 | return self.page.pi["format"] |
paul@67 | 508 | |
paul@67 | 509 | def getRevisions(self): |
paul@67 | 510 | |
paul@67 | 511 | "Return a list of page revisions." |
paul@67 | 512 | |
paul@67 | 513 | return self.page.getRevList() |
paul@67 | 514 | |
paul@67 | 515 | def getPageRevision(self): |
paul@24 | 516 | |
paul@67 | 517 | "Return the revision details dictionary for this page." |
paul@67 | 518 | |
paul@67 | 519 | return getPageRevision(self.page) |
paul@67 | 520 | |
paul@67 | 521 | def getPageName(self): |
paul@67 | 522 | |
paul@67 | 523 | "Return the page name." |
paul@67 | 524 | |
paul@67 | 525 | return self.page.page_name |
paul@24 | 526 | |
paul@67 | 527 | def getPrettyPageName(self): |
paul@67 | 528 | |
paul@67 | 529 | "Return a nicely formatted title/name for this page." |
paul@67 | 530 | |
paul@67 | 531 | return getPrettyPageName(self.page) |
paul@67 | 532 | |
paul@67 | 533 | def getBody(self): |
paul@67 | 534 | |
paul@67 | 535 | "Get the current page body." |
paul@47 | 536 | |
paul@67 | 537 | if self.body is None: |
paul@67 | 538 | self.body = self.page.get_raw_body() |
paul@67 | 539 | return self.body |
paul@67 | 540 | |
paul@69 | 541 | def getEvents(self): |
paul@69 | 542 | |
paul@69 | 543 | "Return a list of events from this page." |
paul@67 | 544 | |
paul@69 | 545 | if self.events is None: |
paul@69 | 546 | details = {} |
paul@69 | 547 | self.events = [Event(self, details)] |
paul@47 | 548 | |
paul@67 | 549 | if self.getFormat() == "wiki": |
paul@67 | 550 | for match in definition_list_regexp.finditer(self.getBody()): |
paul@67 | 551 | |
paul@67 | 552 | # Skip commented-out items. |
paul@47 | 553 | |
paul@67 | 554 | if match.group("optcomment"): |
paul@67 | 555 | continue |
paul@67 | 556 | |
paul@67 | 557 | # Permit case-insensitive list terms. |
paul@67 | 558 | |
paul@67 | 559 | term = match.group("term").lower() |
paul@67 | 560 | desc = match.group("desc") |
paul@67 | 561 | |
paul@67 | 562 | # Special value type handling. |
paul@27 | 563 | |
paul@67 | 564 | # Dates. |
paul@67 | 565 | |
paul@67 | 566 | if term in ("start", "end"): |
paul@123 | 567 | desc = getDateTime(desc) |
paul@67 | 568 | |
paul@67 | 569 | # Lists (whose elements may be quoted). |
paul@67 | 570 | |
paul@67 | 571 | elif term in ("topics", "categories"): |
paul@84 | 572 | desc = [getSimpleWikiText(value.strip()) for value in desc.split(",") if value.strip()] |
paul@67 | 573 | |
paul@67 | 574 | # Labels which may well be quoted. |
paul@67 | 575 | |
paul@92 | 576 | elif term in ("title", "summary", "description", "location"): |
paul@179 | 577 | desc = getSimpleWikiText(desc.strip()) |
paul@67 | 578 | |
paul@67 | 579 | if desc is not None: |
paul@69 | 580 | |
paul@69 | 581 | # Handle apparent duplicates by creating a new set of |
paul@69 | 582 | # details. |
paul@69 | 583 | |
paul@69 | 584 | if details.has_key(term): |
paul@92 | 585 | |
paul@92 | 586 | # Make a new event. |
paul@92 | 587 | |
paul@69 | 588 | details = {} |
paul@69 | 589 | self.events.append(Event(self, details)) |
paul@67 | 590 | |
paul@69 | 591 | details[term] = desc |
paul@69 | 592 | |
paul@69 | 593 | return self.events |
paul@69 | 594 | |
paul@69 | 595 | def setEvents(self, events): |
paul@69 | 596 | |
paul@69 | 597 | "Set the given 'events' on this page." |
paul@69 | 598 | |
paul@69 | 599 | self.events = events |
paul@67 | 600 | |
paul@67 | 601 | def getCategoryMembership(self): |
paul@27 | 602 | |
paul@67 | 603 | "Get the category names from this page." |
paul@67 | 604 | |
paul@67 | 605 | if self.categories is None: |
paul@67 | 606 | body = self.getBody() |
paul@67 | 607 | match = category_membership_regexp.search(body) |
paul@158 | 608 | self.categories = match and [x for x in match.groups() if x] or [] |
paul@67 | 609 | |
paul@67 | 610 | return self.categories |
paul@67 | 611 | |
paul@67 | 612 | def setCategoryMembership(self, category_names): |
paul@10 | 613 | |
paul@67 | 614 | """ |
paul@67 | 615 | Set the category membership for the page using the specified |
paul@67 | 616 | 'category_names'. |
paul@67 | 617 | """ |
paul@67 | 618 | |
paul@67 | 619 | self.categories = category_names |
paul@67 | 620 | |
paul@67 | 621 | def flushEventDetails(self): |
paul@67 | 622 | |
paul@67 | 623 | "Flush the current event details to this page's body text." |
paul@10 | 624 | |
paul@67 | 625 | new_body_parts = [] |
paul@67 | 626 | end_of_last_match = 0 |
paul@67 | 627 | body = self.getBody() |
paul@69 | 628 | |
paul@69 | 629 | events = iter(self.getEvents()) |
paul@69 | 630 | |
paul@69 | 631 | event = events.next() |
paul@69 | 632 | event_details = event.getDetails() |
paul@69 | 633 | replaced_terms = set() |
paul@67 | 634 | |
paul@67 | 635 | for match in definition_list_regexp.finditer(body): |
paul@47 | 636 | |
paul@10 | 637 | # Permit case-insensitive list terms. |
paul@10 | 638 | |
paul@10 | 639 | term = match.group("term").lower() |
paul@10 | 640 | desc = match.group("desc") |
paul@10 | 641 | |
paul@69 | 642 | # Check that the term has not already been substituted. If so, |
paul@69 | 643 | # get the next event. |
paul@69 | 644 | |
paul@69 | 645 | if term in replaced_terms: |
paul@69 | 646 | try: |
paul@69 | 647 | event = events.next() |
paul@69 | 648 | |
paul@69 | 649 | # No more events. |
paul@69 | 650 | |
paul@69 | 651 | except StopIteration: |
paul@69 | 652 | break |
paul@69 | 653 | |
paul@69 | 654 | event_details = event.getDetails() |
paul@69 | 655 | replaced_terms = set() |
paul@69 | 656 | |
paul@75 | 657 | # Add preceding text to the new body. |
paul@75 | 658 | |
paul@75 | 659 | new_body_parts.append(body[end_of_last_match:match.start()]) |
paul@75 | 660 | |
paul@75 | 661 | # Get the matching regions, adding the term to the new body. |
paul@75 | 662 | |
paul@75 | 663 | new_body_parts.append(match.group("wholeterm")) |
paul@75 | 664 | |
paul@10 | 665 | # Special value type handling. |
paul@10 | 666 | |
paul@67 | 667 | if event_details.has_key(term): |
paul@19 | 668 | |
paul@67 | 669 | # Dates. |
paul@47 | 670 | |
paul@67 | 671 | if term in ("start", "end"): |
paul@67 | 672 | desc = desc.replace("YYYY-MM-DD", str(event_details[term])) |
paul@47 | 673 | |
paul@67 | 674 | # Lists (whose elements may be quoted). |
paul@47 | 675 | |
paul@67 | 676 | elif term in ("topics", "categories"): |
paul@92 | 677 | desc = ", ".join([getEncodedWikiText(item) for item in event_details[term]]) |
paul@47 | 678 | |
paul@92 | 679 | # Labels which must be quoted. |
paul@47 | 680 | |
paul@67 | 681 | elif term in ("title", "summary"): |
paul@67 | 682 | desc = getEncodedWikiText(event_details[term]) |
paul@47 | 683 | |
paul@67 | 684 | # Text which need not be quoted, but it will be Wiki text. |
paul@55 | 685 | |
paul@92 | 686 | elif term in ("description", "link", "location"): |
paul@67 | 687 | desc = event_details[term] |
paul@55 | 688 | |
paul@69 | 689 | replaced_terms.add(term) |
paul@69 | 690 | |
paul@75 | 691 | # Add the replaced value. |
paul@75 | 692 | |
paul@67 | 693 | new_body_parts.append(desc) |
paul@10 | 694 | |
paul@69 | 695 | # Remember where in the page has been processed. |
paul@69 | 696 | |
paul@69 | 697 | end_of_last_match = match.end() |
paul@69 | 698 | |
paul@69 | 699 | # Write the rest of the page. |
paul@69 | 700 | |
paul@69 | 701 | new_body_parts.append(body[end_of_last_match:]) |
paul@10 | 702 | |
paul@67 | 703 | self.body = "".join(new_body_parts) |
paul@11 | 704 | |
paul@67 | 705 | def flushCategoryMembership(self): |
paul@17 | 706 | |
paul@67 | 707 | "Flush the category membership to the page body." |
paul@11 | 708 | |
paul@67 | 709 | body = self.getBody() |
paul@67 | 710 | category_names = self.getCategoryMembership() |
paul@67 | 711 | match = category_membership_regexp.search(body) |
paul@10 | 712 | |
paul@67 | 713 | if match: |
paul@67 | 714 | self.body = "".join([body[:match.start()], " ".join(category_names), body[match.end():]]) |
paul@10 | 715 | |
paul@67 | 716 | def saveChanges(self): |
paul@10 | 717 | |
paul@67 | 718 | "Save changes to the event." |
paul@10 | 719 | |
paul@67 | 720 | self.flushEventDetails() |
paul@67 | 721 | self.flushCategoryMembership() |
paul@67 | 722 | self.page.saveText(self.getBody(), 0) |
paul@10 | 723 | |
paul@67 | 724 | def linkToPage(self, request, text, query_string=None): |
paul@11 | 725 | |
paul@67 | 726 | """ |
paul@67 | 727 | Using 'request', return a link to this page with the given link 'text' |
paul@67 | 728 | and optional 'query_string'. |
paul@67 | 729 | """ |
paul@11 | 730 | |
paul@67 | 731 | return linkToPage(request, self.page, text, query_string) |
paul@13 | 732 | |
paul@130 | 733 | class Event(ActsAsTimespan): |
paul@69 | 734 | |
paul@69 | 735 | "A description of an event." |
paul@69 | 736 | |
paul@69 | 737 | def __init__(self, page, details): |
paul@69 | 738 | self.page = page |
paul@69 | 739 | self.details = details |
paul@69 | 740 | |
paul@170 | 741 | def __repr__(self): |
paul@170 | 742 | return "<Event %r %r>" % (self.getSummary(), self.as_limits()) |
paul@170 | 743 | |
paul@128 | 744 | def __hash__(self): |
paul@128 | 745 | return hash(self.getSummary()) |
paul@69 | 746 | |
paul@69 | 747 | def getPage(self): |
paul@69 | 748 | |
paul@69 | 749 | "Return the page describing this event." |
paul@69 | 750 | |
paul@69 | 751 | return self.page |
paul@69 | 752 | |
paul@69 | 753 | def setPage(self, page): |
paul@69 | 754 | |
paul@69 | 755 | "Set the 'page' describing this event." |
paul@69 | 756 | |
paul@69 | 757 | self.page = page |
paul@69 | 758 | |
paul@69 | 759 | def getSummary(self, event_parent=None): |
paul@69 | 760 | |
paul@69 | 761 | """ |
paul@69 | 762 | Return either the given title or summary of the event according to the |
paul@69 | 763 | event details, or a summary made from using the pretty version of the |
paul@69 | 764 | page name. |
paul@69 | 765 | |
paul@69 | 766 | If the optional 'event_parent' is specified, any page beneath the given |
paul@69 | 767 | 'event_parent' page in the page hierarchy will omit this parent information |
paul@69 | 768 | if its name is used as the summary. |
paul@69 | 769 | """ |
paul@69 | 770 | |
paul@69 | 771 | event_details = self.details |
paul@69 | 772 | |
paul@69 | 773 | if event_details.has_key("title"): |
paul@69 | 774 | return event_details["title"] |
paul@69 | 775 | elif event_details.has_key("summary"): |
paul@69 | 776 | return event_details["summary"] |
paul@69 | 777 | else: |
paul@69 | 778 | # If appropriate, remove the parent details and "/" character. |
paul@69 | 779 | |
paul@69 | 780 | title = self.page.getPageName() |
paul@69 | 781 | |
paul@74 | 782 | if event_parent and title.startswith(event_parent): |
paul@69 | 783 | title = title[len(event_parent.rstrip("/")) + 1:] |
paul@69 | 784 | |
paul@69 | 785 | return getPrettyTitle(title) |
paul@69 | 786 | |
paul@69 | 787 | def getDetails(self): |
paul@69 | 788 | |
paul@69 | 789 | "Return the details for this event." |
paul@69 | 790 | |
paul@69 | 791 | return self.details |
paul@69 | 792 | |
paul@69 | 793 | def setDetails(self, event_details): |
paul@69 | 794 | |
paul@69 | 795 | "Set the 'event_details' for this event." |
paul@69 | 796 | |
paul@69 | 797 | self.details = event_details |
paul@69 | 798 | |
paul@123 | 799 | # Timespan-related methods. |
paul@123 | 800 | |
paul@123 | 801 | def __contains__(self, other): |
paul@123 | 802 | return self == other |
paul@123 | 803 | |
paul@123 | 804 | def __cmp__(self, other): |
paul@123 | 805 | if isinstance(other, Event): |
paul@123 | 806 | return cmp(self.as_timespan(), other.as_timespan()) |
paul@123 | 807 | else: |
paul@123 | 808 | return cmp(self.as_timespan(), other) |
paul@123 | 809 | |
paul@123 | 810 | def as_timespan(self): |
paul@123 | 811 | details = self.details |
paul@123 | 812 | if details.has_key("start") and details.has_key("end"): |
paul@123 | 813 | return Timespan(details["start"], details["end"]) |
paul@123 | 814 | else: |
paul@123 | 815 | return None |
paul@123 | 816 | |
paul@128 | 817 | def as_limits(self): |
paul@170 | 818 | ts = self.as_timespan() |
paul@170 | 819 | return ts and ts.as_limits() |
paul@123 | 820 | |
paul@168 | 821 | def getEventsFromPages(pages): |
paul@168 | 822 | |
paul@168 | 823 | "Return a list of events found on the given 'pages'." |
paul@12 | 824 | |
paul@10 | 825 | events = [] |
paul@168 | 826 | |
paul@168 | 827 | for page in pages: |
paul@168 | 828 | |
paul@168 | 829 | # Get a real page, not a result page. |
paul@168 | 830 | |
paul@168 | 831 | event_page = EventPage(page) |
paul@168 | 832 | |
paul@168 | 833 | # Get all events described in the page. |
paul@168 | 834 | |
paul@168 | 835 | for event in event_page.getEvents(): |
paul@168 | 836 | |
paul@168 | 837 | # Remember the event. |
paul@168 | 838 | |
paul@168 | 839 | events.append(event) |
paul@168 | 840 | |
paul@168 | 841 | return events |
paul@168 | 842 | |
paul@171 | 843 | def getEventsInPeriod(events, calendar_period): |
paul@168 | 844 | |
paul@168 | 845 | """ |
paul@168 | 846 | Return a collection containing those of the given 'events' which occur |
paul@171 | 847 | within the given 'calendar_period'. |
paul@168 | 848 | """ |
paul@168 | 849 | |
paul@171 | 850 | all_shown_events = [] |
paul@168 | 851 | |
paul@168 | 852 | for event in events: |
paul@168 | 853 | |
paul@168 | 854 | # Test for the suitability of the event. |
paul@168 | 855 | |
paul@168 | 856 | if event.as_timespan() is not None: |
paul@168 | 857 | |
paul@168 | 858 | # Compare the dates to the requested calendar window, if any. |
paul@168 | 859 | |
paul@168 | 860 | if event in calendar_period: |
paul@171 | 861 | all_shown_events.append(event) |
paul@168 | 862 | |
paul@168 | 863 | return all_shown_events |
paul@10 | 864 | |
paul@171 | 865 | def getEventLimits(events): |
paul@171 | 866 | |
paul@171 | 867 | "Return the earliest and latest of the given 'events'." |
paul@171 | 868 | |
paul@171 | 869 | earliest = None |
paul@171 | 870 | latest = None |
paul@171 | 871 | |
paul@171 | 872 | for event in events: |
paul@171 | 873 | |
paul@171 | 874 | # Test for the suitability of the event. |
paul@171 | 875 | |
paul@171 | 876 | if event.as_timespan() is not None: |
paul@171 | 877 | ts = event.as_timespan() |
paul@171 | 878 | if earliest is None or ts.start < earliest: |
paul@171 | 879 | earliest = ts.start |
paul@171 | 880 | if latest is None or ts.end > latest: |
paul@171 | 881 | latest = ts.end |
paul@171 | 882 | |
paul@171 | 883 | return earliest, latest |
paul@171 | 884 | |
paul@29 | 885 | def setEventTimestamps(request, events): |
paul@29 | 886 | |
paul@29 | 887 | """ |
paul@29 | 888 | Using 'request', set timestamp details in the details dictionary of each of |
paul@67 | 889 | the 'events'. |
paul@29 | 890 | |
paul@111 | 891 | Return the latest timestamp found. |
paul@29 | 892 | """ |
paul@29 | 893 | |
paul@29 | 894 | latest = None |
paul@29 | 895 | |
paul@69 | 896 | for event in events: |
paul@69 | 897 | event_details = event.getDetails() |
paul@69 | 898 | event_page = event.getPage() |
paul@29 | 899 | |
paul@29 | 900 | # Get the initial revision of the page. |
paul@29 | 901 | |
paul@67 | 902 | revisions = event_page.getRevisions() |
paul@67 | 903 | event_page_initial = Page(request, event_page.getPageName(), rev=revisions[-1]) |
paul@29 | 904 | |
paul@29 | 905 | # Get the created and last modified times. |
paul@29 | 906 | |
paul@30 | 907 | initial_revision = getPageRevision(event_page_initial) |
paul@30 | 908 | event_details["created"] = initial_revision["timestamp"] |
paul@67 | 909 | latest_revision = event_page.getPageRevision() |
paul@30 | 910 | event_details["last-modified"] = latest_revision["timestamp"] |
paul@29 | 911 | event_details["sequence"] = len(revisions) - 1 |
paul@30 | 912 | event_details["last-comment"] = latest_revision["comment"] |
paul@29 | 913 | |
paul@29 | 914 | if latest is None or latest < event_details["last-modified"]: |
paul@29 | 915 | latest = event_details["last-modified"] |
paul@29 | 916 | |
paul@29 | 917 | return latest |
paul@29 | 918 | |
paul@26 | 919 | def getOrderedEvents(events): |
paul@26 | 920 | |
paul@26 | 921 | """ |
paul@26 | 922 | Return a list with the given 'events' ordered according to their start and |
paul@67 | 923 | end dates. |
paul@26 | 924 | """ |
paul@26 | 925 | |
paul@26 | 926 | ordered_events = events[:] |
paul@68 | 927 | ordered_events.sort() |
paul@26 | 928 | return ordered_events |
paul@26 | 929 | |
paul@171 | 930 | def getCalendarPeriod(calendar_start, calendar_end): |
paul@168 | 931 | |
paul@168 | 932 | """ |
paul@171 | 933 | Return a calendar period for the given 'calendar_start' and 'calendar_end'. |
paul@171 | 934 | These parameters can be given as None. |
paul@168 | 935 | """ |
paul@168 | 936 | |
paul@168 | 937 | # Re-order the window, if appropriate. |
paul@168 | 938 | |
paul@168 | 939 | if calendar_start is not None and calendar_end is not None and calendar_start > calendar_end: |
paul@168 | 940 | calendar_start, calendar_end = calendar_end, calendar_start |
paul@168 | 941 | |
paul@171 | 942 | return Timespan(calendar_start, calendar_end) |
paul@168 | 943 | |
paul@187 | 944 | def getConcretePeriod(calendar_start, calendar_end, earliest, latest, resolution): |
paul@13 | 945 | |
paul@13 | 946 | """ |
paul@13 | 947 | From the requested 'calendar_start' and 'calendar_end', which may be None, |
paul@13 | 948 | indicating that no restriction is imposed on the period for each of the |
paul@13 | 949 | boundaries, use the 'earliest' and 'latest' event months to define a |
paul@13 | 950 | specific period of interest. |
paul@13 | 951 | """ |
paul@13 | 952 | |
paul@13 | 953 | # Define the period as starting with any specified start month or the |
paul@13 | 954 | # earliest event known, ending with any specified end month or the latest |
paul@13 | 955 | # event known. |
paul@13 | 956 | |
paul@13 | 957 | first = calendar_start or earliest |
paul@13 | 958 | last = calendar_end or latest |
paul@13 | 959 | |
paul@13 | 960 | # If there is no range of months to show, perhaps because there are no |
paul@13 | 961 | # events in the requested period, and there was no start or end month |
paul@13 | 962 | # specified, show only the month indicated by the start or end of the |
paul@13 | 963 | # requested period. If all events were to be shown but none were found show |
paul@13 | 964 | # the current month. |
paul@13 | 965 | |
paul@187 | 966 | if resolution == "date": |
paul@122 | 967 | get_current = getCurrentDate |
paul@122 | 968 | else: |
paul@122 | 969 | get_current = getCurrentMonth |
paul@122 | 970 | |
paul@13 | 971 | if first is None: |
paul@122 | 972 | first = last or get_current() |
paul@13 | 973 | if last is None: |
paul@122 | 974 | last = first or get_current() |
paul@13 | 975 | |
paul@187 | 976 | if resolution == "month": |
paul@187 | 977 | first = first.as_month() |
paul@187 | 978 | last = last.as_month() |
paul@187 | 979 | |
paul@13 | 980 | # Permit "expiring" periods (where the start date approaches the end date). |
paul@13 | 981 | |
paul@13 | 982 | return min(first, last), last |
paul@13 | 983 | |
paul@168 | 984 | def getCoverage(events, resolution="date"): |
paul@15 | 985 | |
paul@15 | 986 | """ |
paul@168 | 987 | Determine the coverage of the given 'events', returning a collection of |
paul@168 | 988 | timespans, along with a dictionary mapping locations to collections of |
paul@168 | 989 | slots, where each slot contains a tuple of the form (timespans, events). |
paul@15 | 990 | """ |
paul@15 | 991 | |
paul@118 | 992 | all_events = {} |
paul@123 | 993 | full_coverage = TimespanCollection(resolution) |
paul@15 | 994 | |
paul@15 | 995 | # Get event details. |
paul@15 | 996 | |
paul@69 | 997 | for event in events: |
paul@69 | 998 | event_details = event.getDetails() |
paul@15 | 999 | |
paul@168 | 1000 | # Find the coverage of this period for the event. |
paul@168 | 1001 | |
paul@168 | 1002 | # For day views, each location has its own slot, but for month |
paul@168 | 1003 | # views, all locations are pooled together since having separate |
paul@168 | 1004 | # slots for each location can lead to poor usage of vertical space. |
paul@168 | 1005 | |
paul@168 | 1006 | if resolution == "datetime": |
paul@168 | 1007 | event_location = event_details.get("location") |
paul@168 | 1008 | else: |
paul@168 | 1009 | event_location = None |
paul@168 | 1010 | |
paul@168 | 1011 | # Update the overall coverage. |
paul@168 | 1012 | |
paul@168 | 1013 | full_coverage.insert_in_order(event) |
paul@168 | 1014 | |
paul@168 | 1015 | # Add a new events list for a new location. |
paul@168 | 1016 | # Locations can be unspecified, thus None refers to all unlocalised |
paul@168 | 1017 | # events. |
paul@168 | 1018 | |
paul@168 | 1019 | if not all_events.has_key(event_location): |
paul@168 | 1020 | all_events[event_location] = [TimespanCollection(resolution, [event])] |
paul@168 | 1021 | |
paul@168 | 1022 | # Try and fit the event into an events list. |
paul@168 | 1023 | |
paul@168 | 1024 | else: |
paul@168 | 1025 | slot = all_events[event_location] |
paul@168 | 1026 | |
paul@168 | 1027 | for slot_events in slot: |
paul@168 | 1028 | |
paul@168 | 1029 | # Where the event does not overlap with the events in the |
paul@168 | 1030 | # current collection, add it alongside these events. |
paul@168 | 1031 | |
paul@168 | 1032 | if not event in slot_events: |
paul@168 | 1033 | slot_events.insert_in_order(event) |
paul@168 | 1034 | break |
paul@168 | 1035 | |
paul@168 | 1036 | # Make a new element in the list if the event cannot be |
paul@168 | 1037 | # marked alongside existing events. |
paul@15 | 1038 | |
paul@15 | 1039 | else: |
paul@168 | 1040 | slot.append(TimespanCollection(resolution, [event])) |
paul@15 | 1041 | |
paul@15 | 1042 | return full_coverage, all_events |
paul@15 | 1043 | |
paul@122 | 1044 | def getCoverageScale(coverage): |
paul@126 | 1045 | |
paul@126 | 1046 | """ |
paul@126 | 1047 | Return a scale for the given coverage so that the times involved are |
paul@126 | 1048 | exposed. The scale consists of a list of non-overlapping timespans forming |
paul@126 | 1049 | a contiguous period of time. |
paul@126 | 1050 | """ |
paul@126 | 1051 | |
paul@122 | 1052 | times = set() |
paul@122 | 1053 | for timespan in coverage: |
paul@128 | 1054 | start, end = timespan.as_limits() |
paul@128 | 1055 | |
paul@128 | 1056 | # Add either genuine times or dates converted to times. |
paul@128 | 1057 | |
paul@128 | 1058 | if isinstance(start, DateTime): |
paul@128 | 1059 | times.add(start) |
paul@140 | 1060 | else: |
paul@140 | 1061 | times.add(start.as_datetime(None, None, None, None)) |
paul@128 | 1062 | |
paul@128 | 1063 | if isinstance(end, DateTime): |
paul@140 | 1064 | times.add(end) |
paul@140 | 1065 | else: |
paul@140 | 1066 | times.add(end.as_date().next_day()) |
paul@128 | 1067 | |
paul@122 | 1068 | times = list(times) |
paul@135 | 1069 | times.sort(cmp_dates_as_day_start) |
paul@122 | 1070 | |
paul@122 | 1071 | scale = [] |
paul@122 | 1072 | first = 1 |
paul@122 | 1073 | start = None |
paul@122 | 1074 | for time in times: |
paul@122 | 1075 | if not first: |
paul@123 | 1076 | scale.append(Timespan(start, time)) |
paul@122 | 1077 | else: |
paul@122 | 1078 | first = 0 |
paul@122 | 1079 | start = time |
paul@126 | 1080 | |
paul@122 | 1081 | return scale |
paul@122 | 1082 | |
paul@67 | 1083 | # Date-related functions. |
paul@67 | 1084 | |
paul@135 | 1085 | def cmp_dates_as_day_start(a, b): |
paul@135 | 1086 | |
paul@135 | 1087 | """ |
paul@135 | 1088 | Compare dates/datetimes 'a' and 'b' treating dates without time information |
paul@135 | 1089 | as the earliest time in a particular day. |
paul@135 | 1090 | """ |
paul@135 | 1091 | |
paul@135 | 1092 | are_equal = a == b |
paul@135 | 1093 | |
paul@135 | 1094 | if are_equal: |
paul@135 | 1095 | a2 = a.as_datetime_or_date() |
paul@135 | 1096 | b2 = b.as_datetime_or_date() |
paul@135 | 1097 | |
paul@135 | 1098 | if isinstance(a2, Date) and isinstance(b2, DateTime): |
paul@135 | 1099 | return -1 |
paul@135 | 1100 | elif isinstance(a2, DateTime) and isinstance(b2, Date): |
paul@135 | 1101 | return 1 |
paul@135 | 1102 | |
paul@135 | 1103 | return cmp(a, b) |
paul@135 | 1104 | |
paul@168 | 1105 | class Convertible: |
paul@168 | 1106 | |
paul@168 | 1107 | "Support for converting temporal objects." |
paul@168 | 1108 | |
paul@168 | 1109 | def _get_converter(self, resolution): |
paul@168 | 1110 | if resolution == "month": |
paul@168 | 1111 | return lambda x: x and x.as_month() |
paul@168 | 1112 | elif resolution == "date": |
paul@168 | 1113 | return lambda x: x and x.as_date() |
paul@168 | 1114 | elif resolution == "datetime": |
paul@168 | 1115 | return lambda x: x and x.as_datetime_or_date() |
paul@168 | 1116 | else: |
paul@168 | 1117 | return lambda x: x |
paul@168 | 1118 | |
paul@168 | 1119 | class Temporal(Convertible): |
paul@67 | 1120 | |
paul@92 | 1121 | "A simple temporal representation, common to dates and times." |
paul@67 | 1122 | |
paul@67 | 1123 | def __init__(self, data): |
paul@92 | 1124 | self.data = list(data) |
paul@67 | 1125 | |
paul@67 | 1126 | def __repr__(self): |
paul@67 | 1127 | return "%s(%r)" % (self.__class__.__name__, self.data) |
paul@67 | 1128 | |
paul@67 | 1129 | def __hash__(self): |
paul@67 | 1130 | return hash(self.as_tuple()) |
paul@67 | 1131 | |
paul@67 | 1132 | def as_tuple(self): |
paul@92 | 1133 | return tuple(self.data) |
paul@92 | 1134 | |
paul@168 | 1135 | def convert(self, resolution): |
paul@168 | 1136 | return self._get_converter(resolution)(self) |
paul@168 | 1137 | |
paul@92 | 1138 | def __cmp__(self, other): |
paul@129 | 1139 | |
paul@129 | 1140 | """ |
paul@129 | 1141 | The result of comparing this instance with 'other' is derived from a |
paul@129 | 1142 | comparison of the instances' date(time) data at the highest common |
paul@129 | 1143 | resolution, meaning that if a date is compared to a datetime, the |
paul@129 | 1144 | datetime will be considered as a date. Thus, a date and a datetime |
paul@129 | 1145 | referring to the same date will be considered equal. |
paul@129 | 1146 | """ |
paul@129 | 1147 | |
paul@122 | 1148 | if not isinstance(other, Temporal): |
paul@122 | 1149 | return NotImplemented |
paul@122 | 1150 | else: |
paul@122 | 1151 | data = self.as_tuple() |
paul@122 | 1152 | other_data = other.as_tuple() |
paul@122 | 1153 | length = min(len(data), len(other_data)) |
paul@122 | 1154 | return cmp(data[:length], other_data[:length]) |
paul@92 | 1155 | |
paul@212 | 1156 | def __sub__(self, other): |
paul@212 | 1157 | |
paul@212 | 1158 | """ |
paul@212 | 1159 | Return the difference between this object and the 'other' object at the |
paul@212 | 1160 | highest common accuracy of both objects. |
paul@212 | 1161 | """ |
paul@212 | 1162 | |
paul@212 | 1163 | if not isinstance(other, Temporal): |
paul@212 | 1164 | return NotImplemented |
paul@212 | 1165 | else: |
paul@212 | 1166 | data = self.as_tuple() |
paul@212 | 1167 | other_data = other.as_tuple() |
paul@212 | 1168 | if len(data) < len(other_data): |
paul@212 | 1169 | return len(self.until(other)) |
paul@212 | 1170 | else: |
paul@212 | 1171 | return len(other.until(self)) |
paul@212 | 1172 | |
paul@187 | 1173 | def _until(self, start, end, nextfn, prevfn): |
paul@103 | 1174 | |
paul@103 | 1175 | """ |
paul@103 | 1176 | Return a collection of units of time by starting from the given 'start' |
paul@103 | 1177 | and stepping across intervening units until 'end' is reached, using the |
paul@103 | 1178 | given 'nextfn' and 'prevfn' to step from one unit to the next. |
paul@103 | 1179 | """ |
paul@103 | 1180 | |
paul@103 | 1181 | current = start |
paul@103 | 1182 | units = [current] |
paul@103 | 1183 | if current < end: |
paul@103 | 1184 | while current < end: |
paul@103 | 1185 | current = nextfn(current) |
paul@103 | 1186 | units.append(current) |
paul@103 | 1187 | elif current > end: |
paul@103 | 1188 | while current > end: |
paul@103 | 1189 | current = prevfn(current) |
paul@103 | 1190 | units.append(current) |
paul@103 | 1191 | return units |
paul@103 | 1192 | |
paul@140 | 1193 | def ambiguous(self): |
paul@140 | 1194 | |
paul@140 | 1195 | "Only times can be ambiguous." |
paul@140 | 1196 | |
paul@140 | 1197 | return 0 |
paul@140 | 1198 | |
paul@92 | 1199 | class Month(Temporal): |
paul@92 | 1200 | |
paul@92 | 1201 | "A simple year-month representation." |
paul@92 | 1202 | |
paul@92 | 1203 | def __str__(self): |
paul@92 | 1204 | return "%04d-%02d" % self.as_tuple()[:2] |
paul@67 | 1205 | |
paul@93 | 1206 | def as_datetime(self, day, hour, minute, second, zone): |
paul@93 | 1207 | return DateTime(self.as_tuple() + (day, hour, minute, second, zone)) |
paul@93 | 1208 | |
paul@67 | 1209 | def as_date(self, day): |
paul@67 | 1210 | return Date(self.as_tuple() + (day,)) |
paul@67 | 1211 | |
paul@92 | 1212 | def as_month(self): |
paul@92 | 1213 | return self |
paul@92 | 1214 | |
paul@67 | 1215 | def year(self): |
paul@67 | 1216 | return self.data[0] |
paul@67 | 1217 | |
paul@67 | 1218 | def month(self): |
paul@67 | 1219 | return self.data[1] |
paul@67 | 1220 | |
paul@67 | 1221 | def month_properties(self): |
paul@67 | 1222 | |
paul@67 | 1223 | """ |
paul@67 | 1224 | Return the weekday of the 1st of the month, along with the number of |
paul@67 | 1225 | days, as a tuple. |
paul@67 | 1226 | """ |
paul@67 | 1227 | |
paul@92 | 1228 | year, month = self.as_tuple()[:2] |
paul@67 | 1229 | return calendar.monthrange(year, month) |
paul@67 | 1230 | |
paul@67 | 1231 | def month_update(self, n=1): |
paul@67 | 1232 | |
paul@67 | 1233 | "Return the month updated by 'n' months." |
paul@67 | 1234 | |
paul@92 | 1235 | year, month = self.as_tuple()[:2] |
paul@67 | 1236 | return Month((year + (month - 1 + n) / 12, (month - 1 + n) % 12 + 1)) |
paul@67 | 1237 | |
paul@187 | 1238 | update = month_update |
paul@187 | 1239 | |
paul@67 | 1240 | def next_month(self): |
paul@67 | 1241 | |
paul@67 | 1242 | "Return the month following this one." |
paul@67 | 1243 | |
paul@67 | 1244 | return self.month_update(1) |
paul@67 | 1245 | |
paul@187 | 1246 | next = next_month |
paul@187 | 1247 | |
paul@67 | 1248 | def previous_month(self): |
paul@67 | 1249 | |
paul@67 | 1250 | "Return the month preceding this one." |
paul@67 | 1251 | |
paul@67 | 1252 | return self.month_update(-1) |
paul@67 | 1253 | |
paul@187 | 1254 | previous = previous_month |
paul@187 | 1255 | |
paul@67 | 1256 | def months_until(self, end): |
paul@92 | 1257 | |
paul@92 | 1258 | "Return the collection of months from this month until 'end'." |
paul@92 | 1259 | |
paul@187 | 1260 | return self._until(self.as_month(), end.as_month(), Month.next_month, Month.previous_month) |
paul@187 | 1261 | |
paul@187 | 1262 | until = months_until |
paul@67 | 1263 | |
paul@67 | 1264 | class Date(Month): |
paul@67 | 1265 | |
paul@67 | 1266 | "A simple year-month-day representation." |
paul@67 | 1267 | |
paul@96 | 1268 | def constrain(self): |
paul@96 | 1269 | year, month, day = self.as_tuple()[:3] |
paul@96 | 1270 | |
paul@96 | 1271 | month = max(min(month, 12), 1) |
paul@96 | 1272 | wd, last_day = calendar.monthrange(year, month) |
paul@96 | 1273 | day = max(min(day, last_day), 1) |
paul@96 | 1274 | |
paul@96 | 1275 | self.data[1:3] = month, day |
paul@96 | 1276 | |
paul@67 | 1277 | def __str__(self): |
paul@67 | 1278 | return "%04d-%02d-%02d" % self.as_tuple()[:3] |
paul@67 | 1279 | |
paul@93 | 1280 | def as_datetime(self, hour, minute, second, zone): |
paul@93 | 1281 | return DateTime(self.as_tuple() + (hour, minute, second, zone)) |
paul@93 | 1282 | |
paul@92 | 1283 | def as_date(self): |
paul@92 | 1284 | return self |
paul@92 | 1285 | |
paul@130 | 1286 | def as_datetime_or_date(self): |
paul@130 | 1287 | return self |
paul@130 | 1288 | |
paul@67 | 1289 | def as_month(self): |
paul@67 | 1290 | return Month(self.data[:2]) |
paul@67 | 1291 | |
paul@67 | 1292 | def day(self): |
paul@67 | 1293 | return self.data[2] |
paul@67 | 1294 | |
paul@122 | 1295 | def day_update(self, n=1): |
paul@122 | 1296 | |
paul@145 | 1297 | "Return the month updated by 'n' days." |
paul@122 | 1298 | |
paul@122 | 1299 | delta = datetime.timedelta(n) |
paul@122 | 1300 | dt = datetime.date(*self.as_tuple()[:3]) |
paul@122 | 1301 | dt_new = dt + delta |
paul@122 | 1302 | return Date((dt_new.year, dt_new.month, dt_new.day)) |
paul@122 | 1303 | |
paul@187 | 1304 | update = day_update |
paul@187 | 1305 | |
paul@67 | 1306 | def next_day(self): |
paul@67 | 1307 | |
paul@67 | 1308 | "Return the date following this one." |
paul@67 | 1309 | |
paul@92 | 1310 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1311 | _wd, end_day = calendar.monthrange(year, month) |
paul@67 | 1312 | if day == end_day: |
paul@67 | 1313 | if month == 12: |
paul@67 | 1314 | return Date((year + 1, 1, 1)) |
paul@67 | 1315 | else: |
paul@67 | 1316 | return Date((year, month + 1, 1)) |
paul@67 | 1317 | else: |
paul@67 | 1318 | return Date((year, month, day + 1)) |
paul@67 | 1319 | |
paul@187 | 1320 | next = next_day |
paul@187 | 1321 | |
paul@67 | 1322 | def previous_day(self): |
paul@67 | 1323 | |
paul@67 | 1324 | "Return the date preceding this one." |
paul@67 | 1325 | |
paul@92 | 1326 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1327 | if day == 1: |
paul@67 | 1328 | if month == 1: |
paul@67 | 1329 | return Date((year - 1, 12, 31)) |
paul@67 | 1330 | else: |
paul@67 | 1331 | _wd, end_day = calendar.monthrange(year, month - 1) |
paul@67 | 1332 | return Date((year, month - 1, end_day)) |
paul@67 | 1333 | else: |
paul@67 | 1334 | return Date((year, month, day - 1)) |
paul@67 | 1335 | |
paul@187 | 1336 | previous = previous_day |
paul@187 | 1337 | |
paul@67 | 1338 | def days_until(self, end): |
paul@92 | 1339 | |
paul@92 | 1340 | "Return the collection of days from this date until 'end'." |
paul@92 | 1341 | |
paul@187 | 1342 | return self._until(self.as_date(), end.as_date(), Date.next_day, Date.previous_day) |
paul@187 | 1343 | |
paul@187 | 1344 | until = days_until |
paul@92 | 1345 | |
paul@92 | 1346 | class DateTime(Date): |
paul@92 | 1347 | |
paul@92 | 1348 | "A simple date plus time representation." |
paul@92 | 1349 | |
paul@96 | 1350 | def constrain(self): |
paul@96 | 1351 | Date.constrain(self) |
paul@96 | 1352 | |
paul@96 | 1353 | hour, minute, second = self.as_tuple()[3:6] |
paul@96 | 1354 | |
paul@96 | 1355 | if self.has_time(): |
paul@96 | 1356 | hour = max(min(hour, 23), 0) |
paul@96 | 1357 | minute = max(min(minute, 59), 0) |
paul@96 | 1358 | |
paul@96 | 1359 | if second is not None: |
paul@96 | 1360 | second = max(min(second, 60), 0) # support leap seconds |
paul@96 | 1361 | |
paul@96 | 1362 | self.data[3:6] = hour, minute, second |
paul@92 | 1363 | |
paul@92 | 1364 | def __str__(self): |
paul@128 | 1365 | return Date.__str__(self) + self.time_string() |
paul@128 | 1366 | |
paul@128 | 1367 | def time_string(self): |
paul@92 | 1368 | if self.has_time(): |
paul@92 | 1369 | data = self.as_tuple() |
paul@92 | 1370 | time_str = " %02d:%02d" % data[3:5] |
paul@92 | 1371 | if data[5] is not None: |
paul@92 | 1372 | time_str += ":%02d" % data[5] |
paul@92 | 1373 | if data[6] is not None: |
paul@92 | 1374 | time_str += " %s" % data[6] |
paul@128 | 1375 | return time_str |
paul@92 | 1376 | else: |
paul@128 | 1377 | return "" |
paul@92 | 1378 | |
paul@93 | 1379 | def as_datetime(self): |
paul@93 | 1380 | return self |
paul@93 | 1381 | |
paul@92 | 1382 | def as_date(self): |
paul@92 | 1383 | return Date(self.data[:3]) |
paul@92 | 1384 | |
paul@128 | 1385 | def as_datetime_or_date(self): |
paul@128 | 1386 | |
paul@128 | 1387 | """ |
paul@128 | 1388 | Return a date for this datetime if fields are missing. Otherwise, return |
paul@128 | 1389 | this datetime itself. |
paul@128 | 1390 | """ |
paul@128 | 1391 | |
paul@128 | 1392 | if not self.has_time(): |
paul@128 | 1393 | return self.as_date() |
paul@128 | 1394 | else: |
paul@128 | 1395 | return self |
paul@128 | 1396 | |
paul@126 | 1397 | def __cmp__(self, other): |
paul@129 | 1398 | |
paul@129 | 1399 | """ |
paul@129 | 1400 | The result of comparing this instance with 'other' is, if both instances |
paul@129 | 1401 | are datetime instances, derived from a comparison of the datetimes |
paul@129 | 1402 | converted to UTC. If one or both datetimes cannot be converted to UTC, |
paul@129 | 1403 | the datetimes are compared using the basic temporal comparison which |
paul@129 | 1404 | compares their raw time data. |
paul@129 | 1405 | """ |
paul@129 | 1406 | |
paul@140 | 1407 | this = self |
paul@140 | 1408 | |
paul@140 | 1409 | if this.has_time(): |
paul@128 | 1410 | if isinstance(other, DateTime): |
paul@140 | 1411 | if other.has_time(): |
paul@140 | 1412 | this_utc = this.to_utc() |
paul@140 | 1413 | other_utc = other.to_utc() |
paul@140 | 1414 | if this_utc is not None and other_utc is not None: |
paul@140 | 1415 | return cmp(this_utc.as_tuple(), other_utc.as_tuple()) |
paul@140 | 1416 | else: |
paul@140 | 1417 | other = other.padded() |
paul@140 | 1418 | else: |
paul@140 | 1419 | this = this.padded() |
paul@128 | 1420 | |
paul@128 | 1421 | return Date.__cmp__(this, other) |
paul@126 | 1422 | |
paul@92 | 1423 | def has_time(self): |
paul@140 | 1424 | |
paul@140 | 1425 | """ |
paul@140 | 1426 | Return whether this object has any time information. Objects without |
paul@140 | 1427 | time information can refer to the very start of a day. |
paul@140 | 1428 | """ |
paul@140 | 1429 | |
paul@92 | 1430 | return self.data[3] is not None and self.data[4] is not None |
paul@92 | 1431 | |
paul@128 | 1432 | def time(self): |
paul@128 | 1433 | return self.data[3:] |
paul@128 | 1434 | |
paul@92 | 1435 | def seconds(self): |
paul@92 | 1436 | return self.data[5] |
paul@92 | 1437 | |
paul@92 | 1438 | def time_zone(self): |
paul@92 | 1439 | return self.data[6] |
paul@92 | 1440 | |
paul@93 | 1441 | def set_time_zone(self, value): |
paul@92 | 1442 | self.data[6] = value |
paul@92 | 1443 | |
paul@140 | 1444 | def padded(self, empty_value=0): |
paul@140 | 1445 | |
paul@140 | 1446 | """ |
paul@140 | 1447 | Return a datetime with missing fields defined as being the given |
paul@140 | 1448 | 'empty_value' or 0 if not specified. |
paul@140 | 1449 | """ |
paul@140 | 1450 | |
paul@140 | 1451 | data = [] |
paul@140 | 1452 | for x in self.data[:6]: |
paul@140 | 1453 | if x is None: |
paul@140 | 1454 | data.append(empty_value) |
paul@140 | 1455 | else: |
paul@140 | 1456 | data.append(x) |
paul@140 | 1457 | |
paul@140 | 1458 | data += self.data[6:] |
paul@92 | 1459 | return DateTime(data) |
paul@92 | 1460 | |
paul@93 | 1461 | def to_utc(self): |
paul@93 | 1462 | |
paul@93 | 1463 | """ |
paul@93 | 1464 | Return this object converted to UTC, or None if such a conversion is not |
paul@93 | 1465 | defined. |
paul@93 | 1466 | """ |
paul@93 | 1467 | |
paul@128 | 1468 | if not self.has_time(): |
paul@128 | 1469 | return None |
paul@128 | 1470 | |
paul@93 | 1471 | offset = self.utc_offset() |
paul@93 | 1472 | if offset: |
paul@93 | 1473 | hours, minutes = offset |
paul@93 | 1474 | |
paul@93 | 1475 | # Invert the offset to get the correction. |
paul@93 | 1476 | |
paul@93 | 1477 | hours, minutes = -hours, -minutes |
paul@93 | 1478 | |
paul@93 | 1479 | # Get the components. |
paul@93 | 1480 | |
paul@128 | 1481 | hour, minute, second, zone = self.time() |
paul@93 | 1482 | date = self.as_date() |
paul@93 | 1483 | |
paul@93 | 1484 | # Add the minutes and hours. |
paul@93 | 1485 | |
paul@93 | 1486 | minute += minutes |
paul@103 | 1487 | if minute < 0 or minute > 59: |
paul@103 | 1488 | hour += minute / 60 |
paul@103 | 1489 | minute = minute % 60 |
paul@103 | 1490 | |
paul@103 | 1491 | # NOTE: This makes various assumptions and probably would not work |
paul@103 | 1492 | # NOTE: for general arithmetic. |
paul@93 | 1493 | |
paul@93 | 1494 | hour += hours |
paul@93 | 1495 | if hour < 0: |
paul@93 | 1496 | date = date.previous_day() |
paul@93 | 1497 | hour += 24 |
paul@93 | 1498 | elif hour > 23: |
paul@93 | 1499 | date = date.next_day() |
paul@93 | 1500 | hour -= 24 |
paul@93 | 1501 | |
paul@93 | 1502 | return date.as_datetime(hour, minute, second, "UTC") |
paul@100 | 1503 | |
paul@100 | 1504 | # Cannot convert. |
paul@100 | 1505 | |
paul@93 | 1506 | else: |
paul@93 | 1507 | return None |
paul@93 | 1508 | |
paul@93 | 1509 | def utc_offset(self): |
paul@93 | 1510 | |
paul@93 | 1511 | "Return the UTC offset in hours and minutes." |
paul@93 | 1512 | |
paul@93 | 1513 | zone = self.time_zone() |
paul@95 | 1514 | if not zone: |
paul@95 | 1515 | return None |
paul@93 | 1516 | |
paul@96 | 1517 | # Support explicit UTC zones. |
paul@96 | 1518 | |
paul@96 | 1519 | if zone == "UTC": |
paul@96 | 1520 | return 0, 0 |
paul@96 | 1521 | |
paul@94 | 1522 | # Attempt to return a UTC offset where an explicit offset has been set. |
paul@93 | 1523 | |
paul@94 | 1524 | match = timezone_offset_regexp.match(zone) |
paul@94 | 1525 | if match: |
paul@94 | 1526 | if match.group("sign") == "-": |
paul@93 | 1527 | sign = -1 |
paul@93 | 1528 | else: |
paul@93 | 1529 | sign = 1 |
paul@93 | 1530 | |
paul@94 | 1531 | hours = int(match.group("hours")) * sign |
paul@94 | 1532 | minutes = int(match.group("minutes") or 0) * sign |
paul@94 | 1533 | return hours, minutes |
paul@94 | 1534 | |
paul@102 | 1535 | # Attempt to handle Olson time zone identifiers. |
paul@102 | 1536 | |
paul@102 | 1537 | dt = self.as_olson_datetime() |
paul@102 | 1538 | if dt: |
paul@102 | 1539 | seconds = dt.utcoffset().seconds |
paul@102 | 1540 | hours = seconds / 3600 |
paul@102 | 1541 | minutes = (seconds % 3600) / 60 |
paul@102 | 1542 | return hours, minutes |
paul@102 | 1543 | |
paul@102 | 1544 | # Otherwise return None. |
paul@102 | 1545 | |
paul@93 | 1546 | return None |
paul@93 | 1547 | |
paul@100 | 1548 | def olson_identifier(self): |
paul@100 | 1549 | |
paul@100 | 1550 | "Return the Olson identifier from any zone information." |
paul@100 | 1551 | |
paul@100 | 1552 | zone = self.time_zone() |
paul@100 | 1553 | if not zone: |
paul@100 | 1554 | return None |
paul@100 | 1555 | |
paul@100 | 1556 | # Attempt to match an identifier. |
paul@100 | 1557 | |
paul@100 | 1558 | match = timezone_olson_regexp.match(zone) |
paul@100 | 1559 | if match: |
paul@100 | 1560 | return match.group("olson") |
paul@100 | 1561 | else: |
paul@100 | 1562 | return None |
paul@100 | 1563 | |
paul@102 | 1564 | def _as_olson_datetime(self, hours=None): |
paul@102 | 1565 | |
paul@102 | 1566 | """ |
paul@102 | 1567 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 1568 | Olson time zone identifier and the given 'hours' offset, raising one of |
paul@102 | 1569 | the pytz exceptions in case of ambiguity. |
paul@102 | 1570 | """ |
paul@102 | 1571 | |
paul@102 | 1572 | olson = self.olson_identifier() |
paul@102 | 1573 | if olson and pytz: |
paul@102 | 1574 | tz = pytz.timezone(olson) |
paul@102 | 1575 | data = self.padded().as_tuple()[:6] |
paul@102 | 1576 | dt = datetime.datetime(*data) |
paul@102 | 1577 | |
paul@102 | 1578 | # With an hours offset, find a time probably in a previously |
paul@102 | 1579 | # applicable time zone. |
paul@102 | 1580 | |
paul@102 | 1581 | if hours is not None: |
paul@102 | 1582 | td = datetime.timedelta(0, hours * 3600) |
paul@102 | 1583 | dt += td |
paul@102 | 1584 | |
paul@102 | 1585 | ldt = tz.localize(dt, None) |
paul@102 | 1586 | |
paul@102 | 1587 | # With an hours offset, adjust the time to define it within the |
paul@102 | 1588 | # previously applicable time zone but at the presumably intended |
paul@102 | 1589 | # position. |
paul@102 | 1590 | |
paul@102 | 1591 | if hours is not None: |
paul@102 | 1592 | ldt -= td |
paul@102 | 1593 | |
paul@102 | 1594 | return ldt |
paul@102 | 1595 | else: |
paul@102 | 1596 | return None |
paul@102 | 1597 | |
paul@102 | 1598 | def as_olson_datetime(self): |
paul@102 | 1599 | |
paul@102 | 1600 | """ |
paul@102 | 1601 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 1602 | Olson time zone identifier, choosing the time from the zone before the |
paul@102 | 1603 | period of ambiguity. |
paul@102 | 1604 | """ |
paul@102 | 1605 | |
paul@102 | 1606 | try: |
paul@102 | 1607 | return self._as_olson_datetime() |
paul@102 | 1608 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@103 | 1609 | |
paul@103 | 1610 | # Try again, using an earlier local time and then stepping forward |
paul@103 | 1611 | # in the chosen zone. |
paul@103 | 1612 | # NOTE: Four hours earlier seems reasonable. |
paul@103 | 1613 | |
paul@103 | 1614 | return self._as_olson_datetime(-4) |
paul@102 | 1615 | |
paul@100 | 1616 | def ambiguous(self): |
paul@100 | 1617 | |
paul@100 | 1618 | "Return whether the time is local and ambiguous." |
paul@100 | 1619 | |
paul@102 | 1620 | try: |
paul@102 | 1621 | self._as_olson_datetime() |
paul@102 | 1622 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@102 | 1623 | return 1 |
paul@100 | 1624 | |
paul@100 | 1625 | return 0 |
paul@100 | 1626 | |
paul@168 | 1627 | class Timespan(ActsAsTimespan, Convertible): |
paul@122 | 1628 | |
paul@122 | 1629 | """ |
paul@122 | 1630 | A period of time which can be compared against others to check for overlaps. |
paul@122 | 1631 | """ |
paul@122 | 1632 | |
paul@122 | 1633 | def __init__(self, start, end): |
paul@122 | 1634 | self.start = start |
paul@122 | 1635 | self.end = end |
paul@122 | 1636 | |
paul@179 | 1637 | # NOTE: Should perhaps catch ambiguous time problems elsewhere. |
paul@179 | 1638 | |
paul@182 | 1639 | if self.ambiguous() and self.start is not None and self.end is not None and start > end: |
paul@179 | 1640 | self.start, self.end = end, start |
paul@179 | 1641 | |
paul@122 | 1642 | def __repr__(self): |
paul@122 | 1643 | return "%s(%r, %r)" % (self.__class__.__name__, self.start, self.end) |
paul@122 | 1644 | |
paul@122 | 1645 | def __hash__(self): |
paul@122 | 1646 | return hash((self.start, self.end)) |
paul@122 | 1647 | |
paul@130 | 1648 | def as_timespan(self): |
paul@130 | 1649 | return self |
paul@130 | 1650 | |
paul@128 | 1651 | def as_limits(self): |
paul@123 | 1652 | return self.start, self.end |
paul@123 | 1653 | |
paul@179 | 1654 | def ambiguous(self): |
paul@182 | 1655 | return self.start is not None and self.start.ambiguous() or self.end is not None and self.end.ambiguous() |
paul@179 | 1656 | |
paul@168 | 1657 | def convert(self, resolution): |
paul@168 | 1658 | return Timespan(*map(self._get_converter(resolution), self.as_limits())) |
paul@168 | 1659 | |
paul@122 | 1660 | def is_before(self, a, b): |
paul@129 | 1661 | |
paul@129 | 1662 | """ |
paul@129 | 1663 | Return whether 'a' is before 'b'. Since the end datetime of one period |
paul@129 | 1664 | may be the same as the start datetime of another period, and yet the |
paul@129 | 1665 | first period is intended to be concluded by the end datetime and not |
paul@129 | 1666 | overlap with the other period, a different test is employed for datetime |
paul@129 | 1667 | comparisons. |
paul@129 | 1668 | """ |
paul@129 | 1669 | |
paul@140 | 1670 | # Datetimes without times can be equal to dates and be considered as |
paul@178 | 1671 | # occurring before those dates. Generally, datetimes should not be |
paul@178 | 1672 | # produced without time information as getDateTime converts such |
paul@178 | 1673 | # datetimes to dates. |
paul@140 | 1674 | |
paul@140 | 1675 | if isinstance(a, DateTime) and (isinstance(b, DateTime) or not a.has_time()): |
paul@122 | 1676 | return a <= b |
paul@122 | 1677 | else: |
paul@122 | 1678 | return a < b |
paul@122 | 1679 | |
paul@122 | 1680 | def __contains__(self, other): |
paul@129 | 1681 | |
paul@129 | 1682 | """ |
paul@129 | 1683 | This instance is considered to contain 'other' if one is not before or |
paul@129 | 1684 | after the other. If this instance overlaps or coincides with 'other', |
paul@129 | 1685 | then 'other' is regarded as belonging to this instance's time period. |
paul@129 | 1686 | """ |
paul@129 | 1687 | |
paul@123 | 1688 | return self == other |
paul@122 | 1689 | |
paul@122 | 1690 | def __cmp__(self, other): |
paul@122 | 1691 | |
paul@122 | 1692 | """ |
paul@122 | 1693 | Return whether this timespan occupies the same period of time as the |
paul@129 | 1694 | 'other'. Timespans are considered less than others if their end points |
paul@129 | 1695 | precede the other's start point, and are considered greater than others |
paul@129 | 1696 | if their start points follow the other's end point. |
paul@122 | 1697 | """ |
paul@122 | 1698 | |
paul@130 | 1699 | if isinstance(other, ActsAsTimespan): |
paul@130 | 1700 | other = other.as_timespan() |
paul@130 | 1701 | |
paul@123 | 1702 | if self.end is not None and other.start is not None and self.is_before(self.end, other.start): |
paul@122 | 1703 | return -1 |
paul@123 | 1704 | elif self.start is not None and other.end is not None and self.is_before(other.end, self.start): |
paul@122 | 1705 | return 1 |
paul@122 | 1706 | else: |
paul@122 | 1707 | return 0 |
paul@122 | 1708 | |
paul@122 | 1709 | else: |
paul@123 | 1710 | if self.end is not None and self.is_before(self.end, other): |
paul@122 | 1711 | return -1 |
paul@140 | 1712 | elif self.start is not None and self.is_before(other, self.start): |
paul@122 | 1713 | return 1 |
paul@122 | 1714 | else: |
paul@122 | 1715 | return 0 |
paul@122 | 1716 | |
paul@123 | 1717 | class TimespanCollection: |
paul@123 | 1718 | |
paul@129 | 1719 | """ |
paul@171 | 1720 | A class providing a list-like interface supporting membership tests at a |
paul@171 | 1721 | particular resolution in order to maintain a collection of non-overlapping |
paul@171 | 1722 | timespans. |
paul@129 | 1723 | """ |
paul@123 | 1724 | |
paul@123 | 1725 | def __init__(self, resolution, values=None): |
paul@168 | 1726 | self.resolution = resolution |
paul@168 | 1727 | self.values = values or [] |
paul@168 | 1728 | |
paul@168 | 1729 | def as_timespan(self): |
paul@168 | 1730 | return Timespan(*self.as_limits()) |
paul@168 | 1731 | |
paul@168 | 1732 | def as_limits(self): |
paul@168 | 1733 | |
paul@168 | 1734 | "Return the earliest and latest points in time for this collection." |
paul@168 | 1735 | |
paul@168 | 1736 | if not self.values: |
paul@168 | 1737 | return None, None |
paul@123 | 1738 | else: |
paul@168 | 1739 | first, last = self.values[0], self.values[-1] |
paul@168 | 1740 | if isinstance(first, ActsAsTimespan): |
paul@168 | 1741 | first = first.as_timespan().start |
paul@168 | 1742 | if isinstance(last, ActsAsTimespan): |
paul@168 | 1743 | last = last.as_timespan().end |
paul@168 | 1744 | return first, last |
paul@123 | 1745 | |
paul@123 | 1746 | def convert(self, value): |
paul@130 | 1747 | if isinstance(value, ActsAsTimespan): |
paul@171 | 1748 | ts = value.as_timespan() |
paul@171 | 1749 | return ts and ts.convert(self.resolution) |
paul@123 | 1750 | else: |
paul@168 | 1751 | return value.convert(self.resolution) |
paul@123 | 1752 | |
paul@123 | 1753 | def __iter__(self): |
paul@123 | 1754 | return iter(self.values) |
paul@123 | 1755 | |
paul@123 | 1756 | def __len__(self): |
paul@123 | 1757 | return len(self.values) |
paul@123 | 1758 | |
paul@123 | 1759 | def __getitem__(self, i): |
paul@123 | 1760 | return self.values[i] |
paul@123 | 1761 | |
paul@123 | 1762 | def __setitem__(self, i, value): |
paul@123 | 1763 | self.values[i] = value |
paul@123 | 1764 | |
paul@123 | 1765 | def __contains__(self, value): |
paul@123 | 1766 | test_value = self.convert(value) |
paul@123 | 1767 | return test_value in self.values |
paul@123 | 1768 | |
paul@123 | 1769 | def append(self, value): |
paul@123 | 1770 | self.values.append(value) |
paul@123 | 1771 | |
paul@123 | 1772 | def insert(self, i, value): |
paul@123 | 1773 | self.values.insert(i, value) |
paul@123 | 1774 | |
paul@123 | 1775 | def pop(self): |
paul@123 | 1776 | return self.values.pop() |
paul@123 | 1777 | |
paul@124 | 1778 | def insert_in_order(self, value): |
paul@171 | 1779 | bisect.insort_left(self, value) |
paul@168 | 1780 | |
paul@93 | 1781 | def getCountry(s): |
paul@92 | 1782 | |
paul@93 | 1783 | "Find a country code in the given string 's'." |
paul@93 | 1784 | |
paul@93 | 1785 | match = country_code_regexp.search(s) |
paul@92 | 1786 | |
paul@93 | 1787 | if match: |
paul@93 | 1788 | return match.group("code") |
paul@93 | 1789 | else: |
paul@93 | 1790 | return None |
paul@67 | 1791 | |
paul@67 | 1792 | def getDate(s): |
paul@67 | 1793 | |
paul@127 | 1794 | "Parse the string 's', extracting and returning a date object." |
paul@127 | 1795 | |
paul@127 | 1796 | dt = getDateTime(s) |
paul@127 | 1797 | if dt is not None: |
paul@127 | 1798 | return dt.as_date() |
paul@127 | 1799 | else: |
paul@127 | 1800 | return None |
paul@123 | 1801 | |
paul@123 | 1802 | def getDateTime(s): |
paul@67 | 1803 | |
paul@140 | 1804 | """ |
paul@140 | 1805 | Parse the string 's', extracting and returning a datetime object where time |
paul@140 | 1806 | information has been given or a date object where time information is |
paul@140 | 1807 | absent. |
paul@140 | 1808 | """ |
paul@67 | 1809 | |
paul@92 | 1810 | m = datetime_regexp.search(s) |
paul@67 | 1811 | if m: |
paul@92 | 1812 | groups = list(m.groups()) |
paul@92 | 1813 | |
paul@94 | 1814 | # Convert date and time data to integer or None. |
paul@92 | 1815 | |
paul@140 | 1816 | return DateTime(map(int_or_none, groups[:6]) + [m.group("zone")]).as_datetime_or_date() |
paul@67 | 1817 | else: |
paul@67 | 1818 | return None |
paul@67 | 1819 | |
paul@88 | 1820 | def getDateStrings(s): |
paul@88 | 1821 | |
paul@88 | 1822 | "Parse the string 's', extracting and returning all date strings." |
paul@88 | 1823 | |
paul@88 | 1824 | start = 0 |
paul@88 | 1825 | m = date_regexp.search(s, start) |
paul@88 | 1826 | l = [] |
paul@88 | 1827 | while m: |
paul@88 | 1828 | l.append("-".join(m.groups())) |
paul@88 | 1829 | m = date_regexp.search(s, m.end()) |
paul@88 | 1830 | return l |
paul@88 | 1831 | |
paul@67 | 1832 | def getMonth(s): |
paul@67 | 1833 | |
paul@88 | 1834 | "Parse the string 's', extracting and returning a month object." |
paul@67 | 1835 | |
paul@67 | 1836 | m = month_regexp.search(s) |
paul@67 | 1837 | if m: |
paul@67 | 1838 | return Month(map(int, m.groups())) |
paul@67 | 1839 | else: |
paul@67 | 1840 | return None |
paul@67 | 1841 | |
paul@122 | 1842 | def getCurrentDate(): |
paul@122 | 1843 | |
paul@122 | 1844 | "Return the current date as a (year, month, day) tuple." |
paul@122 | 1845 | |
paul@122 | 1846 | today = datetime.date.today() |
paul@122 | 1847 | return Date((today.year, today.month, today.day)) |
paul@122 | 1848 | |
paul@67 | 1849 | def getCurrentMonth(): |
paul@67 | 1850 | |
paul@67 | 1851 | "Return the current month as a (year, month) tuple." |
paul@67 | 1852 | |
paul@67 | 1853 | today = datetime.date.today() |
paul@67 | 1854 | return Month((today.year, today.month)) |
paul@67 | 1855 | |
paul@67 | 1856 | def getCurrentYear(): |
paul@67 | 1857 | |
paul@67 | 1858 | "Return the current year." |
paul@67 | 1859 | |
paul@67 | 1860 | today = datetime.date.today() |
paul@67 | 1861 | return today.year |
paul@67 | 1862 | |
paul@184 | 1863 | # Location-related functions. |
paul@184 | 1864 | |
paul@184 | 1865 | class Reference: |
paul@184 | 1866 | |
paul@184 | 1867 | "A map reference." |
paul@184 | 1868 | |
paul@184 | 1869 | def __init__(self, degrees, minutes=0, seconds=0): |
paul@184 | 1870 | self.degrees = degrees |
paul@184 | 1871 | self.minutes = minutes |
paul@184 | 1872 | self.seconds = seconds |
paul@184 | 1873 | |
paul@184 | 1874 | def __repr__(self): |
paul@184 | 1875 | return "Reference(%d, %d, %d)" % (self.degrees, self.minutes, self.seconds) |
paul@184 | 1876 | |
paul@184 | 1877 | def __add__(self, other): |
paul@184 | 1878 | if not isinstance(other, Reference): |
paul@184 | 1879 | return NotImplemented |
paul@184 | 1880 | else: |
paul@184 | 1881 | s = sign(self.degrees) |
paul@184 | 1882 | o = sign(other.degrees) |
paul@184 | 1883 | carry, seconds = adc(s * self.seconds, o * other.seconds) |
paul@184 | 1884 | carry, minutes = adc(s * self.minutes, o * other.minutes + carry) |
paul@184 | 1885 | return Reference(self.degrees + other.degrees + carry, minutes, seconds) |
paul@184 | 1886 | |
paul@184 | 1887 | def __sub__(self, other): |
paul@184 | 1888 | if not isinstance(other, Reference): |
paul@184 | 1889 | return NotImplemented |
paul@184 | 1890 | else: |
paul@184 | 1891 | return self.__add__(Reference(-other.degrees, other.minutes, other.seconds)) |
paul@184 | 1892 | |
paul@185 | 1893 | def _compare(self, op, other): |
paul@185 | 1894 | if not isinstance(other, Reference): |
paul@185 | 1895 | return NotImplemented |
paul@185 | 1896 | else: |
paul@185 | 1897 | return op(self.to_degrees(), other.to_degrees()) |
paul@185 | 1898 | |
paul@185 | 1899 | def __eq__(self, other): |
paul@185 | 1900 | return self._compare(operator.eq, other) |
paul@185 | 1901 | |
paul@185 | 1902 | def __ne__(self, other): |
paul@185 | 1903 | return self._compare(operator.ne, other) |
paul@185 | 1904 | |
paul@185 | 1905 | def __lt__(self, other): |
paul@185 | 1906 | return self._compare(operator.lt, other) |
paul@185 | 1907 | |
paul@185 | 1908 | def __le__(self, other): |
paul@185 | 1909 | return self._compare(operator.le, other) |
paul@185 | 1910 | |
paul@185 | 1911 | def __gt__(self, other): |
paul@185 | 1912 | return self._compare(operator.gt, other) |
paul@185 | 1913 | |
paul@185 | 1914 | def __ge__(self, other): |
paul@185 | 1915 | return self._compare(operator.ge, other) |
paul@185 | 1916 | |
paul@184 | 1917 | def to_degrees(self): |
paul@184 | 1918 | return sign(self.degrees) * (abs(self.degrees) + self.minutes / 60.0 + self.seconds / 3600.0) |
paul@184 | 1919 | |
paul@184 | 1920 | def to_pixels(self, scale): |
paul@184 | 1921 | return self.to_degrees() * scale |
paul@184 | 1922 | |
paul@184 | 1923 | def adc(x, y): |
paul@184 | 1924 | result = x + y |
paul@184 | 1925 | return divmod(result, 60) |
paul@184 | 1926 | |
paul@184 | 1927 | def getPositionForReference(latitude, longitude, map_y, map_x, map_x_scale, map_y_scale): |
paul@184 | 1928 | return (longitude - map_x).to_pixels(map_x_scale), (latitude - map_y).to_pixels(map_y_scale) |
paul@184 | 1929 | |
paul@184 | 1930 | def getPositionForCentrePoint(position, map_x_scale, map_y_scale): |
paul@184 | 1931 | x, y = position |
paul@184 | 1932 | return x - map_x_scale / 2.0, y - map_y_scale / 2.0 |
paul@184 | 1933 | |
paul@184 | 1934 | def getMapReference(value): |
paul@184 | 1935 | |
paul@184 | 1936 | "Return a map reference by parsing the given 'value'." |
paul@184 | 1937 | |
paul@184 | 1938 | return Reference(*map(float, value.split(":"))) |
paul@184 | 1939 | |
paul@184 | 1940 | # vim: tabstop=4 expandtab shiftwidth=4 |
paul@184 | 1941 | |
paul@19 | 1942 | # User interface functions. |
paul@19 | 1943 | |
paul@55 | 1944 | def getParameter(request, name, default=None): |
paul@92 | 1945 | |
paul@92 | 1946 | """ |
paul@92 | 1947 | Using the given 'request', return the value of the parameter with the given |
paul@92 | 1948 | 'name', returning the optional 'default' (or None) if no value was supplied |
paul@92 | 1949 | in the 'request'. |
paul@92 | 1950 | """ |
paul@92 | 1951 | |
paul@110 | 1952 | return get_form(request).get(name, [default])[0] |
paul@23 | 1953 | |
paul@58 | 1954 | def getQualifiedParameter(request, calendar_name, argname, default=None): |
paul@92 | 1955 | |
paul@92 | 1956 | """ |
paul@92 | 1957 | Using the given 'request', 'calendar_name' and 'argname', retrieve the |
paul@92 | 1958 | value of the qualified parameter, returning the optional 'default' (or None) |
paul@92 | 1959 | if no value was supplied in the 'request'. |
paul@92 | 1960 | """ |
paul@92 | 1961 | |
paul@58 | 1962 | argname = getQualifiedParameterName(calendar_name, argname) |
paul@58 | 1963 | return getParameter(request, argname, default) |
paul@58 | 1964 | |
paul@58 | 1965 | def getQualifiedParameterName(calendar_name, argname): |
paul@92 | 1966 | |
paul@92 | 1967 | """ |
paul@92 | 1968 | Return the qualified parameter name using the given 'calendar_name' and |
paul@92 | 1969 | 'argname'. |
paul@92 | 1970 | """ |
paul@92 | 1971 | |
paul@58 | 1972 | if calendar_name is None: |
paul@58 | 1973 | return argname |
paul@58 | 1974 | else: |
paul@58 | 1975 | return "%s-%s" % (calendar_name, argname) |
paul@58 | 1976 | |
paul@122 | 1977 | def getParameterDate(arg): |
paul@122 | 1978 | |
paul@122 | 1979 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@122 | 1980 | |
paul@122 | 1981 | n = None |
paul@122 | 1982 | |
paul@128 | 1983 | if arg is None: |
paul@128 | 1984 | return None |
paul@128 | 1985 | |
paul@128 | 1986 | elif arg.startswith("current"): |
paul@122 | 1987 | date = getCurrentDate() |
paul@122 | 1988 | if len(arg) > 8: |
paul@122 | 1989 | n = int(arg[7:]) |
paul@122 | 1990 | |
paul@122 | 1991 | elif arg.startswith("yearstart"): |
paul@122 | 1992 | date = Date((getCurrentYear(), 1, 1)) |
paul@122 | 1993 | if len(arg) > 10: |
paul@122 | 1994 | n = int(arg[9:]) |
paul@122 | 1995 | |
paul@122 | 1996 | elif arg.startswith("yearend"): |
paul@122 | 1997 | date = Date((getCurrentYear(), 12, 31)) |
paul@122 | 1998 | if len(arg) > 8: |
paul@122 | 1999 | n = int(arg[7:]) |
paul@122 | 2000 | |
paul@122 | 2001 | else: |
paul@122 | 2002 | date = getDate(arg) |
paul@122 | 2003 | |
paul@122 | 2004 | if n is not None: |
paul@122 | 2005 | date = date.day_update(n) |
paul@122 | 2006 | |
paul@122 | 2007 | return date |
paul@122 | 2008 | |
paul@19 | 2009 | def getParameterMonth(arg): |
paul@67 | 2010 | |
paul@67 | 2011 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@67 | 2012 | |
paul@19 | 2013 | n = None |
paul@19 | 2014 | |
paul@128 | 2015 | if arg is None: |
paul@128 | 2016 | return None |
paul@128 | 2017 | |
paul@128 | 2018 | elif arg.startswith("current"): |
paul@19 | 2019 | date = getCurrentMonth() |
paul@19 | 2020 | if len(arg) > 8: |
paul@19 | 2021 | n = int(arg[7:]) |
paul@19 | 2022 | |
paul@19 | 2023 | elif arg.startswith("yearstart"): |
paul@67 | 2024 | date = Month((getCurrentYear(), 1)) |
paul@19 | 2025 | if len(arg) > 10: |
paul@19 | 2026 | n = int(arg[9:]) |
paul@19 | 2027 | |
paul@19 | 2028 | elif arg.startswith("yearend"): |
paul@67 | 2029 | date = Month((getCurrentYear(), 12)) |
paul@19 | 2030 | if len(arg) > 8: |
paul@19 | 2031 | n = int(arg[7:]) |
paul@19 | 2032 | |
paul@19 | 2033 | else: |
paul@19 | 2034 | date = getMonth(arg) |
paul@19 | 2035 | |
paul@19 | 2036 | if n is not None: |
paul@67 | 2037 | date = date.month_update(n) |
paul@19 | 2038 | |
paul@19 | 2039 | return date |
paul@19 | 2040 | |
paul@122 | 2041 | def getFormDate(request, calendar_name, argname): |
paul@122 | 2042 | |
paul@122 | 2043 | """ |
paul@122 | 2044 | Return the date from the 'request' for the calendar with the given |
paul@122 | 2045 | 'calendar_name' using the parameter having the given 'argname'. |
paul@122 | 2046 | """ |
paul@122 | 2047 | |
paul@122 | 2048 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 2049 | return getParameterDate(arg) |
paul@122 | 2050 | |
paul@19 | 2051 | def getFormMonth(request, calendar_name, argname): |
paul@67 | 2052 | |
paul@67 | 2053 | """ |
paul@67 | 2054 | Return the month from the 'request' for the calendar with the given |
paul@67 | 2055 | 'calendar_name' using the parameter having the given 'argname'. |
paul@67 | 2056 | """ |
paul@67 | 2057 | |
paul@58 | 2058 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 2059 | return getParameterMonth(arg) |
paul@19 | 2060 | |
paul@127 | 2061 | def getFormDateTriple(request, yeararg, montharg, dayarg): |
paul@127 | 2062 | |
paul@127 | 2063 | """ |
paul@127 | 2064 | Return the date from the 'request' for the calendar with the given |
paul@127 | 2065 | 'calendar_name' using the parameters having the given 'yeararg', 'montharg' |
paul@127 | 2066 | and 'dayarg' names. |
paul@127 | 2067 | """ |
paul@127 | 2068 | |
paul@127 | 2069 | year = getParameter(request, yeararg) |
paul@127 | 2070 | month = getParameter(request, montharg) |
paul@127 | 2071 | day = getParameter(request, dayarg) |
paul@127 | 2072 | if year and month and day: |
paul@127 | 2073 | return Date((int(year), int(month), int(day))) |
paul@19 | 2074 | else: |
paul@19 | 2075 | return None |
paul@19 | 2076 | |
paul@23 | 2077 | def getFormMonthPair(request, yeararg, montharg): |
paul@67 | 2078 | |
paul@67 | 2079 | """ |
paul@67 | 2080 | Return the month from the 'request' for the calendar with the given |
paul@67 | 2081 | 'calendar_name' using the parameters having the given 'yeararg' and |
paul@67 | 2082 | 'montharg' names. |
paul@67 | 2083 | """ |
paul@67 | 2084 | |
paul@23 | 2085 | year = getParameter(request, yeararg) |
paul@23 | 2086 | month = getParameter(request, montharg) |
paul@23 | 2087 | if year and month: |
paul@67 | 2088 | return Month((int(year), int(month))) |
paul@23 | 2089 | else: |
paul@23 | 2090 | return None |
paul@23 | 2091 | |
paul@122 | 2092 | def getFullDateLabel(request, date): |
paul@122 | 2093 | |
paul@122 | 2094 | """ |
paul@122 | 2095 | Return the full month plus year label using the given 'request' and |
paul@122 | 2096 | 'year_month'. |
paul@122 | 2097 | """ |
paul@122 | 2098 | |
paul@128 | 2099 | if not date: |
paul@128 | 2100 | return "" |
paul@128 | 2101 | |
paul@122 | 2102 | _ = request.getText |
paul@122 | 2103 | year, month, day = date.as_tuple()[:3] |
paul@125 | 2104 | start_weekday, number_of_days = date.month_properties() |
paul@125 | 2105 | weekday = (start_weekday + day - 1) % 7 |
paul@125 | 2106 | day_label = _(getDayLabel(weekday)) |
paul@122 | 2107 | month_label = _(getMonthLabel(month)) |
paul@122 | 2108 | return "%s %s %s %s" % (day_label, day, month_label, year) |
paul@122 | 2109 | |
paul@114 | 2110 | def getFullMonthLabel(request, year_month): |
paul@114 | 2111 | |
paul@114 | 2112 | """ |
paul@114 | 2113 | Return the full month plus year label using the given 'request' and |
paul@114 | 2114 | 'year_month'. |
paul@114 | 2115 | """ |
paul@114 | 2116 | |
paul@128 | 2117 | if not year_month: |
paul@128 | 2118 | return "" |
paul@128 | 2119 | |
paul@114 | 2120 | _ = request.getText |
paul@122 | 2121 | year, month = year_month.as_tuple()[:2] |
paul@114 | 2122 | month_label = _(getMonthLabel(month)) |
paul@114 | 2123 | return "%s %s" % (month_label, year) |
paul@114 | 2124 | |
paul@67 | 2125 | # Page-related functions. |
paul@67 | 2126 | |
paul@19 | 2127 | def getPrettyPageName(page): |
paul@19 | 2128 | |
paul@19 | 2129 | "Return a nicely formatted title/name for the given 'page'." |
paul@19 | 2130 | |
paul@117 | 2131 | title = page.split_title(force=1) |
paul@55 | 2132 | return getPrettyTitle(title) |
paul@55 | 2133 | |
paul@27 | 2134 | def linkToPage(request, page, text, query_string=None): |
paul@27 | 2135 | |
paul@27 | 2136 | """ |
paul@27 | 2137 | Using 'request', return a link to 'page' with the given link 'text' and |
paul@27 | 2138 | optional 'query_string'. |
paul@27 | 2139 | """ |
paul@27 | 2140 | |
paul@27 | 2141 | text = wikiutil.escape(text) |
paul@117 | 2142 | return page.link_to_raw(request, text, query_string) |
paul@27 | 2143 | |
paul@88 | 2144 | def getFullPageName(parent, title): |
paul@88 | 2145 | |
paul@88 | 2146 | """ |
paul@88 | 2147 | Return a full page name from the given 'parent' page (can be empty or None) |
paul@88 | 2148 | and 'title' (a simple page name). |
paul@88 | 2149 | """ |
paul@88 | 2150 | |
paul@88 | 2151 | if parent: |
paul@88 | 2152 | return "%s/%s" % (parent.rstrip("/"), title) |
paul@88 | 2153 | else: |
paul@88 | 2154 | return title |
paul@88 | 2155 | |
paul@88 | 2156 | def fillEventPageFromTemplate(template_page, new_page, event_details, category_pagenames): |
paul@88 | 2157 | |
paul@88 | 2158 | """ |
paul@88 | 2159 | Using the given 'template_page', complete the 'new_page' by copying the |
paul@88 | 2160 | template and adding the given 'event_details' (a dictionary of event |
paul@88 | 2161 | fields), setting also the 'category_pagenames' to define category |
paul@88 | 2162 | membership. |
paul@88 | 2163 | """ |
paul@88 | 2164 | |
paul@88 | 2165 | event_page = EventPage(template_page) |
paul@88 | 2166 | new_event_page = EventPage(new_page) |
paul@88 | 2167 | new_event_page.copyPage(event_page) |
paul@88 | 2168 | |
paul@88 | 2169 | if new_event_page.getFormat() == "wiki": |
paul@88 | 2170 | new_event = Event(new_event_page, event_details) |
paul@88 | 2171 | new_event_page.setEvents([new_event]) |
paul@88 | 2172 | new_event_page.setCategoryMembership(category_pagenames) |
paul@88 | 2173 | new_event_page.saveChanges() |
paul@88 | 2174 | |
paul@180 | 2175 | # Formatting-related functions. |
paul@180 | 2176 | |
paul@180 | 2177 | def getParserClass(request, format): |
paul@180 | 2178 | |
paul@180 | 2179 | """ |
paul@180 | 2180 | Return a parser class using the 'request' for the given 'format', returning |
paul@180 | 2181 | a plain text parser if no parser can be found for the specified 'format'. |
paul@180 | 2182 | """ |
paul@180 | 2183 | |
paul@180 | 2184 | try: |
paul@180 | 2185 | return wikiutil.searchAndImportPlugin(request.cfg, "parser", format or "plain") |
paul@180 | 2186 | except wikiutil.PluginMissingError: |
paul@180 | 2187 | return wikiutil.searchAndImportPlugin(request.cfg, "parser", "plain") |
paul@180 | 2188 | |
paul@180 | 2189 | def getFormatter(request, mimetype, page): |
paul@180 | 2190 | |
paul@180 | 2191 | """ |
paul@180 | 2192 | Return a formatter using the given 'request' for the given 'mimetype' for |
paul@180 | 2193 | use on the indicated 'page'. |
paul@180 | 2194 | """ |
paul@180 | 2195 | |
paul@180 | 2196 | try: |
paul@180 | 2197 | cls = wikiutil.searchAndImportPlugin(request.cfg, "formatter", mimetype) |
paul@180 | 2198 | except wikiutil.PluginMissingError: |
paul@180 | 2199 | cls = wikiutil.searchAndImportPlugin(request.cfg, "formatter", "text/plain") |
paul@180 | 2200 | fmt = request.formatter = page.formatter = cls(request) |
paul@180 | 2201 | fmt.setPage(page) |
paul@180 | 2202 | return fmt |
paul@180 | 2203 | |
paul@180 | 2204 | def formatText(text, request, fmt, parser_cls): |
paul@180 | 2205 | |
paul@180 | 2206 | """ |
paul@180 | 2207 | Format the given 'text' using the specified 'request', formatter 'fmt' and |
paul@180 | 2208 | parser class 'parser_cls'. |
paul@180 | 2209 | """ |
paul@180 | 2210 | |
paul@180 | 2211 | # Suppress line anchors. |
paul@180 | 2212 | |
paul@180 | 2213 | parser = parser_cls(text, request, line_anchors=False) |
paul@180 | 2214 | |
paul@180 | 2215 | # Fix lists by indicating that a paragraph is already started. |
paul@180 | 2216 | |
paul@180 | 2217 | return request.redirectedOutput(parser.format, fmt, inhibit_p=True) |
paul@180 | 2218 | |
paul@10 | 2219 | # vim: tabstop=4 expandtab shiftwidth=4 |