PK68sE--WikiTemplates/model.pyc; =uEc@sDdkZdkTdklZdklZdefdYZdS(N(s*(s WikiSystem(s to_unicodes WikiTemplatecBsqtZdZeeeedZeeedZeddZeedZeedZ edZ RS(s)Represents a wiki page (new or existing).cCs||_||_||_|o|i||||nd|_d|_d|_|i|_ |i|_ |ii i dt |iidS(NissWikiTemplate: '%s'(senvsselfsnamestables_fetchsversionsdbstextsreadonlysold_texts old_readonlyslogsdebugs to_unicodes__dict__sitems(sselfsenvsnamesversionsdbstable((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pys__init__s        c Cs1| o|ii}n|i}d}|o|d|7}n |d7}|o$|i|d|t |fn|i|d|f|i } | oH| \}}}t ||_||_ |o t |pd|_nd|_d|_ d|_|iiidt|iidS( Ns"SELECT version,text,readonly FROM s%s s templates sWHERE name=%s AND version=%ss+WHERE name=%s ORDER BY version DESC LIMIT 1issWikiTemplate Fetched: '%s'(sdbsselfsenvs get_db_cnxscursorsQUERYstablesversionsexecutesnamesintsfetchonesrowstextsreadonlyslogsdebugs to_unicodes__dict__sitems( sselfsnamesversionsdbstablestextscursorsreadonlysQUERYsrow((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pys_fetch,s.       !   sfgetcCs |idjS(Ni(sselfsversion(sself((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pysJsc Cs|ip td| o|ii}t}nt}t}|i }|t jo4|i d|if|iiid|in:|i d|i|f|iiid||if|t jp ||i jo|i|it |n|i oqdkl}x3|i|id|i|D]}|i|q5Wx+t|iiD]}|i|q_Wn|o|indS(NsCannot delete non-existent pages#DELETE FROM templates WHERE name=%ssDeleted page %ss2DELETE FROM templates WHERE name=%s and version=%ssDeleted version %d of page %s(s Attachments templates(sselfsexistssAssertionErrorsdbsenvs get_db_cnxsTrues handle_tasFalses page_deletedscursorsversionsNonesexecutesnameslogsinfos_fetchstrac.attachments Attachmentsselects attachmentsdeletes WikiSystemschange_listenersslistenerswiki_page_deletedscommit( sselfsversionsdbslisteners attachments page_deletedscursors handle_tas Attachment((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pysdeleteLs6        c Cs| o|ii}t}nt}|tjot i }n|i |i joW|i }|i d|i|id||||i ||if|id7_nL|i|ijo,|i }|i d|i|ifn td|o|inxZt|iiD]F}|idjo|i|q!|i||i||||q!W|i|_|i |_ dS(NslINSERT INTO templates (name,version,time,author,ipnr,text,comment,readonly) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)is.UPDATE templates SET readonly=%s WHERE name=%ssPage not modified(sdbsselfsenvs get_db_cnxsTrues handle_tasFalsestsNonestimestextsold_textscursorsexecutesnamesversionsauthors remote_addrscommentsreadonlys old_readonlys TracErrorscommits WikiSystemschange_listenersslistenerswiki_page_addedswiki_page_changed( sselfsauthorscomments remote_addrstsdbslistenerscursors handle_ta((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pyssaveus4    /    ccsz| o|ii}n|i}|id|i|ifx0|D](\}}}}}|||||fVqJWdS(NsjSELECT version,time,author,comment,ipnr FROM templates WHERE name=%s AND version<=%s ORDER BY version DESC( sdbsselfsenvs get_db_cnxscursorsexecutesnamesversionstimesauthorscommentsipnr(sselfsdbscommentsauthorscursorsversionstimesipnr((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pys get_historys  ( s__name__s __module__s__doc__sNones__init__s_fetchspropertysexistssdeletessaves get_history(((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pys WikiTemplates )%(stimes trac.cores trac.wiki.apis WikiSystemstrac.util.texts to_unicodesobjects WikiTemplate(s to_unicodes WikiSystems WikiTemplatestime((s7build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/model.pys?s   PK}25{bAOcOcWikiTemplates/attachment.py# -*- coding: iso-8859-1 -*- # # Copyright (C) 2003-2005 Edgewall Software # Copyright (C) 2003-2005 Jonas Borgström # Copyright (C) 2005 Christopher Lenz # Copyright (C) 2006 Pedro Algarvio # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Jonas Borgström # Christopher Lenz # Pedro Algarvio import os import re import shutil import time import unicodedata from trac import perm, util from trac.config import BoolOption, IntOption from trac.core import * from trac.env import IEnvironmentSetupParticipant from trac.mimeview import * from trac.util import get_reporter_id, create_unique_file from trac.util.datefmt import format_datetime, pretty_timedelta from trac.util.html import Markup, html from trac.util.text import unicode_quote, unicode_unquote, pretty_size from trac.web import HTTPBadRequest, IRequestHandler from trac.web.chrome import add_link, add_stylesheet, INavigationContributor from trac.wiki.api import IWikiSyntaxProvider from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner class InvalidAttachment(TracError): """Exception raised when attachment validation fails.""" class IAttachmentChangeListener(Interface): """Extension point interface for components that require notification when attachments are created or deleted.""" def attachment_added(attachment): """Called when an attachment is added.""" def attachment_deleted(attachment): """Called when an attachment is deleted.""" class IAttachmentManipulator(Interface): """Extension point interface for components that need to manipulate attachments. Unlike change listeners, a manipulator can reject changes being committed to the database.""" def prepare_attachment(req, attachment, fields): """Not currently called, but should be provided for future compatibility.""" def validate_attachment(req, attachment): """Validate an attachment after upload but before being stored in Trac environment. Must return a list of `(field, message)` tuples, one for each problem detected. `field` can be any of `description`, `username`, `filename`, `content`, or `None` to indicate an overall problem with the attachment. Therefore, a return value of `[]` means everything is OK.""" class Attachment(object): def __init__(self, env, parent_type, parent_id, filename=None, db=None): self.env = env self.parent_type = parent_type self.parent_id = unicode(parent_id) if filename: self._fetch(filename, db) else: self.filename = None self.description = None self.size = None self.time = None self.author = None self.ipnr = None def _fetch(self, filename, db=None): if not db: db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT filename,description,size,time,author,ipnr " "FROM attachment WHERE type=%s AND id=%s " "AND filename=%s ORDER BY time", (self.parent_type, unicode(self.parent_id), filename)) row = cursor.fetchone() cursor.close() if not row: self.filename = filename raise TracError('Attachment %s does not exist.' % (self.title), 'Invalid Attachment') self.filename = row[0] self.description = row[1] self.size = row[2] and int(row[2]) or 0 self.time = row[3] and int(row[3]) or 0 self.author = row[4] self.ipnr = row[5] def _get_path(self): path = os.path.join(self.env.path, 'attachments', self.parent_type, unicode_quote(self.parent_id)) if self.filename: path = os.path.join(path, unicode_quote(self.filename)) return os.path.normpath(path) path = property(_get_path) def href(self, req, *args, **dict): return req.href.attachment(self.parent_type, self.parent_id, self.filename, *args, **dict) def parent_href(self, req): return req.href(self.parent_type, self.parent_id) def _get_title(self): return '%s%s: %s' % (self.parent_type == 'ticket' and '#' or '', self.parent_id, self.filename) title = property(_get_title) def delete(self, db=None): assert self.filename, 'Cannot delete non-existent attachment' if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False cursor = db.cursor() cursor.execute("DELETE FROM attachment WHERE type=%s AND id=%s " "AND filename=%s", (self.parent_type, self.parent_id, self.filename)) if os.path.isfile(self.path): try: os.unlink(self.path) except OSError: self.env.log.error('Failed to delete attachment file %s', self.path, exc_info=True) if handle_ta: db.rollback() raise TracError, 'Could not delete attachment' self.env.log.info('Attachment removed: %s' % self.title) if handle_ta: db.commit() for listener in AttachmentModule(self.env).change_listeners: listener.attachment_deleted(self) def insert(self, filename, fileobj, size, t=None, db=None): if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False self.size = size and int(size) or 0 self.time = int(t or time.time()) # Make sure the path to the attachment is inside the environment # attachments directory attachments_dir = os.path.join(os.path.normpath(self.env.path), 'attachments') commonprefix = os.path.commonprefix([attachments_dir, self.path]) assert commonprefix == attachments_dir if not os.access(self.path, os.F_OK): os.makedirs(self.path) filename = unicode_quote(filename) path, targetfile = create_unique_file(os.path.join(self.path, filename)) try: # Note: `path` is an unicode string because `self.path` was one. # As it contains only quoted chars and numbers, we can use `ascii` basename = os.path.basename(path).encode('ascii') filename = unicode_unquote(basename) cursor = db.cursor() cursor.execute("INSERT INTO attachment " "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", (self.parent_type, self.parent_id, filename, self.size, self.time, self.description, self.author, self.ipnr)) shutil.copyfileobj(fileobj, targetfile) self.filename = filename self.env.log.info('New attachment: %s by %s', self.title, self.author) if handle_ta: db.commit() for listener in AttachmentModule(self.env).change_listeners: listener.attachment_added(self) finally: targetfile.close() def select(cls, env, parent_type, parent_id, db=None): if not db: db = env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT filename,description,size,time,author,ipnr " "FROM attachment WHERE type=%s AND id=%s ORDER BY time", (parent_type, unicode(parent_id))) for filename,description,size,time,author,ipnr in cursor: attachment = Attachment(env, parent_type, parent_id) attachment.filename = filename attachment.description = description attachment.size = size and int(size) or 0 attachment.time = time and int(time) or 0 attachment.author = author attachment.ipnr = ipnr yield attachment def delete_all(cls, env, parent_type, parent_id, db): """Delete all attachments of a given resource. As this is usually done while deleting the parent resource, the `db` argument is ''not'' optional here. """ attachment_dir = None for attachment in list(cls.select(env, parent_type, parent_id, db)): attachment_dir = os.path.dirname(attachment.path) attachment.delete(db) if attachment_dir: try: os.rmdir(attachment_dir) except OSError: env.log.error("Can't delete attachment directory %s", attachment_dir, exc_info=True) select = classmethod(select) delete_all = classmethod(delete_all) def open(self): self.env.log.debug('Trying to open attachment at %s', self.path) try: fd = open(self.path, 'rb') except IOError: raise TracError('Attachment %s not found' % self.filename) return fd # Templating utilities def attachments_to_hdf(env, req, db, parent_type, parent_id): return [attachment_to_hdf(env, req, db, attachment) for attachment in Attachment.select(env, parent_type, parent_id, db)] def attachment_to_hdf(env, req, db, attachment): if not db: db = env.get_db_cnx() hdf = { 'filename': attachment.filename, 'description': wiki_to_oneliner(attachment.description, env, db), 'author': attachment.author, 'ipnr': attachment.ipnr, 'size': pretty_size(attachment.size), 'time': format_datetime(attachment.time), 'age': pretty_timedelta(attachment.time), 'href': attachment.href(req) } return hdf class AttachmentModule(Component): implements(IEnvironmentSetupParticipant, IRequestHandler, INavigationContributor, IWikiSyntaxProvider) change_listeners = ExtensionPoint(IAttachmentChangeListener) manipulators = ExtensionPoint(IAttachmentManipulator) CHUNK_SIZE = 4096 max_size = IntOption('attachment', 'max_size', 262144, """Maximum allowed file size for ticket and wiki attachments.""") render_unsafe_content = BoolOption('attachment', 'render_unsafe_content', 'false', """Whether non-binary attachments should be rendered in the browser, or only made downloadable. Pretty much any text file may be interpreted as HTML by the browser, which allows a malicious user to attach a file containing cross-site scripting attacks. For public sites where anonymous users can create attachments, it is recommended to leave this option disabled (which is the default).""") # IEnvironmentSetupParticipant methods def environment_created(self): """Create the attachments directory.""" if self.env.path: os.mkdir(os.path.join(self.env.path, 'attachments')) def environment_needs_upgrade(self, db): return False def upgrade_environment(self, db): pass # INavigationContributor methods def get_active_navigation_item(self, req): return req.args.get('type') def get_navigation_items(self, req): return [] # IRequestHandler methods def match_request(self, req): match = re.match(r'^/attachment/(ticket|wiki|templates)(?:[/:](.*))?$', req.path_info) if match: req.args['type'] = match.group(1) req.args['path'] = match.group(2).replace(':', '/') return True def process_request(self, req): parent_type = req.args.get('type') path = req.args.get('path') if not parent_type or not path: raise HTTPBadRequest('Bad request') if not parent_type in ['ticket', 'wiki', 'templates']: raise HTTPBadRequest('Unknown attachment type') action = req.args.get('action', 'view') if action == 'new': attachment = Attachment(self.env, parent_type, path) else: segments = path.split('/') parent_id = '/'.join(segments[:-1]) last_segment = segments[-1] if len(segments) == 1: self._render_list(req, parent_type, last_segment) return 'attachment.cs', None if not last_segment: raise HTTPBadRequest('Bad request') attachment = Attachment(self.env, parent_type, parent_id, last_segment) parent_link, parent_text = self._parent_to_hdf( req, attachment.parent_type, attachment.parent_id) if req.method == 'POST': if action == 'new': self._do_save(req, attachment) elif action == 'delete': self._do_delete(req, attachment) elif action == 'delete': self._render_confirm(req, attachment) elif action == 'new': self._render_form(req, attachment) else: add_link(req, 'up', parent_link, parent_text) self._render_view(req, attachment) add_stylesheet(req, 'common/css/code.css') return 'attachment.cs', None def _parent_to_hdf(self, req, parent_type, parent_id): # Populate attachment.parent: parent_link = req.href(parent_type, parent_id) if parent_type == 'ticket': parent_text = 'Ticket #' + parent_id else: # 'wiki' parent_text = parent_id req.hdf['attachment.parent'] = { 'type': parent_type, 'id': parent_id, 'name': parent_text, 'href': parent_link } return parent_link, parent_text # IWikiSyntaxProvider methods def get_wiki_syntax(self): return [] def get_link_resolvers(self): yield ('attachment', self._format_link) # Public methods def get_history(self, start, stop, type): """Return an iterable of tuples describing changes to attachments on a particular object type. The tuples are in the form (change, type, id, filename, time, description, author). `change` can currently only be `created`.""" # Traverse attachment directory db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT type, id, filename, time, description, author " " FROM attachment " " WHERE time > %s AND time < %s " " AND type = %s", (start, stop, type)) for type, id, filename, time, description, author in cursor: yield ('created', type, id, filename, time, description, author) def get_timeline_events(self, req, db, type, format, start, stop, display): """Return an iterable of events suitable for ITimelineEventProvider. `display` is a callback for formatting the attachment's parent """ for change, type, id, filename, time, descr, author in \ self.get_history(start, stop, type): title = html.EM(os.path.basename(filename)) + \ ' attached to ' + display(id) if format == 'rss': descr = wiki_to_html(descr or '--', self.env, req, db, absurls=True) href = req.abs_href else: descr = wiki_to_oneliner(descr, self.env, db, shorten=True) title += Markup(' by %s', author) href = req.href yield('attachment', href.attachment(type, id, filename), title, time, author, descr) # Internal methods def _do_save(self, req, attachment): perm_map = { 'ticket': 'TICKET_APPEND', 'wiki': 'WIKI_MODIFY', 'templates': 'TEMPLATES_MODIFY', } req.perm.assert_permission(perm_map[attachment.parent_type]) if req.args.has_key('cancel'): req.redirect(attachment.parent_href(req)) upload = req.args['attachment'] if not hasattr(upload, 'filename') or not upload.filename: raise TracError('No file uploaded') if hasattr(upload.file, 'fileno'): size = os.fstat(upload.file.fileno())[6] else: size = upload.file.len if size == 0: raise TracError("Can't upload empty file") # Maximum attachment size (in bytes) max_size = self.max_size if max_size >= 0 and size > max_size: raise TracError('Maximum attachment size: %d bytes' % max_size, 'Upload failed') # We try to normalize the filename to unicode NFC if we can. # Files uploaded from OS X might be in NFD. filename = unicodedata.normalize('NFC', unicode(upload.filename, 'utf-8')) filename = filename.replace('\\', '/').replace(':', '/') filename = os.path.basename(filename) if not filename: raise TracError('No file uploaded') attachment.description = req.args.get('description', '') attachment.author = get_reporter_id(req, 'author') attachment.ipnr = req.remote_addr # Validate attachment for manipulator in self.manipulators: for field, message in manipulator.validate_attachment(req, attachment): if field: raise InvalidAttachment('Attachment field %s is invalid: %s' % (field, message)) else: raise InvalidAttachment('Invalid attachment: %s' % message) if req.args.get('replace'): try: old_attachment = Attachment(self.env, attachment.parent_type, attachment.parent_id, filename) if not (old_attachment.author and req.authname \ and old_attachment.author == req.authname): perm_map = { 'ticket': 'TICKET_ADMIN', 'wiki': 'WIKI_DELETE', 'templates': 'TEMPLATES_DELETE' } req.perm.assert_permission(perm_map[old_attachment.parent_type]) old_attachment.delete() except TracError: pass # don't worry if there's nothing to replace attachment.filename = None attachment.insert(filename, upload.file, size) # Redirect the user to the newly created attachment req.redirect(attachment.href(req)) def _do_delete(self, req, attachment): perm_map = { 'ticket': 'TICKET_ADMIN', 'wiki': 'WIKI_DELETE', 'templates': 'TEMPLATES_DELETE' } req.perm.assert_permission(perm_map[attachment.parent_type]) if req.args.has_key('cancel'): req.redirect(attachment.href(req)) attachment.delete() # Redirect the user to the attachment parent page req.redirect(attachment.parent_href(req)) def _render_confirm(self, req, attachment): perm_map = { 'ticket': 'TICKET_ADMIN', 'wiki': 'WIKI_DELETE', 'templates': 'TEMPLATES_DELETE' } req.perm.assert_permission(perm_map[attachment.parent_type]) req.hdf['title'] = '%s (delete)' % attachment.title req.hdf['attachment'] = {'filename': attachment.filename, 'mode': 'delete'} def _render_form(self, req, attachment): perm_map = { 'ticket': 'TICKET_APPEND', 'wiki': 'WIKI_MODIFY', 'templates': 'TEMPLATES_MODIFY' } req.perm.assert_permission(perm_map[attachment.parent_type]) req.hdf['attachment'] = {'mode': 'new', 'author': get_reporter_id(req)} def _render_view(self, req, attachment): perm_map = { 'ticket': 'TICKET_VIEW', 'wiki': 'WIKI_VIEW', 'templates': 'TEMPLATES_VIEW' } req.perm.assert_permission(perm_map[attachment.parent_type]) req.check_modified(attachment.time) # Render HTML view req.hdf['title'] = attachment.title req.hdf['attachment'] = attachment_to_hdf(self.env, req, None, attachment) # Override the 'oneliner' req.hdf['attachment.description'] = wiki_to_html(attachment.description, self.env, req) perm_map = { 'ticket': 'TICKET_ADMIN', 'wiki': 'WIKI_DELETE', 'templates': 'TEMPLATES_DELETE' } if req.perm.has_permission(perm_map[attachment.parent_type]): req.hdf['attachment.can_delete'] = 1 fd = attachment.open() try: mimeview = Mimeview(self.env) # MIME type detection str_data = fd.read(1000) fd.seek(0) binary = is_binary(str_data) mime_type = mimeview.get_mimetype(attachment.filename, str_data) # Eventually send the file directly format = req.args.get('format') if format in ('raw', 'txt'): if not self.render_unsafe_content and not binary: # Force browser to download HTML/SVG/etc pages that may # contain malicious code enabling XSS attacks req.send_header('Content-Disposition', 'attachment;' + 'filename=' + attachment.filename) if not mime_type or (self.render_unsafe_content and \ not binary and format == 'txt'): mime_type = 'text/plain' if 'charset=' not in mime_type: charset = mimeview.get_charset(str_data, mime_type) mime_type = mime_type + '; charset=' + charset req.send_file(attachment.path, mime_type) # add ''Plain Text'' alternate link if needed if self.render_unsafe_content and not binary and \ mime_type and not mime_type.startswith('text/plain'): plaintext_href = attachment.href(req, format='txt') add_link(req, 'alternate', plaintext_href, 'Plain Text', mime_type) # add ''Original Format'' alternate link (always) raw_href = attachment.href(req, format='raw') add_link(req, 'alternate', raw_href, 'Original Format', mime_type) self.log.debug("Rendering preview of file %s with mime-type %s" % (attachment.filename, mime_type)) req.hdf['attachment'] = mimeview.preview_to_hdf( req, fd, os.fstat(fd.fileno()).st_size, mime_type, attachment.filename, raw_href, annotations=['lineno']) finally: fd.close() def _render_list(self, req, p_type, p_id): self._parent_to_hdf(req, p_type, p_id) req.hdf['attachment'] = { 'mode': 'list', 'list': attachments_to_hdf(self.env, req, None, p_type, p_id), 'attach_href': req.href.attachment(p_type, p_id) } def _format_link(self, formatter, ns, target, label): link, params, fragment = formatter.split_link(target) ids = link.split(':', 2) if len(ids) == 3: parent_type, parent_id, filename = ids else: # FIXME: the formatter should know which object the text being # formatter belongs to parent_type, parent_id = 'wiki', 'WikiStart' if formatter.req: path_info = formatter.req.path_info.split('/', 2) if len(path_info) > 1: parent_type = path_info[1] if len(path_info) > 2: parent_id = path_info[2] filename = link href = formatter.href() try: attachment = Attachment(self.env, parent_type, parent_id, filename) if formatter.req: href = attachment.href(formatter.req) + params return html.A(label, class_='attachment', href=href, title='Attachment %s' % attachment.title) except TracError: return html.A(label, class_='missing attachment', rel='nofollow', href=formatter.href()) PKJ8YcgnWikiTemplates/__init__.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: __init__.py 55 2008-02-10 05:39:31Z s0undt3ch $ # ============================================================================= # $URL$ # $LastChangedDate$ # $Rev$ # $LastChangedBy$ # ============================================================================= ############################################################################### # # # Copyright 2006 by Pedro Algarvio # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 2 of the License, or (at your option) # # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # ############################################################################### # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= import web_ui, model, attachment from macros import * PK68s}t}tWikiTemplates/attachment.pyc; EEc@sdkZdkZdkZdkZdkZdklZlZdkl Z l Z dk Tdk l Z dkTdklZlZdklZlZdklZlZdklZlZlZd klZlZd kl Z l!Z!l"Z"d k#l$Z$d k%l&Z&l'Z'd e(fdYZ)de*fdYZ+de*fdYZ,de-fdYZ.dZ/dZ0de1fdYZ2dS(N(spermsutil(s BoolOptions IntOption(s*(sIEnvironmentSetupParticipant(sget_reporter_idscreate_unique_file(sformat_datetimespretty_timedelta(sMarkupshtml(s unicode_quotesunicode_unquotes pretty_size(sHTTPBadRequestsIRequestHandler(sadd_linksadd_stylesheetsINavigationContributor(sIWikiSyntaxProvider(s wiki_to_htmlswiki_to_onelinersInvalidAttachmentcBstZdZRS(s2Exception raised when attachment validation fails.(s__name__s __module__s__doc__(((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysInvalidAttachment*s sIAttachmentChangeListenercBs tZdZdZdZRS(soExtension point interface for components that require notification when attachments are created or deleted.cCsdS(s#Called when an attachment is added.N((s attachment((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysattachment_added1scCsdS(s%Called when an attachment is deleted.N((s attachment((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysattachment_deleted4s(s__name__s __module__s__doc__sattachment_addedsattachment_deleted(((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysIAttachmentChangeListener.s  sIAttachmentManipulatorcBs tZdZdZdZRS(sExtension point interface for components that need to manipulate attachments. Unlike change listeners, a manipulator can reject changes being committed to the database.cCsdS(sNNot currently called, but should be provided for future compatibility.N((sreqs attachmentsfields((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysprepare_attachment>scCsdS(sValidate an attachment after upload but before being stored in Trac environment. Must return a list of `(field, message)` tuples, one for each problem detected. `field` can be any of `description`, `username`, `filename`, `content`, or `None` to indicate an overall problem with the attachment. Therefore, a return value of `[]` means everything is OK.N((sreqs attachment((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysvalidate_attachmentBs(s__name__s __module__s__doc__sprepare_attachmentsvalidate_attachment(((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysIAttachmentManipulator8s  s AttachmentcBstZeedZedZdZeeZdZdZ dZ ee Z edZ eedZ ed Zd ZeeZeeZd ZRS( NcCsv||_||_t||_|o|i||n7t|_t|_ t|_ t|_ t|_ t|_ dS(N(senvsselfs parent_typesunicodes parent_idsfilenames_fetchsdbsNones descriptionssizestimesauthorsipnr(sselfsenvs parent_types parent_idsfilenamesdb((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys__init__Os       cCs| o|ii}n|i}|id|it|i|f|i }|i | o#||_ t d|idn|d|_ |d|_|dot|dpd|_|dot|dpd|_|d|_|d |_dS( NswSELECT filename,description,size,time,author,ipnr FROM attachment WHERE type=%s AND id=%s AND filename=%s ORDER BY timesAttachment %s does not exist.sInvalid Attachmentiiiiii(sdbsselfsenvs get_db_cnxscursorsexecutes parent_typesunicodes parent_idsfilenamesfetchonesrowscloses TracErrorstitles descriptionsintssizestimesauthorsipnr(sselfsfilenamesdbscursorsrow((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys_fetch]s"         %% cCsmtii|iid|it|i}|io"tii|t|i}ntii |SdS(Ns attachments( sosspathsjoinsselfsenvs parent_types unicode_quotes parent_idsfilenamesnormpath(sselfspath((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys _get_pathrs  "cOs)|ii|i|i|i||SdS(N( sreqshrefs attachmentsselfs parent_types parent_idsfilenamesargssdict(sselfsreqsargssdict((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pyshrefzscCs|i|i|iSdS(N(sreqshrefsselfs parent_types parent_id(sselfsreq((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys parent_href~scCs2d|idjodpd|i|ifSdS(Ns%s%s: %sstickets#s(sselfs parent_types parent_idsfilename(sself((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys _get_titlescCsG|ip td| o|ii}t}nt}|i }|i d|i |i |ift ii|iokyt i|iWqtj oD|iiid|idt|o|intdqXn|iiid|i|o|inx't|iiD]}|i|q,WdS(Ns%Cannot delete non-existent attachments>DELETE FROM attachment WHERE type=%s AND id=%s AND filename=%ss#Failed to delete attachment file %ssexc_infosCould not delete attachmentsAttachment removed: %s(sselfsfilenamesAssertionErrorsdbsenvs get_db_cnxsTrues handle_tasFalsescursorsexecutes parent_types parent_idsosspathsisfilesunlinksOSErrorslogserrorsrollbacks TracErrorsinfostitlescommitsAttachmentModuleschange_listenersslistenersattachment_deleted(sselfsdbslistenerscursors handle_ta((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysdeletes.   c Cs| o|ii}t} nt} |o t|pd|_t|p t i |_ t i i t i i|ii d} t i i| |i g}|| jptt i|i t i ot i|i nt|}tt i i |i |\} }zt i i| id}t|}|i} | id|i|i||i|i |i |i!|i"ft#i$||||_|ii&i'd|i(|i!| o|i)nx't*|ii+D]} | i-|qWWd|i.XdS(Nis attachmentssasciis7INSERT INTO attachment VALUES (%s,%s,%s,%s,%s,%s,%s,%s)sNew attachment: %s by %s(/sdbsselfsenvs get_db_cnxsTrues handle_tasFalsessizesintststimesosspathsjoinsnormpathsattachments_dirs commonprefixsAssertionErrorsaccesssF_OKsmakedirss unicode_quotesfilenamescreate_unique_files targetfilesbasenamesencodesunicode_unquotescursorsexecutes parent_types parent_ids descriptionsauthorsipnrsshutils copyfileobjsfileobjslogsinfostitlescommitsAttachmentModuleschange_listenersslistenersattachment_addedsclose(sselfsfilenamesfileobjssizestsdbsbasenames commonprefixs targetfileslisteners handle_taspathscursorsattachments_dir((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysinserts@      4  c cs| o|i}n|i} | id|t|fx| D]\}}} } }}t|||} || _|| _ | o t| pd| _ | o t| pd| _ || _ || _ | VqGWdS(NsgSELECT filename,description,size,time,author,ipnr FROM attachment WHERE type=%s AND id=%s ORDER BY timei(sdbsenvs get_db_cnxscursorsexecutes parent_typesunicodes parent_idsfilenames descriptionssizestimesauthorsipnrs Attachments attachmentsint( sclssenvs parent_types parent_idsdbsipnrsauthors descriptionsfilenamescursors attachmentstimessize((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysselects      cCst}xHt|i||||D](}t i i |i }|i |q%W|oDyt i|Wqtj o |iid|dtqXndS(sDelete all attachments of a given resource. As this is usually done while deleting the parent resource, the `db` argument is ''not'' optional here. s$Can't delete attachment directory %ssexc_infoN(sNonesattachment_dirslistsclssselectsenvs parent_types parent_idsdbs attachmentsosspathsdirnamesdeletesrmdirsOSErrorslogserrorsTrue(sclssenvs parent_types parent_idsdbsattachment_dirs attachment((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys delete_alls cCs`|iiid|iyt|id}Wn&tj otd|i nX|SdS(NsTrying to open attachment at %ssrbsAttachment %s not found( sselfsenvslogsdebugspathsopensfdsIOErrors TracErrorsfilename(sselfsfd((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysopens (s__name__s __module__sNones__init__s_fetchs _get_pathspropertyspathshrefs parent_hrefs _get_titlestitlesdeletesinsertsselects delete_alls classmethodsopen(((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys AttachmentMs        1    cCsJgi}ti||||D]}|t ||||q ~SdS(N( sappends_[1]s Attachmentsselectsenvs parent_types parent_idsdbs attachmentsattachment_to_hdfsreq(senvsreqsdbs parent_types parent_ids_[1]s attachment((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysattachments_to_hdfscCs| o|i}nhd|i<dt|i||<d|i<d|i<dt |i <dt |i <dt |i <d|i|<}|SdS( Nsfilenames descriptionsauthorsipnrssizestimesageshref(sdbsenvs get_db_cnxs attachmentsfilenameswiki_to_oneliners descriptionsauthorsipnrs pretty_sizessizesformat_datetimestimespretty_timedeltashrefsreqshdf(senvsreqsdbs attachmentshdf((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysattachment_to_hdf s sAttachmentModulecBstZeeeeeeeZ ee Z dZ e ddddZeddddZd Zd Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#RS(Nis attachmentsmax_sizeis:Maximum allowed file size for ticket and wiki attachments.srender_unsafe_contentsfalsesWhether non-binary attachments should be rendered in the browser, or only made downloadable. Pretty much any text file may be interpreted as HTML by the browser, which allows a malicious user to attach a file containing cross-site scripting attacks. For public sites where anonymous users can create attachments, it is recommended to leave this option disabled (which is the default).cCs7|iio&titii|iidndS(s!Create the attachments directory.s attachmentsN(sselfsenvspathsossmkdirsjoin(sself((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysenvironment_created4s cCstSdS(N(sFalse(sselfsdb((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysenvironment_needs_upgrade9scCsdS(N((sselfsdb((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysupgrade_environment<scCs|iidSdS(Nstype(sreqsargssget(sselfsreq((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysget_active_navigation_itemAscCsgSdS(N((sselfsreq((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysget_navigation_itemsDscCs`tid|i}|o@|id|id<|ididd|id %s AND time < %s AND type = %sscreatedN(sselfsenvs get_db_cnxsdbscursorsexecutesstartsstopstypesidsfilenamestimes descriptionsauthor( sselfsstartsstopstypes descriptionsauthorsdbsfilenamescursorstimesid((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys get_historys  ccsx|i|||D]\} }} } }} } t i t ii| d|| }|djo2t| pd|i||dt} |i}n8t| |i|dt} |td| 7}|i}d|i|| | ||| | fVqWdS( sReturn an iterable of events suitable for ITimelineEventProvider. `display` is a callback for formatting the attachment's parent s attached to srsss--sabsurlssshortens by %ss attachmentN(sselfs get_historysstartsstopstypeschangesidsfilenamestimesdescrsauthorshtmlsEMsosspathsbasenamesdisplaystitlesformats wiki_to_htmlsenvsreqsdbsTruesabs_hrefshrefswiki_to_onelinersMarkups attachment(sselfsreqsdbstypesformatsstartsstopsdisplayshrefsidsdescrsauthorsfilenameschangestitlestime((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pysget_timeline_eventss)    c Cs.hdd<dd<dd<} |ii| |i|iido|i|i |n|id}t |d  p|i ot d nt |id o ti|iid } n |ii} | d jot dn|i}|d jo | |jot d|dntidt|i d}|iddidd}tii|}| ot d n|iidd|_t|d|_|i |_!xe|i"D]Z}xQ|i$||D]=\}} |ot'd|| fqt'd| qWqW|iidoyt(|i)|i|i*|}|io|i,o|i|i,j o<hdd<dd<dd<} |ii| |in|i-Wnt j onXt.|_ n|i/||i| |i|i0|dS(Nstickets TICKET_APPENDswikis WIKI_MODIFYs templatessTEMPLATES_MODIFYscancels attachmentsfilenamesNo file uploadedsfilenoiisCan't upload empty files!Maximum attachment size: %d bytess Upload failedsNFCsutf-8s\s/s:s descriptionssauthors"Attachment field %s is invalid: %ssInvalid attachment: %ssreplaces TICKET_ADMINs WIKI_DELETEsTEMPLATES_DELETE(1sperm_mapsreqspermsassert_permissions attachments parent_typesargsshas_keysredirects parent_hrefsuploadshasattrsfilenames TracErrorsfilesossfstatsfilenossizeslensselfsmax_sizes unicodedatas normalizesunicodesreplacespathsbasenamesgets descriptionsget_reporter_idsauthors remote_addrsipnrs manipulatorss manipulatorsvalidate_attachmentsfieldsmessagesInvalidAttachments Attachmentsenvs parent_idsold_attachmentsauthnamesdeletesNonesinsertshref( sselfsreqs attachments manipulatorsuploadsfilenamesfieldsold_attachmentsmax_sizesperm_mapsmessagessize((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys_do_savesZ!           (! cCshdd<dd<dd<}|ii||i|iido|i|i |n|i |i|i |dS(Nstickets TICKET_ADMINswikis WIKI_DELETEs templatessTEMPLATES_DELETEscancel( sperm_mapsreqspermsassert_permissions attachments parent_typesargsshas_keysredirectshrefsdeletes parent_href(sselfsreqs attachmentsperm_map((s<build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/attachment.pys _do_deletes ! cCsrhdd<dd<dd<}|ii||id|i|id=%s AND time<=%ss&%s wiki template edited by %ssdiffshrefsactionsversions--sabsurlssshortenis%s (%s)cCstdtid|SdS(Nsticket s#(sMarkupshtmlsEMsid(sid((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pysdisplayscCs ti|S(N(shtmlsEMsid(sid((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pyss(%sfilterss WikiSystemsselfsenvstemplatesreqsargssgetsformatsabs_hrefshrefs get_db_cnxsdbscursorsexecutesstartsstopstsnamescommentsauthorsversionsMarkupsformat_page_namestitleshtmlsAs templatess diff_links wiki_to_htmlsTrueswiki_to_onelinersdisplaysAttachmentModulesattsget_timeline_eventssevent(sselfsreqsstartsstopsfiltersscommentshrefseventstitlesversionstemplatesformatsdbsnamesauthorscursors diff_linksattstsdisplay((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pysget_timeline_eventss8     *   #  cCsZt|ii|i}}|o|d|7}n||i d<||i d<|SdS(Ns (%s)stemplates.page_namestitle( s WikiSystemsselfsenvsformat_page_namespagesnamestitlesactionsreqshdf(sselfsreqspagesactionsnamestitle((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys _set_title s   cCsQ|io|iidn|iid|iido |i|ii |i nt |ii ddpt }t |ii ddp|}|o|o ||jo2x?t||D]}|i|d|qWn|i|||i|i o|i|ii n|i|ii |i dS(NsTEMPLATES_ADMINsTEMPLATES_DELETEscancelsversionis old_versioni(spagesreadonlysreqspermsassert_permissionsargsshas_keysredirectshrefs templatessnamesintsgetsNonesversions old_versionsrangesvsdeletesdbscommitsexists(sselfsreqsdbspages old_versionsversionsv((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys _do_delete(s   ""  cCsG|io|iidn0|i o|iidn|iid|iid|_|ii dot |ii d|_nxe|i D]Z}xQ|i||D]=\}}|otd||fqtd|qWqW|it|d|iid |i|i|ii|idS( NsTEMPLATES_ADMINsTEMPLATES_CREATEsTEMPLATES_MODIFYstextsreadonlys)The Template page field %s is invalid: %ssInvalid Template page: %ssauthorscomment(spagesreadonlysreqspermsassert_permissionsexistssargssgetstextshas_permissionsintshas_keysselfspage_manipulatorss manipulatorsvalidate_wiki_pagesfieldsmessagesInvalidTemplatePagessavesget_reporter_ids remote_addrsredirectshrefs templatessname(sselfsreqsdbspages manipulatorsfieldsmessage((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys_do_saveBs$    ! c CsQ|io|iidn|iidt}|iidot |ii dd}nt |ii dpdp|}|i ||dhdd<|id <|tj od}xP|iD]B\} } }}} | |jo |d 7}|d joPqqqWhd|<d|<d |d j<|id cCs.|id}||7}t||idN(sselfs_add_jssreqsfile(sselfsreqsfile((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys _add_js_incLscCsdSdS(NsF((sselfsreq((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys_make_jsQsccs%|iidoddfVndS(NsTEMPLATES_VIEWs templatessWiki Templates(sreqspermshas_permission(sselfsreq((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pysget_search_filtersXsc csd|j odSn|ii}t|dddg|\} }|i } | i d| |xR| D]J\}} }}|ii|d|t|f| |t||fVqmWdS(Ns templatessw1.names w1.authorsw1.textsSELECT w1.name,w1.time,w1.author,w1.text FROM templates w1,(SELECT name,max(version) AS ver FROM templates GROUP BY name) w2 WHERE w1.version = w2.ver AND w1.name = w2.name AND s%s: %s(sfilterssselfsenvs get_db_cnxsdbs search_to_sqlstermss sql_querysargsscursorsexecutesnamesdatesauthorstextsreqshrefs templatess shorten_linesshorten_result( sselfsreqstermssfilterssargssnamesauthorstextsdbscursorsdates sql_query((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pysget_search_results\s!  (&s__name__s __module__s implementssINavigationContributorsIPermissionRequestorsIRequestHandlersITimelineEventProviders ISearchSourcesITemplateProviders ICtxtnavAddersExtensionPointsIWikiPageManipulatorspage_manipulatorssget_htdocs_dirssget_templates_dirssget_active_navigation_itemsget_navigation_itemssmatch_ctxtnav_addsget_ctxtnav_addssget_permission_actionss match_requestsprocess_requestsget_timeline_filterssget_timeline_eventss _set_titles _do_deletes_do_saves_render_confirms _render_diffsFalses_render_editors_render_historys _render_views_add_jss _add_js_incs_make_jssget_search_filterssget_search_results(((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pysWikiTemplatesModule3s8          t  $     U (  5    (;sossresStringIOstrac.attachmentsattachments_to_hdfs trac.cores trac.permsIPermissionRequestors trac.Searchs ISearchSources search_to_sqlsshorten_results trac.TimelinesITimelineEventProviders trac.utilsget_reporter_idstrac.util.datefmtsformat_datetimespretty_timedeltastrac.util.htmlshtmlsMarkupstrac.util.texts shorten_lines to_unicodestrac.versioncontrol.diffsget_diff_optionsshdf_diffstrac.web.chromesadd_linksadd_stylesheets add_scriptsINavigationContributorsITemplateProviderstrac.webs HTTPNotFoundsIRequestHandlers trac.wiki.apisIWikiPageManipulators WikiSystemstrac.wiki.formatters wiki_to_htmlswiki_to_onelinerstrac.mimeview.apisMimeviewsIContentConvertersWikiTemplates.models WikiTemplatesWikiTemplates.errorssTemplatesErrorsWikiTemplates.attachments AttachmentsAttachmentModulesctxtnavadd.apis ICtxtnavAdders TracErrorsInvalidTemplatePages ComponentsWikiTemplatesModule(&sITimelineEventProviders to_unicodesIRequestHandlers search_to_sqlsAttachmentModules wiki_to_htmls WikiTemplateswiki_to_onelinersITemplateProvidersadd_links Attachmentsattachments_to_hdfs add_scriptsadd_stylesheetsreshtmlspretty_timedeltasINavigationContributorsIWikiPageManipulators shorten_linesget_diff_optionssIPermissionRequestorsMarkupsshorten_resultsIContentConvertersTemplatesErrors ICtxtnavAdders WikiSystemshdf_diffsMimeviews HTTPNotFoundsStringIOsformat_datetimesInvalidTemplatePages ISearchSourcesWikiTemplatesModulesget_reporter_idsos((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/web_ui.pys?s0          PK|65##WikiTemplates/model.py# -*- coding: iso-8859-1 -*- # # Copyright (C) 2003-2005 Edgewall Software # Copyright (C) 2003-2005 Jonas Borgstrm # Copyright (C) 2005 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://projects.edgewall.com/trac/. # # Author: Jonas Borgstrm # Christopher Lenz import time from trac.core import * from trac.wiki.api import WikiSystem from trac.util.text import to_unicode class WikiTemplate(object): """Represents a wiki page (new or existing).""" def __init__(self, env, name=None, version=None, db=None, table=None): self.env = env self.name = name self.table = table if name: self._fetch(name, version, db, table) else: self.version = 0 self.text = '' self.readonly = 0 self.old_text = self.text self.old_readonly = self.readonly self.env.log.debug("WikiTemplate: '%s'", to_unicode(self.__dict__.items())) def _fetch(self, name, version=None, db=None, table=None): if not db: db = self.env.get_db_cnx() cursor = db.cursor() QUERY = "SELECT version,text,readonly FROM " if table: QUERY +="%s " % table else: QUERY +="templates " if version: cursor.execute(QUERY + "WHERE name=%s AND version=%s", (name, int(version))) else: cursor.execute(QUERY + "WHERE name=%s ORDER BY version " "DESC LIMIT 1", (name,)) row = cursor.fetchone() if row: version,text,readonly = row self.version = int(version) self.text = text self.readonly = readonly and int(readonly) or 0 else: self.version = 0 self.text = '' self.readonly = 0 self.env.log.debug("WikiTemplate Fetched: '%s'", to_unicode(self.__dict__.items())) exists = property(fget=lambda self: self.version > 0) def delete(self, version=None, db=None): assert self.exists, 'Cannot delete non-existent page' if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False page_deleted = False cursor = db.cursor() if version is None: # Delete a wiki page completely cursor.execute("DELETE FROM templates WHERE name=%s", (self.name,)) self.env.log.info('Deleted page %s' % self.name) else: # Delete only a specific page version cursor.execute("DELETE FROM templates WHERE name=%s and version=%s", (self.name, version)) self.env.log.info('Deleted version %d of page %s' % (version, self.name)) if version is None or version == self.version: self._fetch(self.name, None, db) if not self.exists: # from WikiTemplates.attachment import TemplatesAttachment from trac.attachment import Attachment # Delete orphaned attachments # for attachment in TemplatesAttachment.select(self.env, for attachment in Attachment.select(self.env, 'templates', self.name, db): attachment.delete(db) # Let change listeners know about the deletion for listener in WikiSystem(self.env).change_listeners: listener.wiki_page_deleted(self) if handle_ta: db.commit() def save(self, author, comment, remote_addr, t=None, db=None): if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False if t is None: t = time.time() if self.text != self.old_text: cursor = db.cursor() cursor.execute("INSERT INTO templates (name,version,time,author,ipnr," "text,comment,readonly) VALUES (%s,%s,%s,%s,%s,%s," "%s,%s)", (self.name, self.version + 1, t, author, remote_addr, self.text, comment, self.readonly)) self.version += 1 elif self.readonly != self.old_readonly: cursor = db.cursor() cursor.execute("UPDATE templates SET readonly=%s WHERE name=%s", (self.readonly, self.name)) else: raise TracError('Page not modified') if handle_ta: db.commit() for listener in WikiSystem(self.env).change_listeners: if self.version == 1: listener.wiki_page_added(self) else: listener.wiki_page_changed(self, self.version, t, comment, author, remote_addr) self.old_readonly = self.readonly self.old_text = self.text def get_history(self, db=None): if not db: db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT version,time,author,comment,ipnr FROM templates " "WHERE name=%s AND version<=%s " "ORDER BY version DESC", (self.name, self.version)) for version,time,author,comment,ipnr in cursor: yield version,time,author,comment,ipnr PKKt4  WikiTemplates/errors.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: errors.py 38 2006-04-20 18:34:22Z s0undt3ch $ # ============================================================================= # $URL: http://wikitemplates.ufsoft.org/svn/trunk/WikiTemplates/errors.py $ # $LastChangedDate: 2006-04-20 20:34:22 +0200 (Do, 20 Apr 2006) $ # $Rev: 38 $ # $LastChangedBy: s0undt3ch $ # ============================================================================= ############################################################################### # # # Copyright 2006 by Pedro Algarvio # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 2 of the License, or (at your option) # # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # ############################################################################### # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= from trac.util import escape def TemplatesError(message): """ Class to output a pretty error. """ html = """
Wiki Templates Error:
%(message)s
""" % {'message': escape(message)} return html PK68Ϛ+WikiTemplates/errors.pyc; .GDc@sdklZdZdS((sescapecCs!dhdt|<}|SdS(s) Class to output a pretty error. sc
Wiki Templates Error:
%(message)s
smessageN(sescapesmessageshtml(smessageshtml((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/errors.pysTemplatesError&sN(s trac.utilsescapesTemplatesError(sTemplatesErrorsescape((s8build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/errors.pys?$s PK&4  WikiTemplates/db_schema.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: db_schema.py 41 2006-04-25 08:48:35Z s0undt3ch $ # ============================================================================= # $URL: http://wikitemplates.ufsoft.org/svn/trunk/WikiTemplates/db_schema.py $ # $LastChangedDate: 2006-04-25 10:48:35 +0200 (Di, 25 Apr 2006) $ # $Rev: 41 $ # $LastChangedBy: s0undt3ch $ # ============================================================================= ############################################################################### # # # Copyright 2006 by Pedro Algarvio # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 2 of the License, or (at your option) # # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # ############################################################################### # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= from trac.core import * from trac.db_default import Table, Column, Index # Version of WikiTemplates Schema version = 1 # A copy of trac's wiki dtabase schema since templates will be a subwiki # with a templates/ handler. schema = [ Table('templates', key=('name', 'version'))[ Column('name'), Column('version', type='int'), Column('time', type='int'), Column('author'), Column('ipnr'), Column('text'), Column('comment'), Column('readonly', type='int'), Index(['time'])] ] PK68 :C  WikiTemplates/__init__.pyc; Gc@s&dkZdkZdkZdkTdS(N(s*(sweb_uismodels attachmentsmacros(smodelsweb_uis attachment((s:build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/__init__.pys?$sPK68@yyWikiTemplates/db_schema.pyc; cMDc @sdkTdklZlZlZdZeddddfededdded dded ed ed ed eddded gf gZdS((s*(sTablesColumnsIndexis templatesskeysnamesversionstypesintstimesauthorsipnrstextscommentsreadonlyN(s trac.corestrac.db_defaultsTablesColumnsIndexsversionsschema(sColumnsTablesschemasversionsIndex((s;build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/db_schema.pys?$sPK75jNdNdWikiTemplates/web_ui.py# -*- coding: iso-8859-1 -*- # # Copyright (C) 2003-2006 Edgewall Software # Copyright (C) 2003-2005 Jonas Borgström # Copyright (C) 2004-2005 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Jonas Borgström # Christopher Lenz import os import re import StringIO from trac.attachment import attachments_to_hdf from trac.core import * from trac.perm import IPermissionRequestor from trac.Search import ISearchSource, search_to_sql, shorten_result from trac.Timeline import ITimelineEventProvider from trac.util import get_reporter_id from trac.util.datefmt import format_datetime, pretty_timedelta from trac.util.html import html, Markup from trac.util.text import shorten_line, to_unicode from trac.versioncontrol.diff import get_diff_options, hdf_diff from trac.web.chrome import add_link, add_stylesheet, add_script from trac.web.chrome import INavigationContributor, ITemplateProvider from trac.web import HTTPNotFound, IRequestHandler from trac.wiki.api import IWikiPageManipulator, WikiSystem from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner from trac.mimeview.api import Mimeview, IContentConverter from WikiTemplates.model import WikiTemplate from WikiTemplates.errors import TemplatesError from WikiTemplates.attachment import Attachment, AttachmentModule from ctxtnavadd.api import ICtxtnavAdder class InvalidTemplatePage(TracError): """Exception raised when a Wiki page fails validation.""" class WikiTemplatesModule(Component): implements(INavigationContributor, IPermissionRequestor, IRequestHandler, ITimelineEventProvider, ISearchSource, ITemplateProvider, ICtxtnavAdder) page_manipulators = ExtensionPoint(IWikiPageManipulator) # ITemplateProvider methods def get_htdocs_dirs(self): from pkg_resources import resource_filename resource_dir = resource_filename(__name__, 'htdocs') return [('templates', resource_dir)] def get_templates_dirs(self): from pkg_resources import resource_filename resource_dir = resource_filename(__name__, 'templates') return [resource_dir] # INavigationContributor methods def get_active_navigation_item(self, req): return 'templates' def get_navigation_items(self, req): evil_js = '/'.join(['templates','js','wikitemplates.js']) add_script(req, evil_js) if not req.perm.has_permission('TEMPLATES_VIEW') or not \ req.perm.has_permission('TEMPLATES_ADMIN') or not \ self.env.is_component_enabled( 'wikitemplates.macros.templates.templatesmacro'): return yield ('mainnav', 'templates', html.A('Wiki Templates', href=req.href.templates(), accesskey=9, id='templatesbtn')) # ICtxtnavAdder methods def match_ctxtnav_add(self, req): if not req.perm.has_permission('TEMPLATES_VIEW') or not \ self.env.is_component_enabled( 'wikitemplates.macros.templates.templatesmacro'): return False self._add_js(req,self._make_js(req)) return len(req.path_info) <= 1 or req.path_info == '/' or \ req.path_info.startswith('/wiki') or \ req.path_info.startswith('/templates') def get_ctxtnav_adds(self, req): yield (req.href.templates(), 'Wiki Templates Index') # IPermissionRequestor methods def get_permission_actions(self): actions = [ 'TEMPLATES_CREATE', 'TEMPLATES_DELETE', 'TEMPLATES_MODIFY', 'TEMPLATES_VIEW' ] return actions + [('TEMPLATES_ADMIN', actions)] # IRequestHandler methods def match_request(self, req): match = re.match(r'^/templates(?:/(.*))?', req.path_info) if match: if match.group(1): req.args['page'] = match.group(1) self.env.log.debug("Page Match: '%s'", match.group(1)) self.env.log.debug("Page Match req.args: '%s'", to_unicode(req.args['page'])) else: req.args['page'] = 'TemplatesIndex' self.env.log.debug("Index Match: '%s'", to_unicode(req.args['page'])) return True def process_request(self, req): if req.method == 'POST': action = req.args.get('action', 'create') if action == 'create': redir = req.args.get('new_tpl_name') req.args['action'] = 'edit' req.redirect(self.env.href.templates(redir)) action = req.args.get('action', 'view') pagename = req.args.get('page', 'TemplatesIndex') version = req.args.get('version') db = self.env.get_db_cnx() cursor = db.cursor() req.hdf['templates_base_url'] = self.env.href.templates() # Query our DB for the template previews if pagename == 'TemplatesIndex': # Include all latest versions of every template # to show on the templates index QUERY = """SELECT name, text from templates WHERE version=(SELECT max(t2.version) FROM templates t2 WHERE templates.name=t2.name) ORDER BY name ASC""" cursor.execute(QUERY) req.hdf['templates.showform'] = 1 else: # Include only the latest verion of the template # being called. QUERY = """SELECT name, text FROM templates WHERE name=%s ORDER BY version DESC LIMIT 1""" cursor.execute(QUERY, (pagename,)) templates = cursor.fetchall() previews = [] # REGEX for our variables defenitions {{n}}, n being a digit args_re = re.compile(r'\{\{\d+\}\}') try: for template in templates: name = template[0] contents = template[1] # Dont include the TemplatesIndex if name != 'TemplatesIndex': try: # Substitute the var defenitions found on template # by bogus var to get a "real" preview for i in range(1, len(args_re.findall(contents)) + 1): contents = contents.replace('{{%d}}' % i, 'argument_%d' % i) self.env.log.debug('Replace Results: "%s"' % contents) except: self.env.log.debug('No variables replacing needed.') # Append the dict to the previews list previews.append({'name': name, 'contents': wiki_to_html(contents, self.env, req)}) # Assign our previews list to trac HDF req.hdf['previews'] = previews self.env.log.debug('TemplatesIndex List: "%s"' % previews) except Exception, e: # Aparently no entry was found on db, maybe it's a new template, # so, we don't include any preview, of course # self.env.log.debug("No previous record of '%s' found on DB.") self.env.log.debug(e) self.env.log.debug('Template Name: %s', pagename) # Continue normal wiki behaviour if pagename.endswith('/'): req.redirect(req.href.templates(pagename.strip('/'))) db = self.env.get_db_cnx() page = WikiTemplate(self.env, pagename, version, db) add_stylesheet(req, 'common/css/wiki.css') add_stylesheet(req, 'templates/css/wikitemplates.css') if req.method == 'POST': if action == 'edit': latest_version = WikiTemplate( self.env, pagename, None, db).version if req.args.has_key('cancel'): req.redirect(req.href.templates(page.name)) elif int(version) != latest_version: action = 'collision' self._render_editor(req, db, page) elif req.args.has_key('preview'): action = 'preview' self._render_editor(req, db, page, preview=True) else: self._do_save(req, db, page) elif action == 'delete': self._do_delete(req, db, page) elif action == 'diff': get_diff_options(req) req.redirect(req.href.templates( page.name, version=page.version, old_version=req.args.get('old_version'), action='diff')) elif action == 'delete': self._render_confirm(req, db, page) elif action == 'edit': self._render_editor(req, db, page) elif action == 'diff': self._render_diff(req, db, page) elif action == 'history': self._render_history(req, db, page) else: format = req.args.get('format') if format: Mimeview(self.env).send_converted(req, 'text/x-trac-wiki', page.text, format, page.name) self._render_view(req, db, page) req.hdf['templates.action'] = action req.hdf['templates.current_href'] = req.href.templates(page.name) return 'WikiTemplates.cs', None # ITimelineEventProvider methods def get_timeline_filters(self, req): if req.perm.has_permission('TEMPLATES_VIEW'): yield ('templates', 'Wiki Templates Changes') def get_timeline_events(self, req, start, stop, filters): if 'templates' in filters: template = WikiSystem(self.env) format = req.args.get('format') href = format == 'rss' and req.abs_href or req.href db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT time,name,comment,author,version " "FROM templates WHERE time>=%s AND time<=%s", (start, stop)) for t,name,comment,author,version in cursor: title = Markup('%s wiki template edited by %s', template.format_page_name(name), author) diff_link = html.A('diff', href=href.templates( name, action='diff', version=version)) if format == 'rss': comment = wiki_to_html(comment or '--', self.env, req, db, absurls=True) else: comment = wiki_to_oneliner(comment, self.env, db, shorten=True) if version > 1: comment = Markup('%s (%s)', comment, diff_link) yield 'templates', href.templates(name), title, t, author, comment # Attachments def display(id): return Markup('ticket ', html.EM('#', id)) att = AttachmentModule(self.env) for event in att.get_timeline_events(req, db, 'templates', format, start, stop, lambda id: html.EM(id)): yield event # Internal methods def _set_title(self, req, page, action): title = name = WikiSystem(self.env).format_page_name(page.name) if action: title += ' (%s)' % action req.hdf['templates.page_name'] = name req.hdf['title'] = title return title def _do_delete(self, req, db, page): if page.readonly: req.perm.assert_permission('TEMPLATES_ADMIN') else: req.perm.assert_permission('TEMPLATES_DELETE') if req.args.has_key('cancel'): req.redirect(req.href.templates(page.name)) version = int(req.args.get('version', 0)) or None old_version = int(req.args.get('old_version', 0)) or version if version and old_version and version > old_version: # delete from `old_version` exclusive to `version` inclusive: for v in range(old_version, version): page.delete(v + 1, db) else: # only delete that `version`, or the whole page if `None` page.delete(version, db) db.commit() if not page.exists: req.redirect(req.href.templates()) else: req.redirect(req.href.templates(page.name)) def _do_save(self, req, db, page): if page.readonly: req.perm.assert_permission('TEMPLATES_ADMIN') elif not page.exists: req.perm.assert_permission('TEMPLATES_CREATE') else: req.perm.assert_permission('TEMPLATES_MODIFY') page.text = req.args.get('text') if req.perm.has_permission('TEMPLATES_ADMIN'): # Modify the read-only flag if it has been changed and the user is # TEMPLATES_ADMIN page.readonly = int(req.args.has_key('readonly')) # Give the manipulators a pass at post-processing the page for manipulator in self.page_manipulators: for field, message in manipulator.validate_wiki_page(req, page): if field: raise InvalidTemplatePage("The Template page field %s is invalid: %s" % (field, message)) else: raise InvalidTemplatePage("Invalid Template page: %s" % message) page.save(get_reporter_id(req, 'author'), req.args.get('comment'), req.remote_addr) req.redirect(req.href.templates(page.name)) def _render_confirm(self, req, db, page): if page.readonly: req.perm.assert_permission('TEMPLATES_ADMIN') else: req.perm.assert_permission('TEMPLATES_DELETE') version = None if req.args.has_key('delete_version'): version = int(req.args.get('version', 0)) old_version = int(req.args.get('old_version') or 0) or version self._set_title(req, page, 'delete') req.hdf['templates'] = {'mode': 'delete'} if version is not None: num_versions = 0 for v,t,author,comment,ipnr in page.get_history(): if v >= old_version: num_versions += 1; if num_versions > 1: break req.hdf['templates'] = { 'version': version, 'old_version': old_version, 'only_version': num_versions == 1 } def _render_diff(self, req, db, page): req.perm.assert_permission('TEMPLATES_VIEW') if not page.exists: raise TracError("Version %s of template %s does not exist" % (req.args.get('version'), page.name)) add_stylesheet(req, 'common/css/diff.css') self._set_title(req, page, 'diff') # Ask web spiders to not index old versions req.hdf['html.norobots'] = 1 old_version = req.args.get('old_version') if old_version: old_version = int(old_version) if old_version == page.version: old_version = None elif old_version > page.version: # FIXME: what about reverse diffs? old_version, page = page.version, \ WikiTemplate(self.env, page.name, old_version) latest_page = WikiTemplate(self.env, page.name) new_version = int(page.version) info = { 'version': new_version, 'latest_version': latest_page.version, 'history_href': req.href.templates(page.name, action='history') } num_changes = 0 old_page = None prev_version = next_version = None for version,t,author,comment,ipnr in latest_page.get_history(): if version == new_version: if t: info['time'] = format_datetime(t) info['time_delta'] = pretty_timedelta(t) info['author'] = author or 'anonymous' info['comment'] = wiki_to_html(comment or '--', self.env, req, db) info['ipnr'] = ipnr or '' else: if version < new_version: num_changes += 1 if not prev_version: prev_version = version if (old_version and version == old_version) or \ not old_version: old_page = WikiTemplate(self.env, page.name, version) info['num_changes'] = num_changes info['old_version'] = version break else: next_version = version req.hdf['templates'] = info # -- prev/next links if prev_version: add_link(req, 'prev', req.href.templates(page.name, action='diff', version=prev_version), 'Version %d' % prev_version) if next_version: add_link(req, 'next', req.href.templates(page.name, action='diff', version=next_version), 'Version %d' % next_version) # -- text diffs diff_style, diff_options = get_diff_options(req) oldtext = old_page and old_page.text.splitlines() or [] newtext = page.text.splitlines() context = 3 for option in diff_options: if option.startswith('-U'): context = int(option[2:]) break if context < 0: context = None changes = hdf_diff(oldtext, newtext, context=context, ignore_blank_lines='-B' in diff_options, ignore_case='-i' in diff_options, ignore_space_changes='-b' in diff_options) req.hdf['templates.diff'] = changes def _render_editor(self, req, db, page, preview=False): req.perm.assert_permission('TEMPLATES_MODIFY') if req.args.has_key('text'): page.text = req.args.get('text') if preview: page.readonly = req.args.has_key('readonly') author = get_reporter_id(req, 'author') comment = req.args.get('comment', '') editrows = req.args.get('editrows') if editrows: pref = req.session.get('templates_editrows', '20') if editrows != pref: req.session['templates_editrows'] = editrows else: editrows = req.session.get('templates_editrows', '20') self._set_title(req, page, 'edit') info = { 'page_source': page.text, 'version': page.version, 'author': author, 'comment': comment, 'readonly': page.readonly, 'edit_rows': editrows, 'scroll_bar_pos': req.args.get('scroll_bar_pos', '') } if page.exists: info['history_href'] = req.href.templates(page.name, action='history') info['last_change_href'] = req.href.templates(page.name, action='diff', version=page.version) if preview: info['page_html'] = wiki_to_html(page.text, self.env, req, db) info['comment_html'] = wiki_to_oneliner(comment, self.env, db) info['readonly'] = int(req.args.has_key('readonly')) req.hdf['templates'] = info def _render_history(self, req, db, page): """Extract the complete history for a given page and stores it in the HDF. This information is used to present a changelog/history for a given page. """ req.perm.assert_permission('TEMPLATES_VIEW') if not page.exists: raise TracError, "Template %s does not exist" % page.name self._set_title(req, page, 'history') history = [] for version, t, author, comment, ipnr in page.get_history(): history.append({ 'url': req.href.templates(page.name, version=version), 'diff_url': req.href.templates(page.name, version=version, action='diff'), 'version': version, 'time': format_datetime(t), 'time_delta': pretty_timedelta(t), 'author': author, 'comment': wiki_to_oneliner(comment or '', self.env, db), 'ipaddr': ipnr }) req.hdf['templates.history'] = history def _render_view(self, req, db, page): req.perm.assert_permission('TEMPLATES_VIEW') page_name = self._set_title(req, page, '') if page.name == 'TemplatesIndex': req.hdf['title'] = 'Wiki Templates Index' version = req.args.get('version') if version: # Ask web spiders to not index old versions req.hdf['html.norobots'] = 1 # Add registered converters for conversion in Mimeview(self.env).get_supported_conversions( 'text/x-trac-wiki'): conversion_href = req.href.templates(page.name, version=version, format=conversion[0]) add_link(req, 'alternate', conversion_href, conversion[1], conversion[3]) latest_page = WikiTemplate(self.env, page.name) req.hdf['templates'] = {'exists': page.exists, 'version': page.version, 'latest_version': latest_page.version, 'readonly': page.readonly} if page.exists: req.hdf['templates'] = { 'page_html': wiki_to_html(page.text, self.env, req), 'history_href': req.href.templates(page.name, action='history'), 'last_change_href': req.href.templates(page.name, action='diff', version=page.version) } if version: req.hdf['templates'] = { 'comment_html': wiki_to_oneliner(page.comment or '--', self.env, db), 'author': page.author, 'age': pretty_timedelta(page.time) } else: if not req.perm.has_permission('TEMPLATES_CREATE'): raise HTTPNotFound('Template %s not found', page.name) req.hdf['templates.page_html'] = html.P( 'Describe "%s" template here' % page_name) # Show attachments req.hdf['templates.attachments'] = attachments_to_hdf(self.env, req, db, 'templates', page.name) if req.perm.has_permission('TEMPLATES_MODIFY'): attach_href = req.href.attachment('templates', page.name) req.hdf['templates.attach_href'] = attach_href # TracCtxtnavAdd borrowed Internal Methods def _add_js(self, req, data): """Add javascript to a page via hdf['project.footer']""" footer = req.hdf['project.footer'] footer += data req.hdf['project.footer'] = Markup(footer) def _add_js_inc(self, req, file): """Add a javascript include via hdf['project.footer']""" self._add_js( req, """""" % file) def _make_js(self, req): return """""" # ISearchSource methods def get_search_filters(self, req): if req.perm.has_permission('TEMPLATES_VIEW'): yield ('templates', 'Wiki Templates') def get_search_results(self, req, terms, filters): if not 'templates' in filters: return db = self.env.get_db_cnx() sql_query, args = search_to_sql(db, ['w1.name', 'w1.author', 'w1.text'], terms) cursor = db.cursor() cursor.execute("SELECT w1.name,w1.time,w1.author,w1.text " "FROM templates w1," "(SELECT name,max(version) AS ver " "FROM templates GROUP BY name) w2 " "WHERE w1.version = w2.ver AND w1.name = w2.name " "AND " + sql_query, args) for name, date, author, text in cursor: yield (req.href.templates(name), '%s: %s' % (name, shorten_line(text)), date, author, shorten_result(text, terms)) PKKt4"WikiTemplates/upgrades/__init__.pyPK68]SSWikiTemplates/upgrades/db1.pyc; Gc@sbdkZdkZdkZdklZdklZdklZdk l Z l Z dZ dS(N(sresource_filename(s TracError(sDatabaseManager(sversionsschemac CsPdGHy|i}t|i\}}y&d}|i|dt ft }Wn#d}|i|t dfnXdGyQxEt D]=}x4|i|D]#} |ii| |i| qWqWdGHWnCtj o7}dGH|ii|dd |it|nXd Gydk}td d }xti|D]}|iid |ttii||}|i!} |i#d}|d t$|idd| ddf} |i|| qBW|iidddGHWnStj oG}dGH|iid|ii|dd |it|nXdGyIx=dddfD],} d}dd| f} |i|| qXWdGHWnStj oG}dGH|iid|ii|dd |it|nXdGy4d }|i||i'} |iid!t)| x| D]}yd"d#}|di+d$i,d t$|d t$|d%|d&|d'|d(i-d)d*|d+t$|d,f}|i||t/i0i1d-Wq*tj o7}dGH|ii|dd |it|q*Xq*WdGHWn*tj o}d.GH|iid/nXd0Gy@|iid1d2d3}|ii||i|dGHWnWtj oK}dGH|iid4d5|ii|dd |it|nXd6Gy d7}|i||i'} | o d8GHnyd7}|i||i'} x| D]}g}d9}|i4d:|i4|d i+d$i,d |i4|d%|i4|d&|i4|d'|i4|d(|i4|d+|i4|d,|i||t/i0i1d-qGWdGHWnCtj o7}dGH|i|ii|dd t|nXyZd;Gd<k5l6}l7}|tii|id=tii|id>dGHd?d@GHWn9tj o-}dGH|ii|dd t|nXWnnX|i8Wn>tj o2}|i|ii|dd t|nXdS(ANs!Upgrading WikiTemplates plugin...s!INSERT INTO system VALUES (%s,%s)stemplates_versions(UPDATE system SET value=%s WHERE name=%ss * Creating database table...s dones failedsexc_infois* * Adding default templates to database...s WikiTemplatessDefaultTemplatessTemplate: '%s's6INSERT INTO templates VALUES (%s,%s,%s,%s,%s,%s,%s,%s)sWiki Templates Pluginsis First time installing Trac Wiki sTemplates plugin version >= 0.3sdonesfaileds#Failed to include default templatess# * Including default permissions...sVIEWsCREATEsMODIFYs%INSERT INTO permission VALUES (%s,%s)s anonymouss TEMPLATES_s/Failed to include default templates permissionss * Migrating old templatess1SELECT * FROM wiki WHERE name LIKE '%templates/%'sFound %d < 0.3 templatessINSERT INTO templates s VALUES (%s,%s,%s,%s,%s,%s,%s,%s)s/iiiis[[Image(wiki:templates/s[[Image(templates:iis.s- No Wiki templates from versions < 0.3 found.s,No wiki templates from versions < 0.3 found.s * Deleting old templates...s Deleting old templates from the s'templates/' sub-wikis/DELETE FROM wiki WHERE name LIKE '%templates/%'s$Failed to delete old templates from sthe 'templates/' sub-wikis0 * Migrating attachments from versions < 0.3 ...s5SELECT * FROM attachment WHERE id LIKE '%templates/%'sNo attachments foundsUPDATE attachment SET type=%s, id=%s WHERE filename=%s AND size=%s AND time=%s AND description=%s AND author=%s AND ipnr=%su templatess! * Moving attachements to new dir(smovescopytreesattachments/wiki/templatessattachments/templatess1 * You should confirm that the attachments have sthe permissions correctly set.(9sdbscursorsDatabaseManagersenvs_get_connectors db_backends_sQUERYsexecutestemplates_versionsTrues ADD_PERMSsschemastablesto_sqlsstmtslogsdebugs Exceptionseserrorsrollbacks TracErrorstimesresource_filenamesdeflt_templates_dirsosslistdirstplsopenspathsjoinsfsreadsbodysclosesintsvalsspermsfetchallsrowsslensrowssplitspopsreplacesVALSssyssstdoutswritesqueryscolsappendsshutilsmovescopytreescommit(senvsversdbsdeflt_templates_dirsmovesVALSsquerystablesrowsrowsspermsbodysstmtsvalss_ses db_backendsfs ADD_PERMSstplscopytreescursorstimesQUERYscol((s>build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/upgrades/db1.pys do_upgrade-s"        *        n            #    (sos.pathsosssyss pkg_resourcessresource_filenames trac.cores TracErrorstrac.dbsDatabaseManagersWikiTemplates.db_schemasversionstemplates_versionsschemas do_upgrade(stemplates_versions TracErrorsresource_filenamessyssDatabaseManagers do_upgradesossschema((s>build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/upgrades/db1.pys?$s      PKJ8-g''WikiTemplates/upgrades/db1.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: db1.py 55 2008-02-10 05:39:31Z s0undt3ch $ # ============================================================================= # $URL: http://wikitemplates.ufsoft.org/svn/trunk/WikiTemplates/upgrades/db1.py $ # $LastChangedDate: 2008-02-10 06:39:31 +0100 (So, 10 Feb 2008) $ # $Rev: 55 $ # $LastChangedBy: s0undt3ch $ # ============================================================================= ############################################################################### # # # Copyright 2006 by Pedro Algarvio # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 2 of the License, or (at your option) # # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # ############################################################################### # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= import os.path import os import sys from pkg_resources import resource_filename from trac.core import TracError from trac.db import DatabaseManager from WikiTemplates.db_schema import version as templates_version, schema def do_upgrade(env, ver, db): print 'Upgrading WikiTemplates plugin...' try: cursor = db.cursor() db_backend, _ = DatabaseManager(env)._get_connector() try: QUERY = "INSERT INTO system VALUES (%s,%s)" cursor.execute(QUERY, ('templates_version', templates_version)) ADD_PERMS = True except: # This next step bellow really ain't necessary, cuz this will be # the first time the database will be created QUERY = "UPDATE system SET value=%s WHERE name=%s" cursor.execute(QUERY, (templates_version, 'templates_version')) print ' * Creating database table...', try: for table in schema: for stmt in db_backend.to_sql(table): env.log.debug(stmt) cursor.execute(stmt) print ' done' except Exception, e: print ' failed' env.log.error(e, exc_info=1) db.rollback() raise TracError, e # Include default templates print ' * Adding default templates to database...', try: import time deflt_templates_dir = resource_filename('WikiTemplates', 'DefaultTemplates') for tpl in os.listdir(deflt_templates_dir): env.log.debug("Template: '%s'" % tpl) f = open(os.path.join(deflt_templates_dir, tpl)) body = f.read() f.close() QUERY = 'INSERT INTO templates VALUES (%s,%s,%s,%s,%s,%s,%s,%s)' vals = (tpl, # name 1, # version int(time.time()), # time 'Wiki Templates Plugin', # author '', # ipnr body, # contents '', # comment 0 # read-only ) cursor.execute(QUERY, vals) env.log.debug('First time installing Trac Wiki ' + \ 'Templates plugin version >= 0.3') print 'done' except Exception, e: print 'failed' env.log.debug('Failed to include default templates') env.log.error(e, exc_info=1) db.rollback() raise TracError, e print ' * Including default permissions...', try: for perm in ('VIEW', 'CREATE', 'MODIFY'): QUERY = "INSERT INTO permission VALUES (%s,%s)" vals = ('anonymous', 'TEMPLATES_' + perm) cursor.execute(QUERY, vals) print ' done' except Exception, e: print ' failed' env.log.debug('Failed to include default templates ' 'permissions') env.log.error(e, exc_info=1) db.rollback() raise TracError, e # Migrate old templates to our new table print ' * Migrating old templates', try: QUERY = "SELECT * FROM wiki WHERE name LIKE '%templates/%'" cursor.execute(QUERY) rows = cursor.fetchall() env.log.debug("Found %d < 0.3 templates", len(rows)) for row in rows: try: QUERY = 'INSERT INTO templates ' + \ 'VALUES (%s,%s,%s,%s,%s,%s,%s,%s)' VALS = (row[0].split('/').pop(1), # name int(row[1]), # version int(row[2]), # time row[3], # author row[4], # ipnr row[5].replace('[[Image(wiki:templates/', '[[Image(templates:'), # text row[6], # comment int(row[7]) # readonly ) cursor.execute(QUERY, VALS) sys.stdout.write('.') except Exception, e: print ' failed' env.log.error(e, exc_info=1) db.rollback() raise TracError, e print ' done' except Exception, e: print ' No Wiki templates from versions < 0.3 found.' env.log.debug('No wiki templates from versions < 0.3 found.') print ' * Deleting old templates...', try: # Remove those templates under the 'templates/' sub-wiki env.log.debug("Deleting old templates from the " + \ "'templates/' sub-wiki") QUERY = "DELETE FROM wiki WHERE name LIKE '%templates/%'" env.log.debug(QUERY) cursor.execute(QUERY) print ' done' except Exception, e: print ' failed' env.log.debug("Failed to delete old templates from " + \ "the 'templates/' sub-wiki") env.log.error(e, exc_info=1) db.rollback() raise TracError, e print ' * Migrating attachments from versions < 0.3 ...', try: query = "SELECT * FROM attachment WHERE id LIKE '%templates/%'" cursor.execute(query) rows = cursor.fetchall() if not rows: print 'No attachments found' else: try: query = "SELECT * FROM attachment WHERE id LIKE '%templates/%'" cursor.execute(query) rows = cursor.fetchall() for row in rows: col = [] query = """UPDATE attachment SET type=%s, id=%s WHERE filename=%s AND size=%s AND time=%s AND description=%s AND author=%s AND ipnr=%s""" col.append(u'templates') col.append(row[1].split('/').pop(1)) col.append(row[2]) col.append(row[3]) col.append(row[4]) col.append(row[5]) col.append(row[6]) col.append(row[7]) cursor.execute(query, col) sys.stdout.write('.') print ' done' except Exception, e: print ' failed' db.rollback() env.log.error(e, exc_info=1) raise TracError, e # Move attachements to the new location try: print ' * Moving attachements to new dir', from shutil import move, copytree move(os.path.join(env.path, 'attachments/wiki/templates'), os.path.join(env.path, 'attachments/templates')) print ' done' print ' * You should confirm that the attachments have ' + \ 'the permissions correctly set.' except Exception, e: print ' failed' env.log.error(e, exc_info=1) raise TracError, e except: pass db.commit() except Exception, e: db.rollback() env.log.error(e, exc_info=1) raise TracError, e PK68k#WikiTemplates/upgrades/__init__.pyc; .GDc@sdS(N((((sCbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/upgrades/__init__.pys?sPK682}Θ"WikiTemplates/macros/templates.pyc; =uEc@sdkZdkZdkTdklZdklZdklZl Z dk l Z dk l Z dklZdklZeid Zeid Zd Zd efd YZdS(N(s*(sIEnvironmentSetupParticipant(sIWikiMacroProvider(s wiki_to_htmlswiki_to_oneliner(s to_unicode(s WikiTemplate(sTemplatesError(sversions \{\{\d+\}\}u^

|^

|

$|

$isTemplatesMacrocBsQtZdZeeedZdZdZdZ dZ dZ RS(s Grab a wiki page and include it inside another with pre-formated text replacing the vars '''`{{n}}`''' by the args passed, '''`n`''' being a number. All templates are stored on a diferent DB table than the wiki one.[[BR]] To create them click the ''Wiki Templates'' button shown on the menu bar, there's a box on the topmost right side that allows you to do just that; or go to ''`http://domain.com/templates/TheNameOfTemplate`'', !TheNameOfTemplate being the name of the template you want to create. Arguments are separated by '''`|`'''(pipe), and the first one passed is the name of the template to be used. So, for example, if you have a template(!RedTemplate) with the pre-formated text inside, like for example: {{{ {{{ #!html {{1}} }}} }}} You would use it like: {{{ [[T(RedTemplate|Arg1)]] }}} [[BR]] For more information go to: http://wikitemplates.ufsoft.org cCsdS(N((sself((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pysenvironment_createdAscCs|i}ymd}|i|t|id}| otSn|tjo|}tSn|tjot SnWn|i tSnXdS(Ns7SELECT value FROM system WHERE name='templates_version'i( sdbscursorsQUERYsexecutesintsfetchonesversionsTruestemplates_versionstemplates_version_dbsFalsesrollback(sselfsdbstemplates_version_dbscursorsversionsQUERY((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pysenvironment_needs_upgradeDs      cCs|i}xttdtdD]}d|}y1tdtt |g}t ||}Wn,t j o d||f}t|nX|i|i||q$WdS(Nisdb%isWikiTemplates.upgradess(No upgrade module for version %i (%s.py)(sdbscursorsrangestemplates_version_dbstemplates_versionsisnames __import__sglobalsslocalssupgradessgetattrsscriptsAttributeErrorserrs TracErrors do_upgradesselfsenv(sselfsdbsnameserrsscriptsiscursorsupgrades((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pysupgrade_environmentVs  ccsdVdS(NsT((sself((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pys get_macroscscCstitSdS(N(sinspectsgetdocsTemplatesMacro(sselfsname((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pysget_macro_descriptionfscCs| otdn|o|iddjo|idd}gi}|idD]}||i q^~}gi}t t |D] }|||iddq~} qgi}|idD]}||i q~} nt|i| id} |iidt| | idjoD|iid| itd | i}|iid ||Sn|iid | i| i}t ti|} d}x@t | D]2}|id |dd jo|d7}qqW|iid|t | } |iid| | |jo|iidn| |jotd| |fSn&| |jotd| |fSnxt |D]}|id|dd jo"|id |d| |}qt#| ||idt$dt%| |<| |idd| |<|id |d| |}qWt&||i|} t)i*t+d| } | i SdS(NsNo template name passeds\|is~!#~s|sTemplate Wiki: '%r'is"Template Wiki '%r' does not exist.sTemplate '%r' does not exist.s%rsTemplate Wiki '%r' exists.s{{%d}}isTemplate asks for %d argumentssUser is passing %d argumentss'Passed args and asked args don't match.sYou're passing less arguments(%d) than those the template asks for(%d). Click your browser's back button and correct the error, or check the edit box below if present.sYou're passing more arguments(%d) that those the template supports(%d). Click your browser's back button and correct the error, or check theedit box below if present.sInclude({{%d}})sshortensabsurlss\ns
s(,scontents Exceptionsfindsreplaces temp_argssappends_[1]ssplitsargsstrips striped_argssrangeslensxsargss WikiTemplatesselfsenvspopstemplateslogsdebugs to_unicodesversionsnamesTemplatesErrorsreturn_messagestextscontentssARGS_REsfindallstmp_argsstpl_argssisnr_argsswiki_to_onelinersFalsesTrues wiki_to_htmlsreqs wiki2htmlsressubsSTRIP_RE(sselfsreqsnamescontents temp_argssargsreturn_messagestpl_argsscontentssnr_argsstemplatestmp_argssargss wiki2htmlsis_[1]sxs striped_args((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pys render_macroisX6G:          ""( s__name__s __module__s__doc__s implementssIWikiMacroProvidersIEnvironmentSetupParticipantsenvironment_createdsenvironment_needs_upgradesupgrade_environments get_macrossget_macro_descriptions render_macro(((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pysTemplatesMacros      (sresinspects trac.corestrac.envsIEnvironmentSetupParticipants trac.wiki.apisIWikiMacroProviderstrac.wiki.formatters wiki_to_htmlswiki_to_onelinerstrac.util.texts to_unicodesWikiTemplates.models WikiTemplatesWikiTemplates.errorssTemplatesErrorsWikiTemplates.db_schemasversionstemplates_versionscompilesARGS_REsSTRIP_REstemplates_version_dbs ComponentsTemplatesMacro(stemplates_versions to_unicodesIWikiMacroProvidersinspects wiki_to_htmlstemplates_version_dbs WikiTemplateswiki_to_onelinersresIEnvironmentSetupParticipantsARGS_REsSTRIP_REsTemplatesErrorsTemplatesMacro((sBbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/templates.pys?s        PKJ8_k-- WikiTemplates/macros/__init__.py__all__ = ['includes', 'templates', 'image'] PKEk15*ll WikiTemplates/macros/includes.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: includes.py 48 2006-09-17 17:26:10Z s0undt3ch $ # ============================================================================= # $URL: http://wikitemplates.ufsoft.org/svn/trunk/WikiTemplates/macros/includes.py $ # $LastChangedDate: 2006-09-17 19:26:10 +0200 (So, 17 Sep 2006) $ # $Rev: 48 $ # $LastChangedBy: s0undt3ch $ # ============================================================================= ############################################################################### # # # Copyright 2006 by Pedro Algarvio # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 2 of the License, or (at your option) # # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # ############################################################################### # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= import inspect from trac.core import * from trac.wiki.api import IWikiMacroProvider from trac.wiki.formatter import wiki_to_html from WikiTemplates.model import WikiTemplate from WikiTemplates.errors import TemplatesError class IncludesMacro(Component): """Grab a wiki page and include it's full contents inside another. To use: {{{ [[Include(WikiPageNameToInclude)]] }}} [[BR]] For more information go to: http://wikitemplates.ufsoft.org""" implements(IWikiMacroProvider) # IWikiMacroProvider methods def get_macros(self): yield "Include" def get_macro_description(self, name): return inspect.getdoc(IncludesMacro) def render_macro(self, req, name, content): if not content: raise TracError, "Nothing was passed" # First strip args passed args = [arg.strip() for arg in content.split('|')] if len(args) != 1: self.env.log.debug('ARGS PASSED TO INCLUDE: %r', args) return TemplatesError( "The 'Include' macro doesn't support arguments.\n" "It exists to simply include another wiki page into " "the current one.\nClick your browser's back button " "and correct the error, or check the edit box " "below if present.") if args[0].startswith('http://') or args[0].startswith('https://'): import urllib try: webpage = urllib.urlopen(args[0]) html = webpage.read() webpage.close() self.env.log.debug('INCLUDE CONTENTS: %r', html) return html except Exception, e: return TracError, e else: contents = WikiTemplate(self.env, args.pop(0), table="wiki") return wiki_to_html(contents.text, self.env, req) PK85 E]"]"WikiTemplates/macros/image.py# -*- coding: iso8859-15 -*- # ============================================================================= # $Id: image.py 81 2006-09-25 02:29:56Z s0undt3ch $ # ============================================================================= # $URL: http://wikitemplates.ufsoft.org/svn/trunk/WikiTemplates/macros/image.py $ # $LastChangedDate: 2006-09-25 04:29:56 +0200 (Mo, 25 Sep 2006) $ # $Rev: 81 $ # $LastChangedBy: s0undt3ch $ # ============================================================================= # # Copyright (C) 2005-2006 Edgewall Software # Copyright (C) 2005-2006 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Christopher Lenz # Modified by Pedro Algarvio # ============================================================================= # vim: set tabstop=4 # vim: set shiftwidth=4 # # Display a red square on the 80th char so we can easely limit line width to a # max of 79 chars, the way it should be. # vim: autocmd BufEnter * match Error /\%80v/ # ============================================================================= import re from trac.util.html import html, Markup from trac.wiki.macros import WikiMacroBase class ImageMacro(WikiMacroBase): """Embed an image in wiki-formatted text. The first argument is the file specification. The file specification may reference attachments or files in three ways: * `module:id:file`, where module can be either '''wiki''', '''ticket''' or '''templates''' to refer to the attachment named ''file'' of the specified wiki page, ticket or template. * `id:file`: same as above, but id is either a ticket shorthand or a Wiki page name. * `file` to refer to a local attachment named 'file'. This only works from within that wiki page, ticket. '''Note''': To use the templates attachments, the first form from above '''must''' be used Also, the file specification may refer to repository files, using the `source:file` syntax (`source:file@rev` works also). The remaining arguments are optional and allow configuring the attributes and style of the rendered `` element: * digits and unit are interpreted as the size (ex. 120, 25%) for the image * `right`, `left`, `top` or `bottom` are interpreted as the alignment for the image * `nolink` means without link to image source. * `key=value` style are interpreted as HTML attributes or CSS style indications for the image. Valid keys are: * align, border, width, height, alt, title, longdesc, class, id and usemap * `border` can only be a number Examples: {{{ [[Image(photo.jpg)]] # simplest [[Image(photo.jpg, 120px)]] # with size [[Image(photo.jpg, right)]] # aligned by keyword [[Image(photo.jpg, nolink)]] # without link to source [[Image(photo.jpg, align=right)]] # aligned by attribute }}} You can use image from other page, other ticket or other module. {{{ [[Image(OtherPage:foo.bmp)]] # if current module is wiki [[Image(base/sub:bar.bmp)]] # from hierarchical wiki page [[Image(#3:baz.bmp)]] # if in a ticket, point to #3 [[Image(ticket:36:boo.jpg)]] [[Image(source:/images/bee.jpg)]] # straight from the repository! [[Image(htdocs:foo/bar.png)]] # image file in project htdocs dir. [[Image(templates:foo_tpl:bar.png)]] # image attached to a template }}} ''Adapted from the Image.py macro created by Shun-ichi Goto '' """ def render_macro(self, req, name, content): # args will be null if the macro is called without parenthesis. if not content: return '' # parse arguments # we expect the 1st argument to be a filename (filespec) args = content.split(',') if len(args) == 0: raise Exception("No argument.") filespec = args[0] size_re = re.compile('[0-9]+%?$') attr_re = re.compile('(align|border|width|height|alt' '|title|longdesc|class|id|usemap)=(.+)') quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$") attr = {} style = {} nolink = False for arg in args[1:]: arg = arg.strip() if size_re.match(arg): # 'width' keyword attr['width'] = arg continue if arg == 'nolink': nolink = True continue match = attr_re.match(arg) if match: key, val = match.groups() m = quoted_re.search(val) # unquote "..." and '...' if m: val = m.group(1) if key == 'align': style['float'] = val elif key == 'border': style['border'] = ' %dpx solid' % int(val); else: attr[str(key)] = val # will be used as a __call__ keyword # parse filespec argument to get module and id if contained. parts = filespec.split(':') url = None if len(parts) == 3: # module:id:attachment if parts[0] in ['wiki', 'ticket', 'templates']: module, id, file = parts else: raise Exception("%s module can't have attachments" % parts[0]) elif len(parts) == 2: from trac.versioncontrol.web_ui import BrowserModule try: browser_links = [link for link,_ in BrowserModule(self.env).get_link_resolvers()] except Exception: browser_links = [] if parts[0] in browser_links: # source:path module, file = parts rev = None if '@' in file: file, rev = file.split('@') url = req.href.browser(file, rev=rev) raw_url = req.href.browser(file, rev=rev, format='raw') desc = filespec else: # #ticket:attachment or WikiPage:attachment # FIXME: do something generic about shorthand forms... id, file = parts if id and id[0] == '#': module = 'ticket' id = id[1:] elif id == 'htdocs': raw_url = url = req.href.chrome('site', file) desc = os.path.basename(file) elif id in ('http', 'https', 'ftp'): # external URLs raw_url = url = desc = id+':'+file else: module = 'wiki' elif len(parts) == 1: # attachment # determine current object # FIXME: should be retrieved from the formatter... # ...and the formatter should be provided to the macro file = filespec module, id = 'wiki', 'WikiStart' path_info = req.path_info.split('/',2) if len(path_info) > 1: module = path_info[1] if len(path_info) > 2: id = path_info[2] if module not in ['wiki', 'ticket', 'templates']: raise Exception('Cannot reference local attachment from here') else: raise Exception('No filespec given') if not url: # this is an attachment from trac.attachment import Attachment attachment = Attachment(self.env, module, id, file) self.env.log.debug(attachment) url = attachment.href(req) raw_url = attachment.href(req, format='raw') desc = attachment.description for key in ['title', 'alt']: if desc and not attr.has_key(key): attr[key] = desc if style: attr['style'] = '; '.join(['%s:%s' % (k, escape(v)) for k, v in style.iteritems()]) result = Markup(html.IMG(src=raw_url, **attr)).sanitize() if not nolink: result = html.A(result, href=url, style='padding:0; border:none') return result PK68Ќ5 !WikiTemplates/macros/includes.pyc; 2 Ec@s^dkZdkTdklZdklZdklZdkl Z de fdYZ dS(N(s*(sIWikiMacroProvider(s wiki_to_html(s WikiTemplate(sTemplatesErrors IncludesMacrocBs3tZdZeedZdZdZRS(sGrab a wiki page and include it's full contents inside another. To use: {{{ [[Include(WikiPageNameToInclude)]] }}} [[BR]] For more information go to: http://wikitemplates.ufsoft.orgccsdVdS(NsInclude((sself((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/includes.pys get_macros8scCstitSdS(N(sinspectsgetdocs IncludesMacro(sselfsname((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/includes.pysget_macro_description;sc Cs[| o tdngi}|idD]} || iq,~}t|djo$|i i i d|t dSn|didp|didovdk} yG| i|d}|i}|i|i i i d ||SWqWtj o}t|fSqWXn8t|i |idd d } t| i|i |SdS( NsNothing was passeds|isARGS PASSED TO INCLUDE: %rsThe 'Include' macro doesn't support arguments. It exists to simply include another wiki page into the current one. Click your browser's back button and correct the error, or check the edit box below if present.ishttp://shttps://sINCLUDE CONTENTS: %rstableswiki(scontents TracErrorsappends_[1]ssplitsargsstripsargsslensselfsenvslogsdebugsTemplatesErrors startswithsurllibsurlopenswebpagesreadshtmlscloses Exceptionses WikiTemplatespopscontentss wiki_to_htmlstextsreq( sselfsreqsnamescontents_[1]sargsseswebpageshtmlsurllibsargscontents((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/includes.pys render_macro>s$ 6(   !(s__name__s __module__s__doc__s implementssIWikiMacroProviders get_macrossget_macro_descriptions render_macro(((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/includes.pys IncludesMacro,s    ( sinspects trac.cores trac.wiki.apisIWikiMacroProviderstrac.wiki.formatters wiki_to_htmlsWikiTemplates.models WikiTemplatesWikiTemplates.errorssTemplatesErrors Components IncludesMacro(sIWikiMacroProviders wiki_to_htmlsinspects IncludesMacros WikiTemplatesTemplatesError((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/includes.pys?$s     PK68.!WikiTemplates/macros/__init__.pyc; Gc@sdddgZdS(sincludess templatessimageN(s__all__(s__all__((sAbuild/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/__init__.pys?sPK68k..WikiTemplates/macros/image.pyc; $?Ec@sCdkZdklZlZdklZdefdYZdS(N(shtmlsMarkup(s WikiMacroBases ImageMacrocBstZdZdZRS(s Embed an image in wiki-formatted text. The first argument is the file specification. The file specification may reference attachments or files in three ways: * `module:id:file`, where module can be either '''wiki''', '''ticket''' or '''templates''' to refer to the attachment named ''file'' of the specified wiki page, ticket or template. * `id:file`: same as above, but id is either a ticket shorthand or a Wiki page name. * `file` to refer to a local attachment named 'file'. This only works from within that wiki page, ticket. '''Note''': To use the templates attachments, the first form from above '''must''' be used Also, the file specification may refer to repository files, using the `source:file` syntax (`source:file@rev` works also). The remaining arguments are optional and allow configuring the attributes and style of the rendered `` element: * digits and unit are interpreted as the size (ex. 120, 25%) for the image * `right`, `left`, `top` or `bottom` are interpreted as the alignment for the image * `nolink` means without link to image source. * `key=value` style are interpreted as HTML attributes or CSS style indications for the image. Valid keys are: * align, border, width, height, alt, title, longdesc, class, id and usemap * `border` can only be a number Examples: {{{ [[Image(photo.jpg)]] # simplest [[Image(photo.jpg, 120px)]] # with size [[Image(photo.jpg, right)]] # aligned by keyword [[Image(photo.jpg, nolink)]] # without link to source [[Image(photo.jpg, align=right)]] # aligned by attribute }}} You can use image from other page, other ticket or other module. {{{ [[Image(OtherPage:foo.bmp)]] # if current module is wiki [[Image(base/sub:bar.bmp)]] # from hierarchical wiki page [[Image(#3:baz.bmp)]] # if in a ticket, point to #3 [[Image(ticket:36:boo.jpg)]] [[Image(source:/images/bee.jpg)]] # straight from the repository! [[Image(htdocs:foo/bar.png)]] # image file in project htdocs dir. [[Image(templates:foo_tpl:bar.png)]] # image attached to a template }}} ''Adapted from the Image.py macro created by Shun-ichi Goto '' c$Cs| odSn|id}t|djotdn|d}tid}"tid}tid} h}h} t }x|dD]}|i}|"i|o||d D]&\}}!| d)|tA|!fq3~ |d*build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/image.pys render_macrobs        @           T!(s__name__s __module__s__doc__s render_macro(((s>build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/image.pys ImageMacro)s 7(srestrac.util.htmlshtmlsMarkupstrac.wiki.macross WikiMacroBases ImageMacro(sresMarkupshtmls ImageMacros WikiMacroBase((s>build/bdist.darwin-8.0.1-x86/egg/WikiTemplates/macros/image.pys?%s  PK|65&) ) !WikiTemplates/macros/templates.py# $Id: templates.py 71 2006-09-22 23:43:57Z s0undt3ch $ # -*- coding: iso8859-15 -*- # vim:set tabstop=4 # vim:set shiftwidth=4 # ------------------------------------------------------------------------- # Copyright (C) 2005 Unfinished Software, UfSoft.org # Copyright (C) 2005 Pedro Algarvio # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # Author: Pedro Algarvio, aka s0undt3ch # ------------------------------------------------------------------------- import re import inspect from trac.core import * from trac.env import IEnvironmentSetupParticipant from trac.wiki.api import IWikiMacroProvider from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner from trac.util.text import to_unicode from WikiTemplates.model import WikiTemplate from WikiTemplates.errors import TemplatesError from WikiTemplates.db_schema import version as templates_version ARGS_RE = re.compile(r'\{\{\d+\}\}') STRIP_RE = re.compile(u'^

|^

|

$|

$') templates_version_db = 0 class TemplatesMacro(Component): """ Grab a wiki page and include it inside another with pre-formated text replacing the vars '''`{{n}}`''' by the args passed, '''`n`''' being a number. All templates are stored on a diferent DB table than the wiki one.[[BR]] To create them click the ''Wiki Templates'' button shown on the menu bar, there's a box on the topmost right side that allows you to do just that; or go to ''`http://domain.com/templates/TheNameOfTemplate`'', !TheNameOfTemplate being the name of the template you want to create. Arguments are separated by '''`|`'''(pipe), and the first one passed is the name of the template to be used. So, for example, if you have a template(!RedTemplate) with the pre-formated text inside, like for example: {{{ {{{ #!html {{1}} }}} }}} You would use it like: {{{ [[T(RedTemplate|Arg1)]] }}} [[BR]] For more information go to: http://wikitemplates.ufsoft.org """ implements(IWikiMacroProvider, IEnvironmentSetupParticipant) # IEnvironmentSetupParticipant Methods def environment_created(self): pass def environment_needs_upgrade(self, db): cursor = db.cursor() try: QUERY = "SELECT value FROM system WHERE name='templates_version'" cursor.execute(QUERY) version = int(cursor.fetchone()[0]) if not version: return True if version < templates_version: templates_version_db = version return True elif version == templates_version: return False except: db.rollback() return True def upgrade_environment(self, db): cursor = db.cursor() for i in range(templates_version_db + 1, templates_version +1): name = 'db%i' % i try: upgrades = __import__('WikiTemplates.upgrades', globals(), locals(), [name]) script = getattr(upgrades, name) except AttributeError: err = 'No upgrade module for version %i (%s.py)' % (i, name) raise TracError, err script.do_upgrade(self.env, i, db) # WikiMacroProvider Methods def get_macros(self): yield 'T' def get_macro_description(self, name): return inspect.getdoc(TemplatesMacro) def render_macro(self, req, name, content): # Raise an Exception if the macro is called without # parenthesis, or no template name is passed. if not content: raise Exception("No template name passed") if content: # find if we're escaping '|' and replace it with an awkard # combination of chars, so we can later add | again. if content.find('\|') > 0: temp_args = content.replace('\|', '~!#~') # parse arguments striped_args = [arg.strip() for arg in temp_args.split('|')] # Now we put back '|' where it's needed args = [ striped_args[x].replace('~!#~', '|') for x in range(len(striped_args)) ] else: # We're not escaping '|' so, let's split it args = [arg.strip() for arg in content.split('|')] # Check to see if the user is passing any arguments, # if not, check if the template called asks for any # argument at all and don't fail if it doesn't. # Finaly check to see if the number of passed arguments # matches the ones the template asks for, if not fail # and warn the user. # Let's select the template to use template = WikiTemplate(self.env, args.pop(0)) self.log.debug("Template Wiki: '%r'", to_unicode(template)) if template.version < 1: self.log.debug("Template Wiki '%r' does not exist.", template.name) return_message = TemplatesError( "Template '%r' does not exist." % template.name) self.log.debug('%r', return_message) return return_message self.log.debug("Template Wiki '%r' exists.", template.name) # Grab the template contents contents = template.text tmp_args = len(ARGS_RE.findall(contents)) tpl_args = 0 # Find out the real count of args we need, template might have # repeated arguments for example two ocurrences of {{1}} for i in range(tmp_args): if contents.find("{{%d}}" % (i+1)) != -1: tpl_args += 1 self.log.debug("Template asks for %d arguments", tpl_args) nr_args = len(args) self.log.debug("User is passing %d arguments", nr_args) if nr_args != tpl_args: self.log.debug("Passed args and asked args don't match.") if nr_args < tpl_args: return TemplatesError( "You're passing less arguments(%d) than those " "the template asks for(%d).\nClick your browser's" " back button and correct the error, or check the" " edit box below if present." % (nr_args, tpl_args)) elif nr_args > tpl_args: return TemplatesError( "You're passing more arguments(%d) that those " "the template supports(%d).\nClick your browser's " "back button and correct the error, or check the" "edit box below if present." % (nr_args, tpl_args)) # else: # self.log.debug("Passed args and asked args match.") # Now let's replace the holders with the passed arguments for i in range(tpl_args): # Are we trying to use the include macro, if we are # we must not convert wiki syntax to html for this argument if contents.find("Include({{%d}})" % (i+1)) != -1: contents = contents.replace('{{%d}}' % (i+1), args[i]) else: # First we covert any wiki syntax to html args[i] = wiki_to_oneliner(args[i], self.env, shorten=False, absurls=True) # Now, if we have passed any linefeeds, # convert them also to html args[i] = args[i].replace(r'\n', '
') # Finaly replace our variables place holders # with the passed contents. contents = contents.replace('{{%d}}' % (i+1), args[i]) # self.log.debug(contents) # Finaly return the HTML to include wiki2html = wiki_to_html(contents, self.env, req) # self.log.debug('wiki_to_html pre: "%r"' % wiki2html) # Remove '

' and '

' that caused an inline template # to be broken in two. wiki2html = re.sub(STRIP_RE, '', wiki2html) # self.log.debug('wiki_to_html post re: "%r"' % wiki2html) # Strip linefeeds, causes source html to in just one line, # but fixes #3. return wiki2html.strip() PKt45Η(WikiTemplates/htdocs/js/wikitemplates.jsfunction delete_mainnav_templatesbtn() { var templatesbtn = document.getElementById('templatesbtn'); templatesbtn.parentNode.removeChild(templatesbtn); } PK[`4¹+,,$WikiTemplates/htdocs/img/preview.pngPNG  IHDR{$gAMA abKGD pHYs  tIME16 IDATxyp}?g087DuYlKڱכl,gSv9rv]+9hRل,oŎ,GĔ|EZa q={i4{Uu=qp 7I†s@9@=\=ȫ]AȺU8|Vuus>wKM7.oXq&='TؤnܩE /nSovK4^[o&Yc&՗3'Z(%4SE[.]};uRخ^;d#ЭY]sAϛ%_*|l|uf䚟K*&`-Wӻ@QݸX- C=u'fi~s4Xpt m9xLZ=n#*kRR*kf$7+ kyIWO@MQn?'Xdᗃ?oO C8 w} z-&gK#Ji^0M?aabgm߁e1髯z"JXUL]0ay<:(7:/-}˼zjÏ(oUb%5qh>lj2!T ;ZlFau(ke Qa,gPPuUH3%gܮ"e<~pJ & $Jv%mn(Cp:{ӐK@W n5-LYTg^0 H=̫՟E]\zXuԔjZ$g~_s)af6z/ atM -?C%4v7AW>ܣe6Ssm3^%)PFx6_Ceap:gB d@/@k;._%K[sdB_f|F:aJ<5\czJ'9Ix|6\̰t)f3Ӄ0f91݂V,(s%0l`ؾFa!!G;%{-vi߀jLEJh4ݕ T'<\롣0tԔLВ,ٻMYam9jsBŵ~jLиaƺ LypVήvS`>  ø)N„=d0$^h{r&Y4IhkUC8/@ʄS.[(fmIBG?*?9T2tuOM0I04H $)[XH{ӰϔS4 Fi.dӲa/ຬ<FNI9aypz„]Y"ߵ-հ/yZe0pM_”s1Ŭv ! d-S=U p  VZwE8,Z2!'a†<4-*Gv_&`cLU">uC/Ga GA4GUJN$a7ZmƊ-Н@ ܥ8}X}z”)5,iq٠kr߇aWq6` lN0 .XӮ ֘Гp 3aN8k}aStvDſ6awVpc@n{vy i`%/uL}.CS[`^f6d:<ք)<0O^ XkJMK%I0͇!p7m.uu`J݅&lr/AK 9Y~RF*A8+鋼MɭZ߃-de;(4H  1f'XO1P7hYXt-_(,n=>@?\)hA<_^Y Y!F;$$- "֎:1++ut`̢ R_ǚ3 !ŬPJ*;ᢺ"*`Pj-"lFy)o7ldaG{USE."*3#ZYQ(Ri#k=ٰXXf$#b]5_,Zְwk>/$X. &Ʉ{.DcVn_qhJ ۵k6!b*2t%:Hn!M~F:rjgN B@$=3> 0w쟑HnA;jDhl>=a< oxag.` u~h=)vC0m;P5ImzN7z!acLVبʜ,9l/qR(7Ц|!ÖS0fK;8tpAt*O9o蟻W{ҍe@Ydy@`!{S0~fytQDžƫם@, h~^=⼷:C؛$2piIig)sTKbFBBn|fgo%n`R_by)Ek/t] N5BUep)2Wʭެ_$@ 3^fq EهěWkmD[`_A`E8fDwC(t ,)o5/ǪD,qs]$M;Q'57VeաSeНq:  K6?p1)1R֍o0p| >;<_ܳe.* QJm'>[aĶI[]LJ2N/JI8CW`yc($)6'*`FP0d: b3~?/󵴽*W{օ|+#^;;Ad? "{!~̇^?k]9ߩ\s_ᖁrb)'tY.K J:AX( ܪʴģzj/8t#{pv'%-0MQP.FNWvsRsb1n{<'aG{eIGΗ}l^s)Q8'a_o/m_BJ .<2PCcU]gEME ߻q(؛+`.C-•1wZOsn|V= RY^})Q|7l~f>$D*Y2fɼY.'Y;1g[ B.ioծjbv)ܻ, /(J>d&hKRՍ՜؛/(?\"P5+j]*B mkZTM V *Sde6 K]MtAG7]bXڭu%ot7Vc5VcRp|M"^olߊ7?L2NN#jua# oQŵ/<.ʐ'7ي`B)'Da f 4zl  q9۞)w#[bv: 4q5ϡrZem"⨺J䄁KY/s`&!~r8 a)zMvQSao|)Mf;`EHD< WT&Zl6`U6lj!< @z-Qq'l6}󛀝y,T+\P Z#}\p.o+'-u @< 3o\.Un^yf.t0ͧdh6 ؑԃ0:<*'7y×`xh `Yi\e~5:%f4,F`gfptmǁ=0wX:Q`ZQXgh)(9'yFdE[yW2lśBY蓙^~E@9Z\'Ӈ5,à%l֠UsTW㧾fN7ZGV!$E_]G@'afv@=tțppQdd#S]̓^/d4uhaz \: |*Urv<z+ СHDىmm &ڥµh ~S\YUZ#T-emBF 3!"h_3O8WZA-;[k0-s!TUF| qSA>e6cW~CV >pÞLoT]la$!(;aIS|qTPmiӭvrLE;Rp1;`` nR3Ql`Ib@;ra2  ! ̼Svb9s+EIfMЛGe_MaO;Xacox[_ m#G|Z/¶Z~I8W]T[`$%7$ 3uME[v=&Ď M.l~ &w:g)Eīe#GY:"; 0 2C 0t,o "Sw9UlcN>EK1 MZ%f ;ySFB0ǡ #eJO/'M_Yq́N Zb7}/p Rum#^Ə\]W!c.#L_J»Vz,̓MLTW?SItD%p^4I9r_Ba'` 4.)['7XJOy:Z± 0vjV{>% lD@간vMmfUY9|h9lO]^ya04 Smpu2|k \; {o(~LY0]j9m~'rDW$d.g!}+ϵJ}af oY 4cJ^s5^u<'a#,4y@R[?.&&>~bjz PaSQNSN&NTAZđtDRP$ ,KKxPWe̚(f?ÅJ)o2to(,&AqOqXtqy8J2Htb]8;\8/ G8uО{0? ;(혎Ӽ'ԕ+Κ}5e^2)_\4*BG<*u;0n9;3pnJo]6mZN^ z[閡`5 kۯiXF?׽{@LЛ^NXXXkFjƪvӑYHHwZ#΍X^<\ k[2K$(! X׊ Y][DFaLS0eE6a&5֚!rKO|=,@847AWH`DGWCҟ+Nl0CcSkQ X<0hB[7tВBCt2Š U+Ț aYm rrKqh'C8=,fXVJkRn"&@OCj枂C DahCE=EГ,|TNѱC jeb<Mh8$A{'ECvF4!-H|niwѪb%[54([ Z|3zy03=@C6w |ciPybFh0AE=f$$ЩɎoqHvB.9F 󥥽 h^H,|qөLۭ<PZ3?)߭2qT>"h)ȞN֡S}v*6  dJyA^Dnzh{5|Dt9:$ в/a{`dȞ!RӋ8h4^n`udHHGטV֠5 ,rtW&99x.|!B$.7߭SGf` fqBC;fe׵"DԡrqUb~BMc@0 o/m>5_Rjwӧ ` Ӑ9d3I -@g:sĞs n-U}U k2~Ƨf. i4NBo!a8q'8i0B.e fv@FtQ(@~pg6* `o ؊lcJpPM50 1tK= $,fSH|0E]L҄4a$ 0h4D0tM_ 4 qIDATABQz܍Hb& ISpP UA?RD RKȇ!6\;VC fp,0"t$`bI#-)kp\ݴE%HZ\?DyV|!L߀ ~ ;`K?GSh{ _KS- zUR\8p`L /͟]E\}50YXVV§4-{ӬBQt ٽ"6BQ a-$TBC`SK5F-_h@H2C/@3Ƥ0{fI|f]$6Px&1L<1fljGWܲ7!FYۼSi-90c0UĽ ~DL00}|yl@0QoFv- l*@s&k^ 0?߇; z=S_8pCwvx݅#xM7`}S RcO>Sc\Z3n>ѽȿ vTȋ+*7A7\= ;DJr-݄9YϕZmw, W> 1tR隇kPLZFEp'!6h_z#"۹RS|z)f/|I‹*ǬO:T5N͔{q`A4>({d!ac ~.tn!-眠J*~N m~0[i"+da}E: # HOwiX{)$ľ熜yc*`E-JJ[8DT3r2z<(m0/KМ)>&C{ ga!dowóHt?}y]r?7gA`K2D{ \34v8ſ̙C(j^ 1z s 0ittB mE 7 |@wBIȾ SdU|h=CWڡ-UJUT~n;@}9/ʔe3Q{D `oekG@*XjyzUq݇.+dd@C.S SiC. !y쿯??/VԪI+T g Xl/$ݘi< G jn`!E{`ÿ^?+V IN! \yz@2!bqfK1mwK}q뒷oqn[lQ9^mLKT >  z h6 [e MRmb"nZMpÍ׭ 3LA[iW`P|~o s]@[R|ŒGx&?PaAP}WJC!L [ BHYIC`NAOn5+}O d%A73YҖ7iDq td7M?ڟeoNnI~oPm_u0Vy)0nfS0fYNx?j+xnfP/F@8/C0 !KDrj] No5/`ǥMWq(w+v#F=mPРلŴ0Vr_IoVkI.A Ͱ]e_^Kwc5r%!FJCLaMJ'7maMjI7j|cݐyhXj}4-[*IENDB`PK&4a*WikiTemplates/htdocs/css/wikitemplates.cssfieldset.tplprev { border: 2px groove black; padding: 6px 10px 18px 10px; background: #f4f4f4 url(../img/preview.png); } legend.tplprev { color: #000000; background: #FFFFFF; border: 2px groove black; padding: 3px 4px 5px 4px; text-align: center; width: 60px; } PK}25`EE(WikiTemplates/templates/WikiTemplates.cs
1 ?>

Delete template

Are you sure you want to completely delete this template?
This is the only version the template, so the template will be removed completely! This is an irreversible operation.

Changes between Version and from Version of

Show
Ignore:
checked="checked" />
checked="checked" />
checked="checked" />
Author:
1 ?>(multiple changes) (IP: )
Timestamp:
1 ?>(multiple changes) ( ago)--
Comment:
1 ?>(multiple changes)

Legend:

Unmodified
Added
Removed
Modified
  • Version Version
    v v  

Change History of

Version Date Author Comment
checked="checked" /> checked="checked" />
#10 ?>

Create a New Template

Editing ""

Preview of future version (modified by )
Preview (skip)
Sorry, this template has been modified by somebody else since you started editing. Your changes cannot be saved.

Note: See WikiFormatting and TracWiki for help on editing wiki content.
Change information

       
Version (modified by , ago)

Attachments

  • () -, added by on .

Template Preview [ ]

PKEk15tM-WikiTemplates/DefaultTemplates/TemplatesIndex= What is the !WikiTemplates Plugin = It's a macro plugin that if called like '''`[[T(....)]]`''', grab's a wiki page and includes it inside another with pre-formated text replacing the vars '''''`{{n}}`''''' by the args passed, '''''`n`''''' being a number. If called like '''`[[Include(....)]]`''' grabs a wiki page and include it's full contents inside another. Great aint it? Just imagine the posibilities...[[BR]] More info on the WikiMacros wiki page and http://wikitemplates.ufsoft.org = How to create new templates = As you might have noticed, there's a tiny box on the right side that says '''Create a New Template''', just put a string on that box and click the '''Create''' button, and you're good to go, next step is just like you'd do on a wiki page, or go to '''__`http://domain.com/templates/TheName`__''', '''!TheName''' being the name of the template you want to create. = List of Wiki Templates = Bellow you'll find a list of all Wiki Templates included on this Trac environment. It keeps growing as you add templates. PK682EGG-INFO/zip-safe PK68CCmmEGG-INFO/SOURCES.txtREADME setup.cfg setup.py TracWikiTemplates.egg-info/PKG-INFO TracWikiTemplates.egg-info/SOURCES.txt TracWikiTemplates.egg-info/dependency_links.txt TracWikiTemplates.egg-info/entry_points.txt TracWikiTemplates.egg-info/requires.txt TracWikiTemplates.egg-info/top_level.txt WikiTemplates/__init__.py WikiTemplates/attachment.py WikiTemplates/db_schema.py WikiTemplates/errors.py WikiTemplates/model.py WikiTemplates/web_ui.py WikiTemplates/macros/__init__.py WikiTemplates/macros/image.py WikiTemplates/macros/includes.py WikiTemplates/macros/templates.py WikiTemplates/upgrades/__init__.py WikiTemplates/upgrades/db1.py PK68C..EGG-INFO/entry_points.txt[trac.plugins] wikitemplates = WikiTemplates PK682EGG-INFO/dependency_links.txt PK68: EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: TracWikiTemplates Version: 0.3.0rc3 Summary: Trac Plugin to pre-format parts of the Wiki page using it Home-page: http://wikitemplates.ufsoft.org Author: Pedro Algarvio Author-email: ufs@ufsoft.org License: BSD Download-URL: http://python.org/pypi/TracWikiTemplates Description: =========================== Trac WikiTemplates Plugin =========================== WikiTemplates is a `Trac `_ plugin. This plugin will provide you a way to include parts of other wiki pages, the templates, into our current wiki page. **Why This?** You could have a template that makes the text red colored with a monospace font, and use the template instead of making multiple span's, Some Usage Examples ------------------- The template: :: {{{ #!html {{1}} }}} To use that template, one would put on the wiki page being edited: :: [[T(GreenText|The Green Text Passed)]] The HTML output: :: The Green Text Passed Another example would be: The template: :: {{{ #!html {{1}} {{2}} }}} Wiki implementation: :: [[T(GreenAndRedText|The Green Text Passed|And The Red Not Monospace Text)]] The HTML Output(with line breaks for readability): :: The Green Text Passed And The Red Not Monospace Text Of course this isn't that really usefull but just imagine the possibilities, too many to name here. As of version >=0.3.0, WikiTemplates also supports inclusion of whole wiki pages(with no arguments parsing) and even off site pages. Examples: Include a wiki page: :: [[Include(WikiPageName)]] Include an off-site page: :: [[Include(http://the.url.to.site.com/page)]] You can find more info on the `WikiTemplates `_ site where bugs and new feature requests should go to. Download and Installation ------------------------- WikiTemplates can be installed with `Easy Install `_ by typing:: > easy_install TracWikiTemplates Platform: OS Independent - Anywhere Python and Trac >=0.10 is known to run. Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Text Processing Classifier: Topic :: Utilities Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content PK685WEGG-INFO/requires.txtTracCtxtnavAddPK68C-EGG-INFO/top_level.txtWikiTemplates PK68sE--WikiTemplates/model.pycPK}25{bAOcOcbWikiTemplates/attachment.pyPKJ8YcgnyWikiTemplates/__init__.pyPK68s}t}tǁWikiTemplates/attachment.pycPK686D㶵hh~WikiTemplates/web_ui.pycPK|65##i_WikiTemplates/model.pyPKKt4  vWikiTemplates/errors.pyPK68Ϛ+WikiTemplates/errors.pycPK&4  WikiTemplates/db_schema.pyPK68 :C  WikiTemplates/__init__.pycPK68@yyHWikiTemplates/db_schema.pycPK75jNdNdWikiTemplates/web_ui.pyPKKt4"}WikiTemplates/upgrades/__init__.pyPK68]SSWikiTemplates/upgrades/db1.pycPKJ8-g''L WikiTemplates/upgrades/db1.pyPK68k#3WikiTemplates/upgrades/__init__.pycPK682}Θ"b4WikiTemplates/macros/templates.pycPKJ8_k-- :QWikiTemplates/macros/__init__.pyPKEk15*ll QWikiTemplates/macros/includes.pyPK85 E]"]"OaWikiTemplates/macros/image.pyPK68Ќ5 !WikiTemplates/macros/includes.pycPK68.!ӏWikiTemplates/macros/__init__.pycPK68k..WikiTemplates/macros/image.pycPK|65&) ) !YWikiTemplates/macros/templates.pyPKt45Η(WikiTemplates/htdocs/js/wikitemplates.jsPK[`4¹+,,$WikiTemplates/htdocs/img/preview.pngPK&4a*WikiTemplates/htdocs/css/wikitemplates.cssPK}25`EE(?WikiTemplates/templates/WikiTemplates.csPKEk15tM-?WikiTemplates/DefaultTemplates/TemplatesIndexPK682CEGG-INFO/zip-safePK68CCmm/DEGG-INFO/SOURCES.txtPK68C..FEGG-INFO/entry_points.txtPK6823GEGG-INFO/dependency_links.txtPK68: oGEGG-INFO/PKG-INFOPK685W9UEGG-INFO/requires.txtPK68C-zUEGG-INFO/top_level.txtPK$$ U