def process_request(self, req): req.perm.require('PACKAGE_REPOSITORY_VIEW') name = req.args.get('name') ver = req.args.get('version') id = req.args.get('id') filename = req.args.get('filename') if name is None: self._send_json(req, self.packages) package = self.packages[name] if package is None: raise HTTPNotFound() if ver is None: self._send_json(req, package) version = package['versions'].get(ver) if version is None: raise HTTPNotFound() if filename is None: self._send_json(req, version) file = PackageRepositoryFile.select_by_id(self.env, id) if file is None or file.filename != filename: raise HTTPNotFound() file_path = os.path.join(self.packages_path, file.filename) req.send_header('Content-Disposition', 'attachment') req.send_file(file_path, 'application/octet-stream')
def process_request(self, req): if req.is_xhr and req.method == 'POST' and 'save_prefs' in req.args: self._do_save_xhr(req) panels, providers = self._get_panels(req) if not panels: raise HTTPNotFound(_("No preference panels available")) panels = [] child_panels = {} providers = {} for provider in self.panel_providers: for panel in provider.get_preference_panels(req) or []: if len(panel) == 3: name, label, parent = panel child_panels.setdefault(parent, []).append((name, label)) else: name = panel[0] panels.append(panel) providers[name] = provider panels = sorted(panels) panel_id = req.args.get('panel_id') if panel_id is None: panel_id = panels[1][0] \ if len(panels) > 1 and panels[0][0] == 'advanced' \ else panels[0][0] chosen_provider = providers.get(panel_id) if not chosen_provider: raise HTTPNotFound(_("Unknown preference panel '%(panel)s'", panel=panel_id)) session_data = { 'session': req.session, 'settings': {'session': req.session, # Compat: remove in 1.3.1 'session_id': req.session.sid}, } # Render child preference panels. chrome = Chrome(self.env) children = [] if child_panels.get(panel_id): for name, label in child_panels[panel_id]: ctemplate, cdata = provider.render_preference_panel(req, name) cdata.update(session_data) rendered = chrome.render_template(req, ctemplate, cdata, fragment=True) children.append((name, label, rendered)) template, data = \ chosen_provider.render_preference_panel(req, panel_id) data.update(session_data) data.update({ 'active_panel': panel_id, 'panels': panels, 'children': children, }) add_stylesheet(req, 'common/css/prefs.css') return template, data, None
def process_request(self, req): panels, providers = self._get_panels(req) if not panels: raise HTTPNotFound(_("No administration panels available")) def _panel_order(p1, p2): if p1[::2] == ('general', 'basics'): return -1 elif p2[::2] == ('general', 'basics'): return 1 elif p1[0] == 'general': if p2[0] == 'general': return cmp(p1[1:], p2[1:]) return -1 elif p2[0] == 'general': if p1[0] == 'general': return cmp(p1[1:], p2[1:]) return 1 return cmp(p1, p2) panels.sort(_panel_order) cat_id = req.args.get('cat_id') or panels[0][0] panel_id = req.args.get('panel_id') path_info = req.args.get('path_info') if not panel_id: try: panel_id = \ filter(lambda panel: panel[0] == cat_id, panels)[0][2] except IndexError: raise HTTPNotFound(_("Unknown administration panel")) provider = providers.get((cat_id, panel_id)) if not provider: raise HTTPNotFound(_("Unknown administration panel")) template, data = \ provider.render_admin_panel(req, cat_id, panel_id, path_info) data.update({ 'active_cat': cat_id, 'active_panel': panel_id, 'panel_href': partial(req.href, 'admin', cat_id, panel_id), 'panels': [{ 'category': { 'id': panel[0], 'label': panel[1] }, 'panel': { 'id': panel[2], 'label': panel[3] } } for panel in panels] }) add_stylesheet(req, 'common/css/admin.css') return template, data, None
def process_request(self, req): panels, providers = self._get_panels(req) if not panels: raise HTTPNotFound(_("No administration panels available")) def _panel_order(panel): items = panel[::2] return items[0] != 'general', items != ('general', 'basics'), items panels.sort(key=_panel_order) cat_id = req.args.get('cat_id') or panels[0][0] panel_id = req.args.get('panel_id') path_info = req.args.get('path_info') if not panel_id: try: panel_id = \ filter(lambda panel: panel[0] == cat_id, panels)[0][2] except IndexError: raise HTTPNotFound(_("Unknown administration panel")) provider = providers.get((cat_id, panel_id)) if not provider: raise HTTPNotFound(_("Unknown administration panel")) resp = provider.render_admin_panel(req, cat_id, panel_id, path_info) template, data = resp[:2] data.update({ 'active_cat': cat_id, 'active_panel': panel_id, 'panel_href': partial(req.href, 'admin', cat_id, panel_id), 'panels': itertools.groupby([{ 'category': { 'id': panel[0], 'label': panel[1] }, 'panel': { 'id': panel[2], 'label': panel[3] } } for panel in panels], lambda k: k['category']), }) add_stylesheet(req, 'common/css/admin.css') return resp
def process_request(self, req): style = req.args['style'] try: style_cls = get_style_by_name(style) except ValueError as e: raise HTTPNotFound(e) parts = style_cls.__module__.split('.') filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py') mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz) last_modified = http_date(mtime) if last_modified == req.get_header('If-Modified-Since'): req.send_response(304) req.end_headers() return formatter = HtmlFormatter(style=style_cls) content = u'\n\n'.join([ formatter.get_style_defs('div.code pre'), formatter.get_style_defs('table.code td') ]).encode('utf-8') req.send_response(200) req.send_header('Content-Type', 'text/css; charset=utf-8') req.send_header('Last-Modified', last_modified) req.send_header('Content-Length', len(content)) req.write(content)
def _render_project(self, req, project): if project not in self.projects: raise HTTPNotFound() data = { 'packages': self.projects[project]['packages'], } return 'packagerepository_py_project.html', data, None
def handle_attachment(self, req, path): path = path[len('attachments'):].strip('/') dir = resource_filename('tracwatchlist', 'manuals/attachments') filename = os.path.join(dir, path) if os.path.isfile(filename): req.send_file(filename) else: raise HTTPNotFound(path)
def process_request(self, req): data = {} path_info = req.path_info[13:] if path_info.startswith('screenshot/'): return self._send_screenshot(req, data, path_info[11:]) raise HTTPNotFound("The requested URL was not found on this server")
def process_request(self, req): req.perm.require('TRAC_DEVELOP') modname, attrname = str(req.args['name']).split(':') try: module = sys.modules[modname] obj = getattr(module, attrname) except (KeyError, AttributeError), e: raise HTTPNotFound(e)
def _send_screenshot(self, req, data, name): if name not in self.system.info: raise HTTPNotFound("Invalid theme name '%s'", name) theme = self.system.info[name] if 'screenshot' in theme: img = resource_string(theme['module'], theme['screenshot']) else: img = resource_string(__name__, 'htdocs/no_screenshot.png') req.send(img, 'image/png')
def process_request(self, req): data = {} path_info = req.path_info[13:] if path_info.startswith('screenshot/'): return self._send_screenshot(req, data, path_info[11:]) elif path_info == 'theme.css': req.send_file(os.path.join(self.env.path, 'htdocs', 'theme.css'), 'text/css') raise HTTPNotFound("The requested URL was not found on this server")
def process_request(self, req): """Anticipate permission error to hijack admin panel dispatching process in product context if `TRAC_ADMIN` expectations are not met. """ # TODO: Verify `isinstance(self.env, ProductEnvironment)` once again ? cat_id = req.args.get('cat_id') panel_id = req.args.get('panel_id') if self._check_panel(cat_id, panel_id): with sudo(req): return self.global_process_request(req) else: raise HTTPNotFound(_('Unknown administration panel'))
def _do_PUT(self, req): subscription = Subscription.for_request(self.env, req) if subscription is None: raise HTTPNotFound('Subscription to /%s%s for %s not found', req.args.get('realm'), req.args.get('path'), req.authname) content = req.read() if len(content) > 0: data = json.loads(content) subscription.notify = data['notify'] subscription.update() req.send(json.dumps(subscription, cls=SubscriptionJSONEncoder), 'application/json')
def process_request(self, req): """process request handler""" req.perm.require('PRODUCT_VIEW') pid = req.args.get('productid', None) if pid: req.perm('product', pid).require('PRODUCT_VIEW') try: product = Product(self.env, {'prefix': pid}) except ResourceNotFound: product = Product(self.env) path_info = req.args.get('pathinfo') if path_info and path_info != '/': if not product._exists: # bh:ticket:561 - Display product list and warning message if pid: add_warning(req, _("Product %(pid)s not found", pid=pid)) return self._render_list(req) else: raise HTTPNotFound( _('Unable to render product page. Wrong setup?')) if pid: add_link(req, 'up', req.href.products(), _('Products')) action = req.args.get('action', 'view') if req.method == 'POST': if 'cancel' in req.args: req.redirect(req.href.products(product.prefix)) elif action == 'edit': return self._do_save(req, product) elif action == 'delete': raise TracError(_('Product removal is not allowed!')) elif action in ('new', 'edit'): return self._render_editor(req, product) elif action == 'delete': raise TracError(_('Product removal is not allowed!')) if not product._exists: if pid: # bh:ticket:561 - Display product list and warning message add_warning(req, _("Product %(pid)s not found", pid=pid)) return self._render_list(req) data = { 'product': product, 'context': web_context(req, product.resource) } return 'product_view.html', data, None
def process_request(self, req): if req.environ.get('wsgi.multiprocess'): raise TracError('Dozer middlewar is not usable in a multi-process environment') path_info = req.path_info[17:] if '/' in path_info: path_info = path_info[:path_info.find('/')] if not path_info: path_info = 'index' method = getattr(self, path_info, None) if method is None: raise HTTPNotFound('Nothing could be found to match %s' % path_info) if not getattr(method, 'exposed', False): raise HTTPForbidden('Access to %s is forbidden' % path_info) add_stylesheet(req, 'dozer/main.css') return method(req)
def process_request(self, req): prefix = req.args['prefix'] filename = req.args['filename'] dirs = [] for provider in self.template_providers: for dir in [os.path.normpath(dir[1]) for dir in provider.get_htdocs_dirs() if dir[0] == prefix]: dirs.append(dir) path = os.path.normpath(os.path.join(dir, filename)) assert os.path.commonprefix([dir, path]) == dir if os.path.isfile(path): req.send_file(path, mimeview.get_mimetype(path)) self.log.warning('File %s not found in any of %s', filename, dirs) raise HTTPNotFound(u'Fichier %s non trouvé', filename)
def process_request(self, req): try: if req.path_info != '/wikicss.css': raise Exception ("Unsupported path requested!") if not self.wikipage: raise Exception ("WikiCss: Wiki page not configured.") wiki = WikiPage(self.env, self.wikipage) if not wiki.exists: raise Exception("WikiCss: Configured wiki page '%s' doesn't exits." % self.wikipage) req.send( wiki.text.encode("utf-8"), content_type='text/css', status=200) except RequestDone: pass except Exception, e: raise HTTPNotFound(e, path=req.path_info)
def pre_process_request(self, req, handler): """pre process request filter""" pid = None match = PRODUCT_RE.match(req.path_info) if match: dispatcher = self.env[RequestDispatcher] if dispatcher is None: raise TracError('Unable to load RequestDispatcher.') pid = match.group('pid') if pid: products = Product.select(self.env, where={'prefix': pid}) if pid and len(products) == 1: req.args['productid'] = pid req.args['product'] = products[0].name if handler is self and match.group('pathinfo') not in ('', '/'): # select a new handler environ = req.environ.copy() pathinfo = environ['PATH_INFO'].split('/') pathinfo = '/'.join(pathinfo[:1] + pathinfo[3:]) environ['PATH_INFO'] = pathinfo newreq = Request(environ, lambda *args, **kwds: None) new_handler = None for hndlr in dispatcher.handlers: if hndlr is not self and hndlr.match_request(newreq): new_handler = hndlr req.args.update(newreq.args) break if new_handler is None: if req.path_info.endswith('/'): target = req.path_info.rstrip('/').encode('utf-8') if req.query_string: target += '?' + req.query_string req.redirect(req.href + target, permanent=True) raise HTTPNotFound('No handler matched request to %s', req.path_info) handler = new_handler else: raise ResourceNotFound( _("Product %(id)s does not exist.", id=pid), _("Invalid product id")) return handler
def process_request(self, req): xhr = req.get_header('X-Requested-With') == 'XMLHttpRequest' if xhr and req.method == 'POST' and 'save_prefs' in req.args: self._do_save_xhr(req) panel_id = req.args.get('panel_id') panels = [] child_panels = [] chosen_provider = None chrome = Chrome(self.env) for provider in self.panel_providers: for panel in provider.get_preference_panels(req) or []: if len(panel) == 3: name, label, parent = panel if parent == panel_id: template, data = \ provider.render_preference_panel(req, name) child_panels.append( (name, label, chrome.render_template(req, template, data, fragment=True))) else: name, label = panel if name == panel_id or None: chosen_provider = provider panels.append(panel) if not chosen_provider: raise HTTPNotFound( _("Unknown preference panel '%(panel)s'", panel=panel_id)) template, data = chosen_provider.render_preference_panel(req, panel_id) data.update({ 'active_panel': panel_id, 'panels': panels, 'child_panels': child_panels }) add_stylesheet(req, 'common/css/prefs.css') return template, data, None
def process_request(self, req): req.perm.require('PACKAGE_REPOSITORY_VIEW') project = req.args.get('project') id = req.args.get('id') filename = req.args.get('filename') if project is None: return self._render_index(req) if id is None: return self._render_project(req, project) file = PackageRepositoryFile.select_by_id(self.env, id) if file is None or file.filename != filename: raise HTTPNotFound() file_path = os.path.join(self.packages_path, file.filename) req.send_header('Content-Disposition', 'attachment') req.send_file(file_path, 'application/octet-stream')
def process_request(self, req): path = req.path_info[len("/watchlist/manual"):].strip('/') if path.startswith('attachments'): return self.handle_attachment(req, path) language = path if not language: language = req.session.get('language', 'en-US') # Try to find a suitable language if no manual exists # in the requested one. if language not in self.manuals: # Try to find a main language, # e.g. 'xy' instead of 'xy-ZV' l = language.split('-')[0] language = 'en-US' # fallback if no other is found if l in self.manuals: language = l else: # Prefer 'en-US' before any other English dialect if l == 'en' and 'en-US' in self.manuals: language = 'en-US' else: # If there is none try to find # any other 'xy-*' language l += '-' for lang in sorted(self.manuals.keys()): if lang.startswith(l): language = lang break req.redirect(req.href.watchlist('manual', language)) try: f = open(self.manuals[language], 'r') text = to_unicode(f.read()) except Exception as e: raise HTTPNotFound(e) wldict = dict(format_text=lambda text: format_to_html( self.env, Context.from_request(req), text), text=text) return ("watchlist_manual.html", wldict, "text/html")
def process_request(self, req): prefix = req.args['prefix'] filename = req.args['filename'] dirs = [] for provider in self.template_providers: for dir in [ os.path.normpath(dir[1]) for dir in provider.get_htdocs_dirs() or [] if dir[0] == prefix and dir[1] ]: dirs.append(dir) path = os.path.normpath(os.path.join(dir, filename)) if os.path.commonprefix([dir, path]) != dir: raise TracError( _("Invalid chrome path %(path)s.", path=filename)) elif os.path.isfile(path): req.send_file(path, get_mimetype(path)) self.log.warning('File %s not found in any of %s', filename, dirs) raise HTTPNotFound('File %s not found', filename)
def process_request(self, req): xhr = req.get_header('X-Requested-With') == 'XMLHttpRequest' if xhr and req.method == 'POST' and 'save_prefs' in req.args: self._do_save_xhr(req) panel_id = req.args.get('panel_id') panels = [] chosen_provider = None for provider in self.panel_providers: for name, label in provider.get_preference_panels(req) or []: if name == panel_id or None: chosen_provider = provider panels.append((name, label)) if not chosen_provider: raise HTTPNotFound(_("Unknown preference panel")) template, data = chosen_provider.render_preference_panel(req, panel_id) data.update({'active_panel': panel_id, 'panels': panels}) add_stylesheet(req, 'common/css/prefs.css') return template, data, None
def dispatch(self, req): """Find a registered handler that matches the request and let it process it. In addition, this method initializes the data dictionary passed to the the template and adds the web site chrome. """ self.log.debug('Dispatching %r', req) chrome = Chrome(self.env) # Setup request callbacks for lazily-evaluated properties req.callbacks.update({ 'authname': self.authenticate, 'chrome': chrome.prepare_request, 'perm': self._get_perm, 'session': self._get_session, 'locale': self._get_locale, 'lc_time': self._get_lc_time, 'tz': self._get_timezone, 'form_token': self._get_form_token, 'use_xsendfile': self._get_use_xsendfile, 'xsendfile_header': self._get_xsendfile_header, }) try: try: # Select the component that should handle the request chosen_handler = None try: for handler in self._request_handlers.values(): if handler.match_request(req): chosen_handler = handler break if not chosen_handler and \ (not req.path_info or req.path_info == '/'): chosen_handler = self._get_valid_default_handler(req) # pre-process any incoming request, whether a handler # was found or not self.log.debug("Chosen handler is %s", chosen_handler) chosen_handler = \ self._pre_process_request(req, chosen_handler) except TracError as e: raise HTTPInternalError(e) if not chosen_handler: if req.path_info.endswith('/'): # Strip trailing / and redirect target = unicode_quote(req.path_info.rstrip('/')) if req.query_string: target += '?' + req.query_string req.redirect(req.href + target, permanent=True) raise HTTPNotFound('No handler matched request to %s', req.path_info) req.callbacks['chrome'] = partial(chrome.prepare_request, handler=chosen_handler) # Protect against CSRF attacks: we validate the form token # for all POST requests with a content-type corresponding # to form submissions if req.method == 'POST': ctype = req.get_header('Content-Type') if ctype: ctype, options = cgi.parse_header(ctype) if ctype in ('application/x-www-form-urlencoded', 'multipart/form-data') and \ req.args.get('__FORM_TOKEN') != req.form_token: if self.env.secure_cookies and req.scheme == 'http': msg = _('Secure cookies are enabled, you must ' 'use https to submit forms.') else: msg = _('Do you have cookies enabled?') raise HTTPBadRequest( _('Missing or invalid form token.' ' %(msg)s', msg=msg)) # Process the request and render the template resp = chosen_handler.process_request(req) if resp: if len(resp) == 2: # old Clearsilver template and HDF data self.log.error( "Clearsilver template are no longer " "supported (%s)", resp[0]) raise TracError( _("Clearsilver templates are no longer supported, " "please contact your Trac administrator.")) # Genshi template, data, content_type, method = \ self._post_process_request(req, *resp) if 'hdfdump' in req.args: req.perm.require('TRAC_ADMIN') # debugging helper - no need to render first out = io.BytesIO() pprint(data, out) req.send(out.getvalue(), 'text/plain') self.log.debug("Rendering response from handler") output = chrome.render_template( req, template, data, content_type, method=method, iterable=chrome.use_chunked_encoding) req.send(output, content_type or 'text/html') else: self.log.debug("Empty or no response from handler. " "Entering post_process_request.") self._post_process_request(req) except RequestDone: raise except: # post-process the request in case of errors err = sys.exc_info() try: self._post_process_request(req) except RequestDone: raise except Exception as e: self.log.error( "Exception caught while post-processing" " request: %s", exception_to_unicode(e, traceback=True)) raise err[0], err[1], err[2] except PermissionError as e: raise HTTPForbidden(e) except ResourceNotFound as e: raise HTTPNotFound(e) except TracError as e: raise HTTPInternalError(e)
def dispatch(self, req): """Find a registered handler that matches the request and let it process it. In addition, this method initializes the data dictionary passed to the the template and adds the web site chrome. """ self.log.debug('Dispatching %r', req) chrome = Chrome(self.env) try: # Select the component that should handle the request chosen_handler = None for handler in self._request_handlers.values(): if handler.match_request(req): chosen_handler = handler break if not chosen_handler and req.path_info in ('', '/'): chosen_handler = self._get_valid_default_handler(req) # pre-process any incoming request, whether a handler # was found or not self.log.debug("Chosen handler is %s", chosen_handler) chosen_handler = self._pre_process_request(req, chosen_handler) if not chosen_handler: if req.path_info.endswith('/'): # Strip trailing / and redirect target = unicode_quote(req.path_info.rstrip('/')) if req.query_string: target += '?' + req.query_string req.redirect(req.href + target, permanent=True) raise HTTPNotFound('No handler matched request to %s', req.path_info) req.callbacks['chrome'] = partial(chrome.prepare_request, handler=chosen_handler) # Protect against CSRF attacks: we validate the form token # for all POST requests with a content-type corresponding # to form submissions if req.method == 'POST': ctype = req.get_header('Content-Type') if ctype: ctype, options = cgi.parse_header(ctype) if ctype in ('application/x-www-form-urlencoded', 'multipart/form-data') and \ req.args.get('__FORM_TOKEN') != req.form_token: if self.env.secure_cookies and req.scheme == 'http': msg = _('Secure cookies are enabled, you must ' 'use https to submit forms.') else: msg = _('Do you have cookies enabled?') raise HTTPBadRequest(_('Missing or invalid form token.' ' %(msg)s', msg=msg)) # Process the request and render the template resp = chosen_handler.process_request(req) if resp: template, data, metadata = \ self._post_process_request(req, *resp) if 'hdfdump' in req.args: req.perm.require('TRAC_ADMIN') # debugging helper - no need to render first out = io.BytesIO() pprint({'template': template, 'metadata': metadata, 'data': data}, out) req.send(out.getvalue(), 'text/plain') self.log.debug("Rendering response with template %s", template) metadata.setdefault('iterable', chrome.use_chunked_encoding) content_type = metadata.get('content_type') output = chrome.render_template(req, template, data, metadata) req.send(output, content_type or 'text/html') else: self.log.debug("Empty or no response from handler. " "Entering post_process_request.") self._post_process_request(req) except RequestDone: raise except Exception as e: # post-process the request in case of errors err = sys.exc_info() try: self._post_process_request(req) except RequestDone: raise except TracError as e2: self.log.warning("Exception caught while post-processing" " request: %s", exception_to_unicode(e2)) except Exception as e2: if not (type(e) is type(e2) and e.args == e2.args): self.log.error("Exception caught while post-processing" " request: %s", exception_to_unicode(e2, traceback=True)) if isinstance(e, PermissionError): raise HTTPForbidden(e) if isinstance(e, ResourceNotFound): raise HTTPNotFound(e) if isinstance(e, NotImplementedError): tb = traceback.extract_tb(err[2])[-1] self.log.warning("%s caught from %s:%d in %s: %s", e.__class__.__name__, tb[0], tb[1], tb[2], to_unicode(e) or "(no message)") raise HTTPInternalServerError(TracNotImplementedError(e)) if isinstance(e, TracError): raise HTTPInternalServerError(e) raise err[0], err[1], err[2]
def process_request(self, req): style = req.args['style'] try: style_cls = get_style_by_name(style) except ValueError, e: raise HTTPNotFound(e)
def process_request(self, req): """ Processing the request. """ req.perm('blog').assert_permission('BLOG_VIEW') blog_core = FullBlogCore(self.env) format = req.args.get('format', '').lower() command, pagename, path_items, listing_data = self._parse_path(req) action = req.args.get('action', 'view').lower() try: version = int(req.args.get('version', 0)) except: version = 0 data = {} template = 'fullblog_view.html' data['blog_about'] = BlogPost(self.env, 'about') data['blog_infotext'] = blog_core.get_bloginfotext() blog_month_names = map_month_names( self.env.config.getlist('fullblog', 'month_names')) data['blog_month_names'] = blog_month_names self.env.log.debug( "Blog debug: command=%r, pagename=%r, path_items=%r" % (command, pagename, path_items)) if not command: # Request for just root (display latest) data['blog_post_list'] = [] count = 0 maxcount = self.num_items blog_posts = get_blog_posts(self.env) for post in blog_posts: bp = BlogPost(self.env, post[0], post[1]) if 'BLOG_VIEW' in req.perm(bp.resource): data['blog_post_list'].append(bp) count += 1 if maxcount and count == maxcount: # Only display a certain number on front page (from config) break data['blog_list_title'] = "Recent posts" + \ (len(blog_posts) > maxcount and \ " (max %d) - Browse or Archive for more" % (maxcount,) \ or '') add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') elif command == 'archive': # Requesting the archive page template = 'fullblog_archive.html' data['blog_archive'] = [] for period, period_posts in group_posts_by_month( get_blog_posts(self.env)): allowed_posts = [] for post in period_posts: bp = BlogPost(self.env, post[0], post[1]) if 'BLOG_VIEW' in req.perm(bp.resource): allowed_posts.append(post) if allowed_posts: data['blog_archive'].append((period, allowed_posts)) add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') elif command == 'view' and pagename: # Requesting a specific blog post the_post = BlogPost(self.env, pagename, version) req.perm(the_post.resource).require('BLOG_VIEW') if not the_post.version: raise HTTPNotFound("No blog post named '%s'." % pagename) if req.method == 'POST': # Adding/Previewing a comment # Permission? req.perm(the_post.resource).require('BLOG_COMMENT') comment = BlogComment(self.env, pagename) comment.comment = req.args.get('comment', '') comment.author = (req.authname != 'anonymous' and req.authname) \ or req.args.get('author') comment.time = datetime.datetime.now(utc) warnings = [] if 'cancelcomment' in req.args: req.redirect(req.href.blog(pagename)) elif 'previewcomment' in req.args: warnings.extend( blog_core.create_comment(req, comment, verify_only=True)) elif 'submitcomment' in req.args and not warnings: warnings.extend(blog_core.create_comment(req, comment)) if not warnings: req.redirect( req.href.blog(pagename) + '#comment-' + str(comment.number)) data['blog_comment'] = comment # Push all warnings out to the user. for field, reason in warnings: if field: add_warning(req, "Field '%s': %s" % (field, reason)) else: add_warning(req, reason) data['blog_post'] = the_post context = web_context(req, the_post.resource, absurls=format == 'rss' and True or False) data['context'] = context if format == 'rss': return 'fullblog_post.rss', data, 'application/rss+xml' # Regular web response context = web_context(req, the_post.resource) data['blog_attachments'] = AttachmentModule( self.env).attachment_data(context) # Previous and Next ctxtnav prev, next = blog_core.get_prev_next_posts(req.perm, the_post.name) if prev: add_link(req, 'prev', req.href.blog(prev), prev) if next: add_link(req, 'next', req.href.blog(next), next) if arity(prevnext_nav) == 4: # 0.12 compat following trac:changeset:8597 prevnext_nav(req, 'Previous Post', 'Next Post') else: prevnext_nav(req, 'Post') # RSS feed for post and comments add_link(req, 'alternate', req.href.blog(pagename, format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') elif command in ['create', 'edit']: template = 'fullblog_edit.html' default_pagename = blog_core._get_default_postname(req.authname) the_post = BlogPost(self.env, pagename or default_pagename) warnings = [] if command == 'create' and req.method == 'GET' and not the_post.version: # Support appending query arguments for populating intial fields the_post.update_fields(req.args) if command == 'create' and the_post.version: # Post with name or suggested name already exists if 'BLOG_CREATE' in req.perm and the_post.name == default_pagename \ and not req.method == 'POST': if default_pagename: add_notice( req, "Suggestion for new name already exists " "('%s'). Please make a new name." % the_post.name) elif pagename: warnings.append( ('', "A post named '%s' already exists. Enter new name." % the_post.name)) the_post = BlogPost(self.env, '') if command == 'edit': req.perm(the_post.resource).require( 'BLOG_VIEW') # Starting point if req.method == 'POST': # Create or edit a blog post if 'blog-cancel' in req.args: if req.args.get('action', '') == 'edit': req.redirect(req.href.blog(pagename)) else: req.redirect(req.href.blog()) # Assert permissions if command == 'create': req.perm(Resource('blog', None)).require('BLOG_CREATE') elif command == 'edit': if the_post.author == req.authname: req.perm(the_post.resource).require('BLOG_MODIFY_OWN') else: req.perm(the_post.resource).require('BLOG_MODIFY_ALL') # Check input orig_author = the_post.author if not the_post.update_fields(req.args): warnings.append(('', "None of the fields have changed.")) version_comment = req.args.get('new_version_comment', '') if 'blog-preview' in req.args: warnings.extend( blog_core.create_post(req, the_post, req.authname, version_comment, verify_only=True)) elif 'blog-save' in req.args and not warnings: warnings.extend( blog_core.create_post(req, the_post, req.authname, version_comment)) if not warnings: req.redirect(req.href.blog(the_post.name)) context = web_context(req, the_post.resource) data['context'] = context data['blog_attachments'] = AttachmentModule( self.env).attachment_data(context) data['blog_action'] = 'preview' data['blog_version_comment'] = version_comment if (orig_author and orig_author != the_post.author) and ( not 'BLOG_MODIFY_ALL' in req.perm(the_post.resource)): add_notice(req, "If you change the author you cannot " \ "edit the post again due to restricted permissions.") data['blog_orig_author'] = orig_author for field, reason in warnings: if field: add_warning(req, "Field '%s': %s" % (field, reason)) else: add_warning(req, reason) data['blog_edit'] = the_post elif command == 'delete': bp = BlogPost(self.env, pagename) req.perm(bp.resource).require('BLOG_DELETE') if 'blog-cancel' in req.args: req.redirect(req.href.blog(pagename)) comment = int(req.args.get('comment', '0')) warnings = [] if comment: # Deleting a specific comment bc = BlogComment(self.env, pagename, comment) if not bc.number: raise TracError( "Cannot delete. Blog post name and/or comment number missing." ) if req.method == 'POST' and comment and pagename: warnings.extend(blog_core.delete_comment(bc)) if not warnings: add_notice(req, "Blog comment %d deleted." % comment) req.redirect(req.href.blog(pagename)) template = 'fullblog_delete.html' data['blog_comment'] = bc else: # Delete a version of a blog post or all versions # with comments and attachments if only version. if not bp.version: raise TracError( "Cannot delete. Blog post '%s' does not exist." % (bp.name)) version = int(req.args.get('version', '0')) if req.method == 'POST': if 'blog-version-delete' in req.args: if bp.version != version: raise TracError( "Cannot delete. Can only delete most recent version." ) warnings.extend( blog_core.delete_post(bp, version=bp.versions[-1])) elif 'blog-delete' in req.args: version = 0 warnings.extend( blog_core.delete_post(bp, version=version)) if not warnings: if version > 1: add_notice( req, "Blog post '%s' version %d deleted." % (pagename, version)) req.redirect(req.href.blog(pagename)) else: add_notice(req, "Blog post '%s' deleted." % pagename) req.redirect(req.href.blog()) template = 'fullblog_delete.html' data['blog_post'] = bp for field, reason in warnings: if field: add_warning(req, "Field '%s': %s" % (field, reason)) else: add_warning(req, reason) elif command.startswith('listing-'): # 2007/10 or category/something or author/theuser title = category = author = '' from_dt = to_dt = None if command == 'listing-month': from_dt = listing_data['from_dt'] to_dt = listing_data['to_dt'] title = "Posts for the month of %s %d" % ( blog_month_names[from_dt.month - 1], from_dt.year) add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') elif command == 'listing-category': category = listing_data['category'] if category: title = "Posts in category %s" % category add_link(req, 'alternate', req.href.blog('category', category, format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') elif command == 'listing-author': author = listing_data['author'] if author: title = "Posts by author %s" % author add_link(req, 'alternate', req.href.blog('author', author, format='rss'), 'RSS Feed', 'application/rss+xml', 'rss') if not (author or category or (from_dt and to_dt)): raise HTTPNotFound("Not a valid path for viewing blog posts.") blog_posts = [] for post in get_blog_posts(self.env, category=category, author=author, from_dt=from_dt, to_dt=to_dt): bp = BlogPost(self.env, post[0], post[1]) if 'BLOG_VIEW' in req.perm(bp.resource): blog_posts.append(bp) data['blog_post_list'] = blog_posts data['blog_list_title'] = title else: raise HTTPNotFound("Not a valid blog path.") if (not command or command.startswith('listing-')) and format == 'rss': data['context'] = web_context(req, absurls=True) data['blog_num_items'] = self.num_items return 'fullblog.rss', data, 'application/rss+xml' data['blog_months'], data['blog_authors'], data['blog_categories'], \ data['blog_total'] = \ blog_core.get_months_authors_categories( user=req.authname, perm=req.perm) if 'BLOG_CREATE' in req.perm('blog'): add_ctxtnav(req, 'New Post', href=req.href.blog('create'), title="Create new Blog Post") add_stylesheet(req, 'tracfullblog/css/fullblog.css') add_stylesheet(req, 'common/css/code.css') data['blog_personal_blog'] = self.env.config.getbool( 'fullblog', 'personal_blog') data['blog_archive_rss_icon'] = self.all_rss_icons \ or self.archive_rss_icon data['blog_all_rss_icons'] = self.all_rss_icons return (template, data, None)
# rereads the settings del req.session['watchlist_display_notify_navitems'] except: pass req.redirect(req.href('watchlist')) elif action == "defaultsettings": # Only execute if sent using the watchlist preferences form if onwatchlistpage and req.method == 'POST': self._delete_user_settings(req.authname) req.redirect(req.href('watchlist')) redirectback_notify = options['stay_at_resource_notify'] and not \ onwatchlistpage and not async if action == "notifyon": if not self.res_exists(realm, resid): raise HTTPNotFound(t_("Page %(name)s not found", name=resid)) elif self.wsub and options['notifications']: self.set_notify(req, realm, resid) db.commit() if redirectback_notify: if options['show_messages_on_resource_page']: req.session['watchlist_notify_message'] = _(""" You are now receiving change notifications about this resource. """) req.redirect(req.href(realm, resid)) if async: req.send("", 'text/plain', 200) else: req.redirect(req.href('watchlist')) elif action == "notifyoff":
def process_request(self, req): """Processes requests to the '/watchlist' path.""" user = to_unicode(req.authname) # Reject anonymous users if not user or user == 'anonymous': # TRANSLATOR: Link part of # "Please %(log_in)s to view or change your watchlist" log_in = tag.a(_("log in"), href=req.href('login')) if tag_ == None: # For Trac 0.11 raise HTTPNotFound( tag("Please ", log_in, " to view or change your watchlist")) else: # For Trac 0.12 raise HTTPNotFound( tag_("Please %(log_in)s to view or change your watchlist", log_in=log_in)) # Get and format request arguments realm = to_unicode(req.args.get('realm', u'')) resid = ensure_string(req.args.get('resid', u'')).strip() action = req.args.get('action', 'view') async = req.args.get('async', 'false') == 'true' # Handle AJAX search early to speed up things if action == "search": """AJAX search request. At the moment only used to get list of all not watched resources.""" handler = self.realm_handler[realm] query = to_unicode(req.args.get('q', u'')).strip() group = to_unicode(req.args.get('group', u'notwatched')) if not query: req.send('', 'text/plain', 200) if group == 'notwatched': result = list( handler.unwatched_resources(realm, query, user, self, fuzzy=1)) else: result = list( handler.watched_resources(realm, query, user, self, fuzzy=1)) result.sort(cmp=handler.get_sort_cmp(realm), key=handler.get_sort_key(realm)) req.send( unicode(u'\n'.join(result) + u'\n').encode("utf-8"), 'text/plain', 200) # DB cursor db = self.env.get_db_cnx() cursor = db.cursor() wldict = dict() for k, v in req.args.iteritems(): try: wldict[str(k)] = v except: pass wldict['action'] = action onwatchlistpage = req.environ.get('HTTP_REFERER', '').find( req.href.watchlist()) != -1 settings = self.get_settings(user) options = settings['booloptions'] self.options = options # Needed here to get updated settings if action == "save": newoptions = req.args.get('booloptions', []) for k in settings['booloptions'].keys(): settings['booloptions'][k] = k in newoptions for realm in self.realms: settings[realm + '_fields'] = req.args.get( realm + '_fields', '').split(',') for l in settings['listoptions']: if l in req.args: settings['listoptions'][l] = [ e.strip() for e in req.args.get(l).split(',') ] self._save_user_settings(req.authname, settings) # Clear session cache for nav items try: # Clear session cache for nav items, so that the post processor # rereads the settings del req.session['watchlist_display_notify_navitems'] except: pass req.redirect(req.href('watchlist')) elif action == "defaultsettings": # Only execute if sent using the watchlist preferences form if onwatchlistpage and req.method == 'POST': self._delete_user_settings(req.authname) req.redirect(req.href('watchlist')) redirectback_notify = options['stay_at_resource_notify'] and not \ onwatchlistpage and not async
def process_request(self, req): """ Processing the request. """ req.perm('qa').assert_permission('QA_VIEW') qa_core = QaCore(self.env) entity, action, pagename, path_items = self._parse_path(req) data = {} template = None #data['qa_infotext'] = qa_core.get_qainfotext() self.env.log.debug( "QA debug: entity=%r, action=%r, pagename=%r, path_items=%r" % (entity, action, pagename, path_items)) if not entity: entity = 'report' action = 'result' controller_dict = { 'testplan': 'TestPlanController', 'testrun': 'TestRunController', 'testcase': 'TestCaseController', 'testsuite': 'TestSuiteController', 'execution': 'ExecutionController', 'assignment': 'AssignmentController', 'report': 'ReportController' } if globals()[controller_dict[entity]]: controller = globals()[controller_dict[entity]](self.env, req) if hasattr(controller, action): action_method = getattr(controller, action) template, data = action_method(pagename) else: raise HTTPNotFound("Not a valid QA path.") else: raise HTTPNotFound("Not a valid QA path.") if 'QA_CREATE' in req.perm('qa'): add_ctxtnav(req, 'Test Plans', href=req.href.qa('/testplan/index'), title="Test Plans") add_ctxtnav(req, 'Test Runs', href=req.href.qa('/testrun/index'), title="Test Runs") add_ctxtnav(req, 'Test Suites', href=req.href.qa('/testsuite/index'), title="Test Suites") add_ctxtnav(req, 'Test Cases', href=req.href.qa('/testcase/index'), title="Test Cases") add_ctxtnav(req, 'Reports', href=req.href.qa('/report/result'), title="Reports") add_stylesheet(req, 'tracqa/css/tracqa.css') add_stylesheet(req, 'common/css/admin.css') add_stylesheet(req, 'common/css/report.css') return (template, data, None)