def group_form(self): if IMeeting.providedBy(self.context): self.response['title'] = _(u"Edit permissions") else: self.response['title'] = _(u"Root permissions") post = self.request.POST if 'cancel' in post: url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('PermissionsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=('save', 'cancel')) self.api.register_form_resources(form) if 'save' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Set permissions self.context.set_security(appstruct['userids_and_groups']) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def add_permission(self): if ISiteRoot.providedBy(self.context): self.response['title'] = _(u"Add permission") post = self.request.POST if 'cancel' in post: url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('SinglePermissionSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) if IMeeting.providedBy(self.context): self.response['tabs'] = self.api.render_single_view_component( self.context, self.request, 'tabs', 'manage_tickets') if 'add' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Set permissions self.context.set_groups(appstruct['userid'], appstruct['groups'], event=True) msg = _(u"Added permssion for user ${userid}", mapping={'userid': appstruct['userid']}) self.api.flash_messages.add(msg) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def view_url(context, request, key, default_name, **extra_qs): configured = request.registry.settings.get('cartouche.%s' % key) if configured is None: if extra_qs: return resource_url(context, request, default_name, query=extra_qs) return resource_url(context, request, default_name) return _fixup_url(context, request, configured, **extra_qs)
def forbidden(context, request): site = find_site(context) environ = request.environ referrer = environ.get('HTTP_REFERER', '') if 'repoze.who.identity' in environ: # the user is authenticated but he is not allowed to access this # resource api = TemplateAPI(context, request, 'Forbidden') response = render_to_response( 'templates/forbidden.pt', dict(api=api, login_form_url = resource_url(site, request, 'login.html'), homepage_url = resource_url(site, request)), request=request, ) response.status = '403 Forbidden' return response elif '/login.html' in referrer: url = request.url # this request came from a user submitting the login form login_url = resource_url(site, request, 'login.html', query={'reason':'Bad username or password', 'came_from':url}) return HTTPFound(location=login_url) else: # the user is not authenticated and did not come in as a result of # submitting the login form url = request.url query = {'came_from':url} while url.endswith('/'): url = url[:-1] if url != request.application_url: # if request isnt for homepage query['reason'] = 'Not logged in' login_url = resource_url(site, request, 'login.html', query=query) return HTTPFound(location=login_url)
def pastebin_view(context, request): params = request.params author_name = utils.preferred_author(context, request) language = u'' paste = u'' message = u'' pastebin_url = resource_url(context, request) can_manage = has_permission('manage', context, request) if params.has_key('form.submitted'): if params.get('text'): # trap spambots return HTTPFound(location=resource_url(context, request)) paste = params.get('paste_', '') author_name = params.get('author_name_', '') language = params.get('language_', '') schema = PasteAddSchema() message = None try: schema.to_python(request.params) except formencode.validators.Invalid, why: message = str(why) else: pobj = PasteEntry(author_name, paste, language) pasteid = context.add_item(pobj) url = '%s%s' % (pastebin_url, pasteid) response = HTTPFound(location=url) response.set_cookie(utils.COOKIE_AUTHOR, author_name, max_age=864000) response.set_cookie(utils.COOKIE_LANGUAGE, language) return response
def pastebin_manage_view(context, request): params = request.params message = params.get('message', u'') if params.has_key('form.submitted'): form = marshal(request.environ, request.body_file) checkboxes = form.get('delete', []) for checkbox in checkboxes: del context[checkbox] message = '%s pastes deleted' % len(checkboxes) url = resource_url(context, request, 'manage', query={'message':message}) response = HTTPFound(location=url) response.headers['Location'] = url return response pastebin_url = resource_url(context, request) pastes = utils.get_pastes(context, request, sys.maxint) return dict( api = utils.API(context, request), pastes = pastes, message = message, pastebin_url = pastebin_url, )
def add(self): if 'cancel' in self.request.POST: url = resource_url(self.context, self.request) return HTTPFound(location=url) type = self.request.GET['type'] obj = createContent(type) schema = createSchema(obj.schemas['add']).bind(context = self.context, request = self.request) form = Form(schema, buttons=('save', 'cancel',)) self.register_form_resources(form) if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response obj.set_field_appstruct(appstruct) name = obj.suggest_name(self.context) self.context[name] = obj url = resource_url(self.context, self.request) return HTTPFound(location=url)
def add_form(self): post = self.request.POST if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('AddUserSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) if 'add' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Userid and name should be consistent name = appstruct['userid'] del appstruct['userid'] #creators takes care of setting the role owner as well as adding it to creators attr. obj = createContent('User', creators=[name], **appstruct) self.context[name] = obj self.api.flash_messages.add(_(u"Successfully added")) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def blogview(context, request): system_catalog = find_catalog(context, 'system') blog_catalog = find_catalog(context, 'blog') content_type = system_catalog['content_type'] query = content_type.eq('Blog Entry') query_result = query.execute().sort(blog_catalog['pubdate'], reverse=True) blogentries = [] for blogentry in query_result: blogentries.append({ 'url': resource_url(blogentry, request), 'title': blogentry.title, 'body': _getentrybody(blogentry.format, blogentry.entry), 'pubdate': blogentry.pubdate, 'attachments': [{ 'name': a.__name__, 'url': resource_url(a, request, 'download') } for a in blogentry['attachments'].values()], 'numcomments': len(blogentry['comments'].values()), }) return dict(blogentries=blogentries)
def lock_info_for_view(context, request, from_time=None): """return a structure suitable for displaying in a template""" if is_locked(context, from_time): lock = lock_info(context) userid = lock['userid'] profiles = find_profiles(context) profile = profiles.get(userid, None) if profile is not None: return dict( is_locked=True, url=resource_url(profile, request), name='%s %s' % (profile.firstname, profile.lastname), email=profile.email, ) else: return dict( is_locked=True, url=resource_url(profiles, request), name='Unknown', email='', ) else: return dict( is_locked=False, url=None, name=None, email=None, )
def get_previous_next(context, request, viewname=''): # Reference Manual sections have inter-item navigation, which # means (sigh) that files and pages do as well. # Only works on resources whose parents are orderable parent = context.__parent__ ordering = getattr(parent, 'ordering', None) if ordering is None: return None, None # Be a chicken and sync ordering.sync(parent.keys()) # Find the prev/next names, then flatten some info about them for # the ZPT current_name = context.__name__ previous = parent.get(ordering.previous_name(current_name)) next = parent.get(ordering.next_name(current_name)) if previous: if _find_view(previous, request, viewname) is not None: href = resource_url(previous, request, viewname) else: href = resource_url(previous, request) previous = {'title': previous.title, 'href': href} if next: if _find_view(next, request, viewname) is not None: href = resource_url(next, request, viewname) else: href = resource_url(next, request) next = {'title': next.title, 'href': href} return previous, next
def delete_node(self): """ Delete node view. Renders either a view to delete the current node or handle the deletion of the current node and get back to the default view of the node. :result: Either a redirect response or a dictionary passed to the template for rendering. :rtype: pyramid.httpexceptions.HTTPFound or dict """ action = self.request.POST.get(u'delete', None) if action is not None: parent = self.context.__parent__ if action == u'delete': location = resource_url(parent, self.request) self.flash( _(u'${title} was deleted.', mapping=dict(title=self.context.title)), u'success') del parent[self.context.name] else: location = resource_url(self.context, self.request) return HTTPFound(location=location) return {}
def error_monitor_subsystem_view(context, request): error_monitor_dir = get_setting(context, 'error_monitor_dir', '') subsystems = get_setting(context, 'error_monitor_subsystems') subsystem = request.params.get('subsystem', None) if subsystem is None or subsystem not in subsystems: raise NotFound() back_url = resource_url(context, request, 'error_monitor.html') if 'clear' in request.params: path = os.path.join(error_monitor_dir, subsystem) os.remove(path) return HTTPFound(location=back_url) clear_url = resource_url(context, request, request.view_name, query={'clear': '1', 'subsystem': subsystem}) entries = _get_error_monitor_state(error_monitor_dir, subsystem) return dict( api=AdminTemplateAPI(context, request), menu=_menu_macro(), subsystem=subsystem, entries=entries, back_url=back_url, clear_url=clear_url, )
def calendar_setup_view(context, request): default_category_name = ICalendarCategory.getTaggedValue('default_name') categories = filter(lambda x: x.__name__ != default_category_name, _get_calendar_categories(context)) default_layer_name = ICalendarLayer.getTaggedValue('default_name') layers = filter(lambda x: x.__name__ != default_layer_name, _get_calendar_layers(context)) fielderrors = {} fielderrors_target = None page_title = 'Calendar Setup' api = TemplateAPI(context, request, page_title) return render_to_response( 'templates/calendar_setup.pt', dict(back_to_calendar_url=resource_url(context, request), categories_url=resource_url(context, request, 'categories.html'), layers_url=resource_url(context, request, 'layers.html'), formfields=api.formfields, fielderrors=fielderrors, fielderrors_target = fielderrors_target, api=api, editable_categories = categories, editable_layers = layers, all_categories = _get_all_calendar_categories(context, request), colors = _COLORS), request = request, )
def chatter_user_info(context, request, userid=None): chatter = find_chatter(context) chatter_url = resource_url(chatter, request) profiles = find_profiles(context) if userid is None: userid = request.GET.get('userid') if userid is None: userid = authenticated_userid(request) profile = profiles.get(userid) profile_url = profile and resource_url(profile, request) or None photo = profile and profile.get('photo') or None if photo is not None: photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE) else: photo_url = get_static_url(request) + "/images/defaultUser.gif" posts = sum(1 for p in chatter.recentWithCreators(*[userid])) following = sum(1 for u in chatter.listFollowed(userid)) followers = sum(1 for u in chatter.listFollowing(userid)) return { 'creator': getattr(profile, 'title', 'anonymous'), 'creator_url': '%s%s' % (chatter_url, userid), 'creator_profile_url': profile_url, 'creator_image_url': photo_url, 'creator_userid': userid, 'chatter_url': chatter_url, 'posts': posts, 'following': following, 'followers': followers }
def lock_info_for_view(context, request, from_time=None): """return a structure suitable for displaying in a template""" if is_locked(context, from_time): lock = lock_info(context) userid = lock['userid'] profiles = find_profiles(context) profile = profiles.get(userid, None) if profile is not None: return dict( is_locked = True, url = resource_url(profile, request), name = '%s %s' % (profile.firstname, profile.lastname), email = profile.email, ) else: return dict( is_locked = True, url = resource_url(profiles, request), name = 'Unknown', email = '', ) else: return dict( is_locked = False, url = None, name = None, email = None, )
def delete_node(self): """ Delete node view. Renders either a view to delete the current node or handle the deletion of the current node and get back to the default view of the node. :result: Either a redirect response or a dictionary passed to the template for rendering. :rtype: pyramid.httpexceptions.HTTPFound or dict """ action = self.request.POST.get(u'delete') if action is not None: parent = self.context.__parent__ if action == u'delete': location = resource_url(parent, self.request) self.flash(_(u'${title} was deleted.', mapping=dict(title=self.context.title)), u'success') del parent[self.context.name] else: location = resource_url(self.context, self.request) return HTTPFound(location=location) return {}
def display_deleted_item(docid, tree_node): deleted_item = tree_node.deleted_item version = repo.history(docid, only_current=True)[0] if tree_node: url = resource_url(context, request, 'trash', query={ 'subfolder': str(docid)}) else: url = None if deleted_item: deleted_by = profiles[deleted_item.deleted_by] return { 'date': format_local_date(deleted_item.deleted_time, tz), 'deleted_by': { 'name': deleted_by.title, 'url': resource_url(deleted_by, request), }, 'restore_url': resource_url( context, request, 'restore', query={'docid': str(deleted_item.docid), 'name': deleted_item.name}), 'title': version.title, 'url': url} else: return { 'date': None, 'deleted_by': None, 'restore_url': None, 'title': version.title, 'url': url}
def sort(self): self.response['title'] = _(u"order_agenda_template_view_title", default = u"Drag and drop agenda items to reorder") post = self.request.POST if 'cancel' in self.request.POST: url = resource_url(self.context, self.request) return HTTPFound(location = url) if 'save' in post: controls = self.request.POST.items() ais = self.context.get_field_value('agenda_items') order = 0 agenda_items = [] for (k, v) in controls: if k == 'agenda_items': ai = ais[int(v)] ai['order'] = order order += 1 agenda_items.append(ai) self.context.set_field_value('agenda_items', agenda_items) self.api.flash_messages.add(_(u'Order updated')) url = resource_url(self.context, self.request) return HTTPFound(location = url) return self.response
def edit_page(context, request): if 'form.submitted' in request.params: context.data = request.params['body'] return HTTPFound(location = resource_url(context, request)) return dict(page = context, save_url = resource_url(context, request, 'edit_page'))
def login_view(context, request): whence = request.registry.queryUtility(ICameFromURL) if whence is not None: came_from = whence(request) else: came_from = resource_url(context, request) form = Form(Login(), buttons=('login',)) rendered_form = form.render({'came_from': came_from}) message = request.GET.get('message') if 'login' in request.POST: try: appstruct = form.validate(request.POST.items()) except ValidationFailure, e: rendered_form = e.render() message = 'Please supply required values' else: credentials = {'login': appstruct['login_name'], 'password': appstruct['password'], } api = get_api(request.environ) identity, headers = api.login(credentials) if identity is not None: came_from = appstruct.get('came_from') if came_from is None: came_from = resource_url(context, request) return HTTPFound(location=came_from, headers=headers) message = 'Login failed'
def chatter_user_info(context, request, userid=None): chatter = find_chatter(context) chatter_url = resource_url(chatter, request) profiles = find_profiles(context) if userid is None: userid = request.GET.get('userid') if userid is None: userid = authenticated_userid(request) profile = profiles.get(userid) profile_url = profile and resource_url(profile, request) or None photo = profile and profile.get('photo') or None if photo is not None: photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE) else: photo_url = get_static_url(request) + "/images/defaultUser.gif" posts = sum(1 for p in chatter.recentWithCreators(*[userid])) following = sum(1 for u in chatter.listFollowed(userid)) followers = sum(1 for u in chatter.listFollowing(userid)) return {'creator': getattr(profile, 'title', 'anonymous'), 'creator_url': '%s%s' % (chatter_url, userid), 'creator_profile_url': profile_url, 'creator_image_url': photo_url, 'creator_userid': userid, 'chatter_url': chatter_url, 'posts': posts, 'following': following, 'followers': followers}
def report_view(context, request): api = TemplateAPI(context, request, context.title) peopledir = find_peopledirectory(context) section = context.__parent__ peopledir_tabs = get_tabs(peopledir, request, section.__name__) client_json_data = {"grid_data": get_grid_data(context, request)} descriptions = get_report_descriptions(context) mgr = ILetterManager(context) letter_info = mgr.get_info(request) kw, qualifiers = get_search_qualifiers(request) print_url = resource_url(context, request, "print.html", **kw) csv_url = resource_url(context, request, "csv", **kw) pictures_url = resource_url(context, request, "picture_view.html", **kw) opensearch_url = resource_url(context, request, "opensearch.xml") return dict( api=api, peopledir=peopledir, peopledir_tabs=peopledir_tabs, head_data=convert_to_script(client_json_data), descriptions=descriptions, letters=letter_info, print_url=print_url, csv_url=csv_url, pictures_url=pictures_url, qualifiers=qualifiers, opensearch_url=opensearch_url, actions=get_actions(context, request), mailto=_get_mailto(context, peopledir), )
def forbidden(context, request): site = find_site(context) request.session['came_from'] = request.url api = TemplateAPI(context, request, 'Forbidden') request.response.status = '200 OK' blacklisted = request.session.get('access_blacklisted', False) if blacklisted: notice = getattr(site, 'restricted_notice', '') return render_to_response('templates/forbidden_blacklisted.pt', dict(api=api, notice=notice), request=request) password_expired = request.session.get('password_expired', False) if password_expired: redirect = request.session.get('change_url') return HTTPFound(location=redirect) if api.userid: login_url = resource_url(site, request, 'login.html') else: reason = request.session.get('logout_reason') if reason is None: reason = 'Not logged in' login_url = resource_url(site, request, 'login.html', query={'reason': reason}) return { 'api': api, 'login_form_url': login_url, 'homepage_url': resource_url(site, request) }
def forbidden(context, request): site = find_site(context) request.session['came_from'] = request.url api = TemplateAPI(context, request, 'Forbidden') request.response.status = '200 OK' blacklisted = request.session.get('access_blacklisted', False) if blacklisted: notice = getattr(site, 'restricted_notice', '') return render_to_response( 'templates/forbidden_blacklisted.pt', dict(api=api, notice=notice), request=request) password_expired = request.session.get('password_expired', False) if password_expired: redirect = request.session.get('change_url') return HTTPFound(location=redirect) if api.userid: login_url = resource_url(site, request, 'login.html') else: reason = request.session.get('logout_reason') if reason is None: reason = 'Not logged in' login_url = resource_url( site, request, 'login.html', query={'reason': reason}) return { 'api': api, 'login_form_url': login_url, 'homepage_url': resource_url(site, request) }
def __init__(self, context, request, page_title=None): self.settings = dict(get_settings(context)) self.settings.update(self.config_settings) self.site = site = find_site(context) self.context = context self.request = request self.userid = authenticated_userid(request) self.app_url = app_url = request.application_url self.profile_url = app_url + '/profiles/%s' % self.userid self.here_url = self.context_url = resource_url(context, request) self.view_url = resource_url(context, request, request.view_name) self.read_only = not is_normal_mode(request.registry) self.static_url = get_static_url(request) self.resource_devel_mode = is_resource_devel_mode() self.browser_upgrade_url = request.registry.settings.get( 'browser_upgrade_url', '') # this data will be provided for the client javascript self.karl_client_data = {} # Provide a setting in the INI to fully control the entire URL # to the static. This is when the proxy runs a different port # number, or to "pipeline" resources on a different URL path. full_static_path = self.settings.get('full_static_path', False) if full_static_path: if '%d' in full_static_path: # XXX XXX note self._start_time is needed... and not _start_time # XXX XXX since this was a trivial bug, there is chance that # XXX XXX this actually never runs! TODO testing??? full_static_path = full_static_path % self._start_time self.static_url = full_static_path self.page_title = page_title self.system_name = self.title = self.settings.get('title', 'KARL') self.user_is_admin = 'group.KarlAdmin' in effective_principals(request) self.can_administer = has_permission('administer', site, request) self.can_email = has_permission('email', site, request) self.admin_url = resource_url(site, request, 'admin.html') date_format = get_user_date_format(context, request) self.karl_client_data['date_format'] = date_format # XXX XXX XXX This will never work from peoples formish templates # XXX XXX XXX (edit_profile and derivates) because, in those form # XXX XXX XXX controllers, the api is instantiated from __init__, # XXX XXX XXX where request.form is still unset!!! (From all other # XXX XXX XXX formcontrollers the api is instantiated from __call__, # XXX XXX XXX which is why this works. A chicken-and-egg problem, really. if hasattr(request, 'form') and getattr(request.form, 'errors', False): # This is a failed form submission request, specify an error message self.error_message = u'Please correct the indicated errors.' self.site_announcements = getattr(self.site, "site_announcements", []) profiles = find_profiles(self.site) profile = profiles is not None and profiles.get(self.userid, None) or None self.unseen_site_announcements = [] if profile is not None and hasattr(profile, "_seen_announcements") \ and hasattr(site, "site_announcements"): for item in site.site_announcements: if item['hash'] not in profile._seen_announcements: self.unseen_site_announcements.append(item)
def show_forum_view(context, request): page_title = context.title api = TemplateAPI(context, request, page_title) actions = [] if has_permission('create', context, request): actions.append(('Add Forum Topic', 'add_forum_topic.html')) if has_permission('edit', context, request): actions.append(('Edit', 'edit.html')) if has_permission('delete', context, request): actions.append(('Delete', 'delete.html')) profiles = find_profiles(context) karldates = getUtility(IKarlDates) topic_batch = get_topic_batch(context, request) topic_entries = topic_batch['entries'] topics = [] for topic in topic_entries: D = {} profile = profiles.get(topic.creator) posted_by = getattr(profile, 'title', None) date = karldates(topic.created, 'longform') D['url'] = resource_url(topic, request) D['title'] = topic.title D['posted_by'] = posted_by D['date'] = date D['number_of_comments'] = len(topic['comments']) topics.append(D) # In the intranet side, the backlinks should go to the show_forums # view (the default) forums = context.__parent__ backto = { 'href': resource_url(forums, request), 'title': forums.title, } # Get a layout layout_provider = get_layout_provider(context, request) layout = layout_provider('generic') ux2_layout = request.layout_manager.layout ux2_layout.section_style = "none" return render_to_response( 'templates/show_forum.pt', dict(api = api, actions = actions, title = context.title, topics = topics, batch_info = topic_batch, backto=backto, old_layout=layout), request=request, )
def redirector_view(context, request): where = context.target_url if not where.startswith('http'): if where.startswith('/'): where = basejoin(resource_url(context, request), where) else: elements = where.split('/') where = resource_url(context.__parent__, request, *elements) return HTTPFound(location=where)
def __init__(self, context, request, page_title=None): self.settings = dict(get_settings(context)) self.settings.update(self.config_settings) self.site = site = find_site(context) self.context = context self.request = request self.userid = authenticated_userid(request) self.app_url = app_url = request.application_url self.profile_url = app_url + "/profiles/%s" % self.userid self.here_url = self.context_url = resource_url(context, request) self.view_url = resource_url(context, request, request.view_name) self.read_only = not is_normal_mode(request.registry) self.static_url = get_static_url(request) self.resource_devel_mode = is_resource_devel_mode() self.browser_upgrade_url = request.registry.settings.get("browser_upgrade_url", "") # this data will be provided for the client javascript self.karl_client_data = {} # Provide a setting in the INI to fully control the entire URL # to the static. This is when the proxy runs a different port # number, or to "pipeline" resources on a different URL path. full_static_path = self.settings.get("full_static_path", False) if full_static_path: if "%d" in full_static_path: # XXX XXX note self._start_time is needed... and not _start_time # XXX XXX since this was a trivial bug, there is chance that # XXX XXX this actually never runs! TODO testing??? full_static_path = full_static_path % self._start_time self.static_url = full_static_path self.page_title = page_title self.system_name = self.title = self.settings.get("title", "KARL") self.user_is_admin = "group.KarlAdmin" in effective_principals(request) self.can_administer = has_permission("administer", site, request) self.can_email = has_permission("email", site, request) self.admin_url = resource_url(site, request, "admin.html") date_format = get_user_date_format(context, request) self.karl_client_data["date_format"] = date_format # XXX XXX XXX This will never work from peoples formish templates # XXX XXX XXX (edit_profile and derivates) because, in those form # XXX XXX XXX controllers, the api is instantiated from __init__, # XXX XXX XXX where request.form is still unset!!! (From all other # XXX XXX XXX formcontrollers the api is instantiated from __call__, # XXX XXX XXX which is why this works. A chicken-and-egg problem, really. if hasattr(request, "form") and getattr(request.form, "errors", False): # This is a failed form submission request, specify an error message self.error_message = u"Please correct the indicated errors." self.site_announcements = getattr(self.site, "site_announcements", []) profiles = find_profiles(self.site) profile = profiles is not None and profiles.get(self.userid, None) or None self.unseen_site_announcements = [] if profile is not None and hasattr(profile, "_seen_announcements") and hasattr(site, "site_announcements"): for item in site.site_announcements: if item["hash"] not in profile._seen_announcements: self.unseen_site_announcements.append(item)
def edit_page(context, request): if 'form.submitted' in request.params: context.data = request.params['body'] return HTTPFound(location = resource_url(context, request)) logged_in = authenticated_userid(request) return dict(page = context, save_url = resource_url(context, request, 'edit_page'), logged_in = logged_in )
def edit_page(context, request): if 'form.submitted' in request.params: context.data = request.params['body'] return HTTPFound(location=resource_url(context, request)) logged_in = authenticated_userid(request) return dict(page=context, save_url=resource_url(context, request, 'edit_page'), logged_in=logged_in)
def url(self): if self._url is None: if IComment.providedBy(self.context): # show the comment in context of its grandparent. # (its parent is a comments folder.) parent = self.context.__parent__.__parent__ self._url = "%s#comment-%s" % (resource_url(parent, self.request), self.context.__name__) else: self._url = resource_url(self.context, self.request) return self._url
def url(self): if self._url is None: if IComment.providedBy(self.context): # show the comment in context of its grandparent. # (its parent is a comments folder.) parent = self.context.__parent__.__parent__ self._url = '%s#comment-%s' % (resource_url( parent, self.request), self.context.__name__) else: self._url = resource_url(self.context, self.request) return self._url
def __init__(self, context, request): self.context = context self.request = request self.app_url = request.application_url # what if context is not traversable? if getattr(context, '__name__', None) is not None: self.context_url = request.resource_url(context) else: self.context_url = request.url self.portlets = [] self.settings = settings = request.registry.settings self.app_url = app_url = request.application_url if getattr(context, '__name__', '_no_name_') != '_no_name_': self.here_url = resource_url(context, request) self.site = find_site(context) chatter = find_chatter(context) self.chatter_url = resource_url(chatter, request) self.current_intranet = find_intranet(context) self.people_url = app_url + '/' + settings.get('people_path', 'people') self.profiles_url = app_url + '/profiles' self.project_name = settings.get('system_name', 'KARL') self.page_title = getattr(context, 'title', 'Page Title') self.userid = authenticated_userid(request) self.tinymce_height = 400 self.tinymce_width = 560 self.html_id_next = 0 self.client_components = set() self.js_devel_mode = asbool(settings.get('js_devel_mode', 'false')) if self.settings: self.kaltura_info = dict( enabled = self.settings.get( 'kaltura_enabled', False) in ('true', 'True'), partner_id = self.settings.get('kaltura_partner_id', ''), sub_partner_id = self.settings.get( 'kaltura_sub_partner_id', ''), admin_secret = self.settings.get('kaltura_admin_secret', ''), user_secret = self.settings.get('kaltura_user_secret', ''), kcw_uiconf_id = self.settings.get( 'kaltura_kcw_uiconf_id', '1000741'), player_uiconf_id = self.settings.get( 'kaltura_player_uiconf_id', ''), player_cache_st = self.settings.get( 'kaltura_player_cache_st', ''), local_user = self.userid, ) if not self.settings.get( 'kaltura_client_session', False) in ('true', 'True'): # Secrets will not be sent to client, instead session is handled on the server. self.kaltura_info['session_url'] = app_url + '/' + 'kaltura_create_session.json' else: self.kaltura_info = dict( enabled = False, )
def __init__(self, context, request): self.context = context self.request = request self.app_url = request.application_url # what if context is not traversable? if getattr(context, '__name__', None) is not None: self.context_url = request.resource_url(context) else: self.context_url = request.url self.portlets = [] self.settings = settings = request.registry.settings self.app_url = app_url = request.application_url if getattr(context, '__name__', '_no_name_') != '_no_name_': self.here_url = resource_url(context, request) self.site = find_site(context) chatter = find_chatter(context) self.chatter_url = resource_url(chatter, request) self.current_intranet = find_intranet(context) self.people_url = app_url + '/' + settings.get('people_path', 'people') self.profiles_url = app_url + '/profiles' self.project_name = settings.get('system_name', 'KARL') self.page_title = getattr(context, 'title', 'Page Title') self.userid = authenticated_userid(request) self.tinymce_height = 400 self.tinymce_width = 560 self.html_id_next = 0 self.client_components = set() self.js_devel_mode = asbool(settings.get('js_devel_mode', 'false')) if self.settings: self.kaltura_info = dict( enabled=self.settings.get('kaltura_enabled', False) in ('true', 'True'), partner_id=self.settings.get('kaltura_partner_id', ''), sub_partner_id=self.settings.get('kaltura_sub_partner_id', ''), admin_secret=self.settings.get('kaltura_admin_secret', ''), user_secret=self.settings.get('kaltura_user_secret', ''), kcw_uiconf_id=self.settings.get('kaltura_kcw_uiconf_id', '1000741'), player_uiconf_id=self.settings.get('kaltura_player_uiconf_id', ''), player_cache_st=self.settings.get('kaltura_player_cache_st', ''), local_user=self.userid, ) if not self.settings.get('kaltura_client_session', False) in ('true', 'True'): # Secrets will not be sent to client, instead session is handled on the server. self.kaltura_info[ 'session_url'] = app_url + '/' + 'kaltura_create_session.json' else: self.kaltura_info = dict(enabled=False, )
def logout_view(context, request, reason='Logged out'): site = find_site(context) site_url = resource_url(site, request) query = {'reason': reason, 'came_from': site_url} if asbool(get_setting(context, 'kerberos', 'False')): # If user explicitly logs out, don't try to log back in immediately # using kerberos. query['try_kerberos'] = 'False' login_url = resource_url(site, request, 'login.html', query=query) redirect = HTTPFound(location=login_url) redirect.headers.extend(forget(request)) return redirect
def redirect_community_view(context, request): assert ICommunity.providedBy(context), str(type(context)) default_tool = getattr(context, 'default_tool', None) if not default_tool: default_tool = 'view.html' # Preserve status_message=, etc in query string query = request.GET if query: location = resource_url(context, request, default_tool, query=query) else: location = resource_url(context, request, default_tool) return HTTPFound(location=location)
def logout_view(context, request, reason='Logged out'): site = find_site(context) site_url = resource_url(site, request) login_url = resource_url(site, request, 'login.html', query={ 'reason': reason, 'came_from': site_url}) redirect = HTTPFound(location=login_url) plugins = request.environ.get('repoze.who.plugins', {}) auth_tkt = plugins.get('auth_tkt') if auth_tkt is not None: forget_headers = auth_tkt.forget(request.environ, {}) redirect.headers.extend(forget_headers) return redirect
def browse_images(self): """ browse images """ images_folder = self._get_images_folder() images = images_folder.list_content(content_type='image') result = [] root_url = self.request.application_url for i in images: i_url = resource_url(i, self.request) i_url = _remove_prefix(i_url, root_url) i_thumb_url = resource_url(i, self.request) + "thumbnail" i_thumb_url = _remove_prefix(i_thumb_url, root_url) result.append({'file': i.id, 'url': i_url, 'thumb_url': i_thumb_url}) return result
def delete_tutorial_view(context, request): parent = context.__parent__ if 'form.yes' in request.params: name = context.__name__ del parent[name] return HTTPFound(location=resource_url(parent, request)) if 'form.no' in request.params: return HTTPFound(location=resource_url(context, request)) return dict( api = API(context, request), form_url = resource_url(context, request, 'delete'), message = 'Are you sure you want to delete "%s"' % context.title )
def __call__(self): context = self.context request = self.request page_title = context.title api = TemplateAPI(context, request, page_title) karldates = getUtility(IKarlDates) actions = [] if has_permission('create', context, request): actions = [(title, request.resource_url(context, view)) for title, view in self._admin_actions] forums = list(context.values()) forums.sort(titlesort) forum_data = [] for forum in forums: D = {} D['title'] = forum.title D['url'] = resource_url(forum, request) D['number_of_topics'] = number_of_topics(forum) D['number_of_comments'] = number_of_comments(forum, request) latest = latest_object(forum, request) _NOW = datetime.datetime.now() if latest: D['latest_activity_url'] = resource_url(latest, request) D['latest_activity_link'] = getattr(latest, 'title', None) D['latest_activity_by'] = getattr(latest, 'creator', None) modified = getattr(latest, 'modified', _NOW) modified_str = karldates(modified, 'longform') D['latest_activity_at'] = modified_str else: D['latest_activity_url'] = None D['latest_activity_link'] = None D['latest_activity_by'] = None D['latest_activity_at'] = None forum_data.append(D) return render_to_response( 'templates/show_forums.pt', dict(api=api, actions=actions, forum_data = forum_data), request=request, )
def add(self, name, docid, deleted_item, is_container): """Add an item to self.deleted.""" version = self.repo.history(docid, only_current=True)[0] item_path = encode_trash_path(self.subfolder_path + [(name, docid)]) if is_container: url = resource_url(self.context, self.request, 'trash', query={'subfolder': item_path}) else: url = None if deleted_item is not None: deleted_by = self.profiles[deleted_item.deleted_by] if self.can_shred: shred_url = resource_url(self.context, self.request, '@@shred', query={'path': item_path}) else: shred_url = None self.deleted.append({ 'date': format_local_date(deleted_item.deleted_time, self.tz), 'deleted_by': { 'name': deleted_by.title, 'url': resource_url(deleted_by, self.request), }, 'restore_url': resource_url(self.context, self.request, '@@restore', query={'path': item_path}), 'shred_url': shred_url, 'title': version.title, 'url': url, }) else: self.deleted.append({ 'date': None, 'deleted_by': None, 'restore_url': None, 'shred_url': None, 'title': version.title, 'url': url, })
def add_page(context, request): name = request.subpath[0] if 'form.submitted' in request.params: body = request.params['body'] page = Page(body) page.__name__ = name page.__parent__ = context context[name] = page return HTTPFound(location=resource_url(page, request)) save_url = resource_url(context, request, 'add_page', name) page = Page('') page.__name__ = name page.__parent__ = context return dict(page=page, save_url=save_url)
def email_voters_about_ongoing_poll(poll, request=None): """ Email voters about that a poll they have voting permission in is open. I.e. in state ongoing. This function is triggered by a workflow subscriber, so not all functionality is nested in the workflow callback. (It would make permission tests very annoying and hard to write otherwise) Note that there's a setting on the meeting called poll_notification_setting that controls wether this should be executed or not. """ meeting = find_interface(poll, IMeeting) assert meeting if not meeting.get_field_value('poll_notification_setting', True): return if request is None: request = get_current_request() userids = security.find_authorized_userids(poll, (security.ADD_VOTE, )) root = find_root(meeting) users = root['users'] email_addresses = set() for userid in userids: #In case user is deleted, they won't have the required permission either #find_authorized_userids loops through the users folder email = users[userid].get_field_value('email') if email: email_addresses.add(email) response = {} response['meeting'] = meeting response['meeting_url'] = resource_url(meeting, request) response['poll_url'] = resource_url(poll, request) sender = "%s <%s>" % (meeting.get_field_value('meeting_mail_name'), meeting.get_field_value('meeting_mail_address')) #FIXME: This should be detatched into a view component body_html = render('../views/templates/email/ongoing_poll_notification.pt', response, request=request) #Since subject won't be part of a renderer, we need to translate it manually #Keep the _ -syntax otherwise Babel/lingua won't pick up the string localizer = get_localizer(request) subject = localizer.translate(_(u"VoteIT: Open poll")) mailer = get_mailer(request) #We need to send individual messages anyway for email in email_addresses: msg = Message(subject=subject, sender=sender, recipients=[ email, ], html=body_html) mailer.send(msg)
def Url(self, resource=None): """ Generates the default url for the resource. Includes the file extension if one specified for the object. If resource is None the current context object is used as resource. returns url """ if not resource: resource = self.context if hasattr(resource, "extension") and resource.extension: return u"%s.%s" % (resource_url( resource, self.request)[:-1], resource.extension) return resource_url(resource, self.request)
def forbidden(context, request): site = find_site(context) request.session['came_from'] = request.url api = TemplateAPI(context, request, 'Secure Login') request.response.status = '401 Unauthorized' if api.userid: login_url = resource_url(site, request, 'login.html') else: query = {'came_from': request.url, 'reason': 'Not logged in'} login_url = resource_url(site, request, 'login.html', query=query) return { 'api': api, 'login_form_url': login_url, 'homepage_url': resource_url(site, request) }
def quip_info(request, *quips): result = [] chatter = find_chatter(request.context) profiles = find_profiles(request.context) chatter_url = resource_url(chatter, request) userid = authenticated_userid(request) for quip in quips: quip_id = quip.__name__ creator = quip.creator reposter = None reposter_fullname = '' if quip.repost is not None: creator = quip.repost reposter = quip.creator profile = profiles.get(reposter) reposter_fullname = profile and profile.title or reposter reply = None if quip.reply in chatter: reply = quip_info(request, *(chatter[quip.reply], ))[0] profile = profiles.get(creator) photo = profile and profile.get('photo') or None creator_fullname = profile and profile.title or creator if photo is not None: photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE) else: photo_url = get_static_url(request) + "/images/defaultUser.gif" timeago = str(quip.created.strftime(TIMEAGO_FORMAT)) info = { 'text': quip.text, 'html': quip.html or quip.text, 'creator': creator, 'creator_fullname': creator_fullname, 'creator_url': '%s%s' % (chatter_url, quip.creator), 'creator_image_url': photo_url, 'is_current_user': creator == userid, 'reposter': reposter, 'reposter_fullname': reposter_fullname, 'reply': reply, 'timeago': timeago, 'names': list(quip.names), 'communities': list(quip.communities), 'tags': list(quip.tags), 'url': resource_url(quip, request), 'private': bool(getattr(quip, '__acl__', ())), 'quip_id': quip_id, } result.append(info) return result
def handle_submit(self, converted): context = self.context request = self.request system_name = get_setting(context, 'system_name', 'KARL') address = converted['email'] if address: address = address.lower() search = getAdapter(context, ICatalogSearch) count, docids, resolver = search(interfaces=[IProfile], email=[address]) users = find_users(context) for docid in docids: profile = resolver(docid) if profile is None: continue userid = profile.__name__ user = users.get_by_id(userid) if user is None: continue # found the profile and user break else: raise ValidationError( **{ "email": "%s has no account with the email address: %s" % (system_name, address) }) groups = user['groups'] if groups and 'group.KarlStaff' in groups: # because staff accounts are managed centrally, staff # must use the forgot_password_url if it is set. forgot_password_url = get_setting(context, 'forgot_password_url') if forgot_password_url: came_from = resource_url(context, request, "login.html") url = '%s?email=%s&came_from=%s' % ( forgot_password_url, urllib.quote_plus(address), urllib.quote_plus(came_from)) return HTTPFound(location=url) request_password_reset(user, profile, request) url = resource_url(context, request, 'reset_sent.html') + ( '?email=%s' % urllib.quote_plus(address)) return HTTPFound(location=url)
def comments(context, request): profiles = find_profiles(context) karldates = request.registry.getUtility(IKarlDates) comments = [] for comment in context['comments'].values(): profile = profiles.get(comment.creator) author_name = profile.title author_url = resource_url(profile, request) newc = {} newc['id'] = comment.__name__ if has_permission('edit', comment, request): newc['edit_url'] = resource_url(comment, request, 'edit.html') else: newc['edit_url'] = None if has_permission('delete', comment, request): newc['delete_url'] = resource_url(comment, request, 'delete.html') else: newc['delete_url'] = None if has_permission('administer', comment, request): newc['advanced_url'] = resource_url(comment, request, 'advanced.html') else: newc['advanced_url'] = None # Display portrait photo = profile.get('photo') if photo is not None: photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE) else: photo_url = request.static_url( "karl.views:static/images/defaultUser.gif") newc["portrait_url"] = photo_url newc['author_url'] = author_url newc['author_name'] = author_name newc['date'] = karldates(comment.created, 'longform') newc['timestamp'] = comment.created newc['text'] = comment.text # Fetch the attachments info newc['attachments'] = fetch_attachments(comment, request) comments.append(newc) comments.sort(key=lambda c: c['timestamp']) return {'comments': comments}
def handle_submit(self, converted): if lock.owns_lock(self.context, self.userid): lock.clear(self.context) context = self.context request = self.request workflow = self.workflow # *will be* modified event objectEventNotify(ObjectWillBeModifiedEvent(context)) if workflow is not None: if 'security_state' in converted: workflow.transition_to_state(context, request, converted['security_state']) context.text = converted['text'] context.description = extract_description(converted['text']) newtitle = converted['title'] if newtitle != context.title: context.change_title(newtitle) # Save the tags on it set_tags(context, request, converted['tags']) # Modified context.modified_by = authenticated_userid(request) objectEventNotify(ObjectModifiedEvent(context)) location = resource_url(context, request) msg = "?status_message=Wiki%20Page%20edited" return HTTPFound(location=location + msg)
def get_wikitoc_data(context, request): wikiparent = context.__parent__ search = getAdapter(context, ICatalogSearch) count, docids, resolver = search(path=resource_path(wikiparent), interfaces=[ IWikiPage, ]) items = [] profiles = find_profiles(context) for docid in docids: entry = resolver(docid) tags = getMultiAdapter((entry, request), ITagQuery).tagswithcounts author = entry.creator profile = profiles.get(author, None) profile_url = resource_url(profile, request) if profile is not None: author_name = '%s %s' % (profile.firstname, profile.lastname) else: author_name = author items.append( dict( id="id_" + entry.__name__, name=entry.__name__, title=entry.title, author=author, author_name=author_name, profile_url=profile_url, tags=[tag['tag'] for tag in tags], created=entry.created.isoformat(), modified=entry.modified.isoformat(), )) result = dict(items=items, ) return result
def handle_submit(self, converted): request = self.request context = self.context workflow = self.workflow wikipage = create_content( IWikiPage, converted['title'], converted['text'], extract_description(converted['text']), authenticated_userid(request), ) name = make_name(context, converted['title']) context[name] = wikipage if workflow is not None: workflow.initialize(wikipage) if 'security_state' in converted: workflow.transition_to_state(wikipage, request, converted['security_state']) # Save the tags on it. set_tags(wikipage, request, converted['tags']) relocate_temp_images(wikipage, request) if converted['sendalert']: alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(wikipage, request) msg = '?status_message=Wiki%20Page%20created' location = resource_url(wikipage, request) + msg return HTTPFound(location=location)