def admin_menu(context, request): admin_settings = {} site = find_site(context) settings = request.registry.settings syslog_view = get_setting(context, 'syslog_view', None) admin_settings['syslog_view_enabled'] = syslog_view != None admin_settings['has_logs'] = not not get_setting(context, 'logs_view', None) admin_settings['redislog'] = asbool(settings.get('redislog', 'False')) admin_settings['can_administer'] = has_permission('administer', site, request) admin_settings['can_email'] = has_permission('email', site, request) statistics_folder = get_setting(context, 'statistics_folder', None) if statistics_folder is not None and os.path.exists(statistics_folder): csv_files = [fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv')] admin_settings['statistics_view_enabled'] = not not csv_files else: admin_settings['statistics_view_enabled'] = False admin_settings['quarantine_url'] = ('%s/po_quarantine.html' % request.application_url) site = find_site(context) if 'offices' in site: admin_settings['offices_url'] = resource_url(site['offices'], request) else: admin_settings['offices_url'] = None admin_settings['has_mailin'] = ( get_setting(context, 'zodbconn.uri.postoffice') and get_setting(context, 'postoffice.queue')) return admin_settings
def admin_menu(context, request): admin_settings = {} site = find_site(context) settings = request.registry.settings syslog_view = get_setting(context, 'syslog_view', None) admin_settings['syslog_view_enabled'] = syslog_view != None admin_settings['has_logs'] = not not get_setting(context, 'logs_view', None) admin_settings['redislog'] = asbool(settings.get('redislog', 'False')) admin_settings['can_administer'] = has_permission('administer', site, request) admin_settings['can_email'] = has_permission('email', site, request) statistics_folder = get_setting(context, 'statistics_folder', None) if statistics_folder is not None and os.path.exists(statistics_folder): csv_files = [ fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv') ] admin_settings['statistics_view_enabled'] = not not csv_files else: admin_settings['statistics_view_enabled'] = False admin_settings['quarantine_url'] = ('%s/po_quarantine.html' % request.application_url) site = find_site(context) if 'offices' in site: admin_settings['offices_url'] = resource_url(site['offices'], request) else: admin_settings['offices_url'] = None admin_settings['has_mailin'] = ( get_setting(context, 'zodbconn.uri.postoffice') and get_setting(context, 'postoffice.queue')) return admin_settings
def restrict_access_view(context, request): site = find_site(context) access_whitelist = getattr(site, 'access_whitelist', []) access_blacklist = getattr(site, 'access_blacklist', []) restricted_notice = getattr(site, 'restricted_notice', '') if ('submit-access-restrictions' in request.params) or ( 'submit' in request.params): whitelist = request.params.get('restricted-whitelist-input', '').strip() whitelist = whitelist.split() if whitelist != access_whitelist: access_whitelist = site.access_whitelist = whitelist blacklist = request.params.get('restricted-blacklist-input', '').strip() blacklist = blacklist.split() if blacklist != access_blacklist: access_blacklist = site.access_blacklist = blacklist notice = request.params.get('restricted-notice-input', '').strip() if notice != restricted_notice: restricted_notice = site.restricted_notice = notice api = AdminTemplateAPI(request.context, request, 'Admin UI: Restrict Access') return {'api': api, 'menu': _menu_macro(), 'restricted_notice': restricted_notice, 'access_whitelist': '\n'.join(access_whitelist), 'access_blacklist': '\n'.join(access_blacklist), }
def office_dump_csv(request): from ZODB.utils import u64 cursor = request.context._p_jar._storage.ex_cursor('office_dump') cursor.execute( """ select get_path(state), state->>'modified', state->>'modified_by', state->>'title', state->>'mimetype' from newt natural join karlex where community_zoid = %s and class_name = 'karl.content.models.files.CommunityFile' """, (u64(find_site(request.context)['offices']._p_oid), )) f = StringIO() writerow = csv.writer(f).writerow writerow(('File Title', 'Office', 'Last Updated By (User)', 'Last Updated On (Date)', 'File Type', 'URL')) for path, modified, modified_by, title, mimetype in cursor: office = path.split('/', 4)[2] writerow((title, path.split('/', 4)[2], modified_by, modified, mimetype, 'https://karl.soros.org' + path[:-1])) cursor.close() response = Response(f.getvalue()) response.content_type = 'application/x-csv' # suggest a filename based on the report name response.headers.add('Content-Disposition', 'attachment;filename=office_dump.csv') return response
def restrict_access_view(context, request): site = find_site(context) access_whitelist = getattr(site, 'access_whitelist', []) access_blacklist = getattr(site, 'access_blacklist', []) restricted_notice = getattr(site, 'restricted_notice', '') if ('submit-access-restrictions' in request.params) or ('submit' in request.params): whitelist = request.params.get('restricted-whitelist-input', '').strip() whitelist = whitelist.split() if whitelist != access_whitelist: access_whitelist = site.access_whitelist = whitelist blacklist = request.params.get('restricted-blacklist-input', '').strip() blacklist = blacklist.split() if blacklist != access_blacklist: access_blacklist = site.access_blacklist = blacklist notice = request.params.get('restricted-notice-input', '').strip() if notice != restricted_notice: restricted_notice = site.restricted_notice = notice api = AdminTemplateAPI(request.context, request, 'Admin UI: Restrict Access') return { 'api': api, 'menu': _menu_macro(), 'restricted_notice': restricted_notice, 'access_whitelist': '\n'.join(access_whitelist), 'access_blacklist': '\n'.join(access_blacklist), }
def user_tagged_content(event): if ITagAddedEvent.providedBy(event): request = get_current_request() context = getattr(request, 'context', None) if context is None: return events = find_events(context) if not events: return site = find_site(context) catalog = find_catalog(context) path = catalog.document_map.address_for_docid(event.item) tagged = find_resource(site, path) if tagged is None: return profile_id = event.user if profile_id in (None, 'None'): return profile = site['profiles'][profile_id] info = _getInfo(profile, tagged) if info is None: return if info['content_type'] == 'Community': info['flavor'] = 'tagged_community' elif info['content_type'] == 'Person': info['flavor'] = 'tagged_profile' else: info['flavor'] = 'tagged_other' info['operation'] = 'tagged' info['tagname'] = event.name events.push(**info)
def before_edit(self): context = self.context aliases = find_site(context).list_aliases try: del aliases[context.short_address] except KeyError: pass
def find_link_tickets(context): site = find_site(context) link_tickets = site.get('link_tickets', None) if not link_tickets: link_tickets = LinkTickets() site['link_tickets'] = link_tickets return link_tickets
def _get_user_home_path(context, request): """If currently authenticated user has a 'home_path' set, create a response redirecting user to that path. Otherwise return None. """ userid = authenticated_userid(request) if userid is None: return None, None site = find_site(context) profiles = find_profiles(site) profile = profiles.get(userid, None) if profile is None: return None, None home_path = getattr(profile, 'home_path', None) if home_path: # OSI sets this to a single space to mean None home_path = home_path.strip() if not home_path: return None, None tdict = traverse(site, home_path) target = tdict['context'] view_name = tdict['view_name'] subpath = list(tdict['subpath']) if view_name: subpath.insert(0, view_name) return target, subpath
def send_mail(self, username, profile): site = find_site(self.context) title = get_setting(self.context, 'title') subject = 'Thank you for joining %s' % title body_template = get_renderer( 'templates/email_accept_site_invitation.pt').implementation() system_email_domain = get_setting(self.context, 'system_email_domain') from_name = '%s invitation' % title from_email = 'invitation@%s' % system_email_domain mailer = getUtility(IMailDelivery) msg = MIMEMultipart('alternative') msg['From'] = '%s <%s>' % (from_name, from_email) msg['To'] = profile.email msg['Subject'] = subject bodyhtml = body_template( username=username, site_href=resource_url(site, self.request), system_name=title ) bodyplain = html2text.html2text(bodyhtml) htmlpart = MIMEText(bodyhtml.encode('UTF-8'), 'html', 'UTF-8') plainpart = MIMEText(bodyplain.encode('UTF-8'), 'plain', 'UTF-8') msg.attach(plainpart) msg.attach(htmlpart) mailer.send([profile.email], msg)
def __init__(self, context, request, page_title=None): super(AdminTemplateAPI, self).__init__(context, request, page_title) settings = request.registry.settings syslog_view = get_setting(context, 'syslog_view', None) self.syslog_view_enabled = syslog_view != None self.has_logs = not not get_setting(context, 'logs_view', None) self.redislog = asbool(settings.get('redislog', 'False')) statistics_folder = get_setting(context, 'statistics_folder', None) if statistics_folder is not None and os.path.exists(statistics_folder): csv_files = [ fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv') ] self.statistics_view_enabled = not not csv_files else: self.statistics_view_enabled = False self.quarantine_url = ('%s/po_quarantine.html' % request.application_url) site = find_site(context) if 'offices' in site: self.offices_url = resource_url(site['offices'], request) else: self.offices_url = None self.has_mailin = (get_setting(context, 'zodbconn.uri.postoffice') and get_setting(context, 'postoffice.queue'))
def request_password_reset(user, profile, request): profile.password_reset_key = sha1(str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = resource_url(context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = MIMEMultipart('alternative') system_name = get_setting(context, 'title', 'KARL') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name bodyhtml = render( "templates/email_reset_password.pt", dict(login=user['login'], reset_url=reset_url, system_name=system_name), request=request, ) bodyplain = html2text.html2text(bodyhtml) htmlpart = MIMEText(bodyhtml.encode('UTF-8'), 'html', 'UTF-8') plainpart = MIMEText(bodyplain.encode('UTF-8'), 'plain', 'UTF-8') mail.attach(plainpart) mail.attach(htmlpart) recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(recipients, mail)
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_template_to_response( 'templates/forbidden.pt', api=api, login_form_url = model_url(site, request, 'login.html'), homepage_url = model_url(site, 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 = model_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 = model_url(site, request, 'login.html', query=query) return HTTPFound(location=login_url)
def clear_mailinglist_aliases(peopledir): site = find_site(peopledir) aliases = site.list_aliases pd_path = resource_path(peopledir) for k, v in list(aliases.items()): # avoid mutating-while-iterating if v.startswith(pd_path): del aliases[k]
def __init__(self, context, request, page_title=None): super(AdminTemplateAPI, self).__init__(context, request, page_title) settings = request.registry.settings syslog_view = get_setting(context, 'syslog_view', None) self.syslog_view_enabled = syslog_view != None self.has_logs = not not get_setting(context, 'logs_view', None) self.redislog = asbool(settings.get('redislog', 'False')) statistics_folder = get_setting(context, 'statistics_folder', None) if statistics_folder is not None and os.path.exists(statistics_folder): csv_files = [fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv')] self.statistics_view_enabled = not not csv_files else: self.statistics_view_enabled = False self.quarantine_url = ('%s/po_quarantine.html' % request.application_url) site = find_site(context) if 'offices' in site: self.offices_url = resource_url(site['offices'], request) else: self.offices_url = None self.has_mailin = ( get_setting(context, 'zodbconn.uri.postoffice') and get_setting(context, 'postoffice.queue'))
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 request_password_reset(user, profile, request): profile.password_reset_key = sha1(str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = resource_url(context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = Message() system_name = get_setting(context, 'system_name', 'KARL') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name body = render( "templates/email_reset_password.pt", dict(login=user['login'], reset_url=reset_url, system_name=system_name), request=request, ) if isinstance(body, unicode): body = body.encode("UTF-8") mail.set_payload(body, "UTF-8") mail.set_type("text/html") recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(recipients, mail)
def __init__(self, context, request, page_title=None): super(AdminTemplateAPI, self).__init__(context, request, page_title) syslog_view = get_setting(context, 'syslog_view', None) self.syslog_view_enabled = syslog_view != None self.has_logs = not not get_setting(context, 'logs_view', None) self.error_monitoring = not not get_setting( context, 'error_monitor_subsystems', None ) statistics_folder = get_setting(context, 'statistics_folder', None) if statistics_folder is not None and os.path.exists(statistics_folder): csv_files = [fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv')] self.statistics_view_enabled = not not csv_files else: self.statistics_view_enabled = False use_postoffice = not not get_setting( context, 'postoffice.zodb_uri', False) if use_postoffice: self.quarantine_url = ('%s/po_quarantine.html' % request.application_url) else: self.quarantine_url = ('%s/mailin/quarantine' % request.application_url) site = find_site(context) if 'offices' in site: self.offices_url = resource_url(site['offices'], request) else: self.offices_url = None
def site_announcement_view(context, request): """ Edit the text of the site announcement, which will be displayed on every page for every user of the site. """ request.layout_manager.use_layout('admin') site = find_site(context) if ('submit-site-announcement' in request.params) or ( 'submit' in request.params): annc = request.params.get('site-announcement-input', '').strip() if annc: # we only take the content of the first <p> tag, with # the <p> tags stripped paramatcher = re.compile('<[pP]\\b[^>]*>(.*?)</[pP]>') match = paramatcher.search(annc) if match is not None: annc = match.groups()[0] site.site_announcement = annc if 'remove-site-announcement' in request.params: site.site_announcement = u'' api = AdminTemplateAPI(context, request, 'Admin UI: Site Announcement') announcement = getattr(site, 'site_announcement', '') return dict( api=api, site_announcement=announcement, menu=_menu_macro() )
def clear_mailinglist_aliases(peopledir): site = find_site(peopledir) aliases = site.list_aliases pd_path = model_path(peopledir) for k, v in list(aliases.items()): # avoid mutating-while-iterating if v.startswith(pd_path): del aliases[k]
def request_password_reset(user, profile, request): profile.password_reset_key = sha1( str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = resource_url( context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = Message() system_name = get_setting(context, 'system_name', 'KARL') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name body = render( "templates/email_reset_password.pt", dict(login=user['login'], reset_url=reset_url, system_name=system_name), request=request, ) if isinstance(body, unicode): body = body.encode("UTF-8") mail.set_payload(body, "UTF-8") mail.set_type("text/html") recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(recipients, mail)
def user_tagged_content(event): if ITagAddedEvent.providedBy(event): request = get_current_request() context = getattr(request, "context", None) if context is None: return events = find_events(context) if not events: return site = find_site(context) catalog = find_catalog(context) path = catalog.document_map.address_for_docid(event.item) tagged = find_resource(site, path) if tagged is None: return profile_id = event.user if profile_id in (None, "None"): return profile = site["profiles"][profile_id] info = _getInfo(profile, tagged) if info is None: return if info["content_type"] == "Community": info["flavor"] = "tagged_community" elif info["content_type"] == "Person": info["flavor"] = "tagged_profile" else: info["flavor"] = "tagged_other" info["operation"] = "tagged" info["tagname"] = event.name events.push(**info)
def __init__(self, context, request, page_title=None): self.context = context self.request = request self.snippets = get_template("templates/snippets.pt") self.snippets.doctype = xhtml 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 = model_url(context, request) self.view_url = model_url(context, request, request.view_name) settings = queryUtility(ISettings) self.js_devel_mode = settings and getattr(settings, "js_devel_mode", None) self.static_url = "%s/static/%s" % (app_url, _get_static_rev()) # 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 = getattr(settings, "full_static_path", False) if full_static_path: if "%d" in full_static_path: full_static_path = full_static_path % _start_time self.static_url = full_static_path self.page_title = page_title self.system_name = get_setting(context, "system_name", "KARL") self.user_is_admin = "group.KarlAdmin" in effective_principals(request) site = find_site(context) self.admin_url = model_url(site, request, "admin.html") self.site_announcement = getattr(site, "site_announcement", "")
def request_password_reset(user, profile, request): profile.password_reset_key = sha1( str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = resource_url( context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = MIMEMultipart('alternative') system_name = get_setting(context, 'title', 'KARL') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name bodyhtml = render( "templates/email_reset_password.pt", dict(login=user['login'], reset_url=reset_url, system_name=system_name), request=request, ) bodyplain = html2text.html2text(bodyhtml) htmlpart = MIMEText(bodyhtml.encode('UTF-8'), 'html', 'UTF-8') plainpart = MIMEText(bodyplain.encode('UTF-8'), 'plain', 'UTF-8') mail.attach(plainpart) mail.attach(htmlpart) recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(recipients, mail)
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 _pop_category_section(self, profile, element, section): categories = [item.text.strip() for item in element.iterchildren(self.NS_PREFIX + 'item')] root = find_site(profile) category_group = root['people'].categories[section] category_names = dict([(v.sync_id, k) for k,v in category_group.items()]) profile.categories[section] = [category_names[id] for id in categories]
def __call__(self, v): if not v: return site = find_site(self.context) try: target = find_resource(site, v) except KeyError, e: raise Invalid("Path not found: %s" % v)
def __init__(self, context): site = find_site(context) legal = site.get('legal') if legal is not None: self.terms_and_conditions = legal.text privacy = site.get('privacy') if privacy is not None: self.privacy_statement = privacy.text
def parse_report(people, elem): from karl.views.peopledirectory import COLUMNS name, title = name_and_title(elem) link_title = elem.get('link-title', title) css_class = elem.get('class', 'general') report = PeopleReport(title, link_title, css_class) categories = people.get('categories', {}) for e in elem.findall('filter'): f_name = e.get('name') typ = e.get('type') values = e.get('values', '').split() if typ in ('category', 'groups') and not values: raise ParseError("No values given", e) if typ == 'category': category = e.get('category') if category is None: raise ParseError("No category given", e) pc = categories.get(category) if pc is None: raise ParseError("No such category defined", e) for v in values: if v not in pc: raise ParseError("No such category value: %s" % v, e) report[category] = PeopleReportCategoryFilter(tuple(values)) elif typ == 'groups': report[f_name] = PeopleReportGroupFilter(tuple(values)) elif typ == 'is_staff': include_staff = report.get('include_staff', False) report[f_name] = PeopleReportIsStaffFilter(include_staff) else: raise ParseError("Unknown filter type", e) mlist_elem = elem.find('mailinglist') if mlist_elem is not None: mlist = report['mailinglist'] = PeopleReportMailingList() short_address = mlist_elem.get('short_address') if short_address is not None: if short_address in find_site(people).list_aliases: raise ParseError("Duplicate short address: %s" % short_address, mlist_elem) mlist.short_address = short_address columns = None e = elem.find('columns') if e is not None: columns = e.get('names', '').split() if not columns: columns = e.get('ids', '').split() # BBB if not columns: raise ParseError("No columns given", elem) for colid in columns: if not colid in COLUMNS: raise ParseError("No such column defined: %s" % colid, e) report.columns = tuple(columns) return name, report
def site_announcement(context, request): site = find_site(context) body = None if hasattr(site, 'site_announcement'): body = site.site_announcement return dict( show=True if body else False, body=body, )
def parse_report(people, elem): from karl.views.peopledirectory import COLUMNS name, title = name_and_title(elem) link_title = elem.get("link-title", title) css_class = elem.get("class", "general") report = PeopleReport(title, link_title, css_class) categories = people.get("categories", {}) for e in elem.findall("filter"): f_name = e.get("name") typ = e.get("type") values = e.get("values", "").split() if typ in ("category", "groups") and not values: raise ParseError("No values given", e) if typ == "category": category = e.get("category") if category is None: raise ParseError("No category given", e) pc = categories.get(category) if pc is None: raise ParseError("No such category defined", e) for v in values: if v not in pc: raise ParseError("No such category value: %s" % v, e) report[category] = PeopleReportCategoryFilter(tuple(values)) elif typ == "groups": report[f_name] = PeopleReportGroupFilter(tuple(values)) elif typ == "is_staff": include_staff = report.get("include_staff", False) report[f_name] = PeopleReportIsStaffFilter(include_staff) else: raise ParseError("Unknown filter type", e) mlist_elem = elem.find("mailinglist") if mlist_elem is not None: mlist = report["mailinglist"] = PeopleReportMailingList() short_address = mlist_elem.get("short_address") if short_address is not None: if short_address in find_site(people).list_aliases: raise ParseError("Duplicate short address: %s" % short_address, mlist_elem) mlist.short_address = short_address columns = None e = elem.find("columns") if e is not None: columns = e.get("names", "").split() if not columns: columns = e.get("ids", "").split() # BBB if not columns: raise ParseError("No columns given", elem) for colid in columns: if not colid in COLUMNS: raise ParseError("No such column defined: %s" % colid, e) report.columns = tuple(columns) return name, report
def _get_in_group(context, group): if context.__class__ == Profile: site = find_site(context) user = site.users.get_by_id(context.__name__) if not user: return False if 'group.KarlStaff' in user['groups']: return True return False
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 _pop_category_section(self, profile, element, section): categories = [ item.text.strip() for item in element.iterchildren(self.NS_PREFIX + 'item') ] root = find_site(profile) category_group = root['people']['categories'][section] category_names = dict([(v.sync_id, k) for k, v in category_group.items()]) profile.categories[section] = [category_names[id] for id in categories]
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 add_mailinglist(obj, event): # When this handler is called while loading a peopleconf configuration, # this will get called before the maillist has been added to the site, # so we won't actually have a path to the site. In this case we'll get # back a report object that doesn't have a 'list_aliases' attribute. We # safely do nothing here, since the peopleconf loader will go back and # add the aliases when it has finished loading. site = find_site(obj) aliases = getattr(site, 'list_aliases', None) if aliases is not None: aliases[obj.short_address] = resource_path(obj.__parent__)
def __call__(self, v): if not v: return site = find_site(self.context) try: target = find_resource(site, v) except KeyError: raise Invalid("Path not found: %s" % v) else: if target is site: raise Invalid("Path must not point to the site root")
def site_announcement_view(context, request): """ Edit the text of the site announcement, which will be displayed on every page for every user of the site. """ if "submit-site-announcement" in request.params: site = find_site(context) annc = request.params.get("site-announcement-input", "").strip() if annc: # we only take the content of the first <p> tag, with # the <p> tags stripped paramatcher = re.compile("<[pP]\\b[^>]*>(.*?)</[pP]>") match = paramatcher.search(annc) if match is not None: annc = match.groups()[0] site.site_announcement = annc if "remove-site-announcement" in request.params: site = find_site(context) site.site_announcement = u"" api = AdminTemplateAPI(context, request, "Admin UI: Move Content") return dict(api=api, menu=_menu_macro())
def __call__(self, v): if v: context = self.context # Let's not find conflicts with our own selves prev = getattr(context, "short_address", None) if prev == v: # Nothing's changed, no need to check return root = find_site(context) if v in root.list_aliases: raise Invalid("'short_address' is already in use by another mailing list.")
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 terms_and_conditions(self): site = find_site(self.context) offices = site.get('offices') if not offices: return self.tc_default_text files = offices.get('files') if not files: return self.tc_default_text tc = files.get('terms_and_conditions', None) if tc: return tc.text else: return self.tc_default_text
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 privacy_statement(self): site = find_site(self.context) offices = site.get('offices') if not offices: return self.ps_default_text files = offices.get('files', None) if not files: return self.ps_default_text ps = files.get('privacy_statement', None) if ps: return ps.text else: return self.ps_default_text
def __call__(self, v): if v: context = self.context # Let's not find conflicts with our own selves prev = getattr(context, 'short_address', None) if prev == v: # Nothing's changed, no need to check return root = find_site(context) if v in root.list_aliases: raise Invalid( "'short_address' is already in use by another mailing list.")
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 _get_common_email_info(community, community_href): info = {} site = find_site(community) info['system_name'] = get_setting(site, 'title') info['system_email_domain'] = get_setting(community, 'system_email_domain') info['from_name'] = '%s invitation' % info['system_name'] info['from_email'] = 'invitation@%s' % info['system_email_domain'] info['c_title'] = community.title info['c_description'] = community.description info['c_href'] = community_href info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email']) return info
def unlock_profiles_view(context, request): site = find_site(context) if 'submit' in request.params: unlock = request.params.getall('unlock-profiles') for profile_id in unlock: site.login_tries[profile_id] = 8 locked = [p[0] for p in site.login_tries.items() if p[1] < 1] api = AdminTemplateAPI(request.context, request, 'Admin UI: Unlock Accounts') return { 'api': api, 'locked': locked, 'menu': _menu_macro(), }
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 restricted_access(self, context, principals): request = get_current_request() restricted = False site = find_site(context) whitelist = getattr(site, 'access_whitelist', []) blacklist = getattr(site, 'access_blacklist', []) is_admin = u'group.KarlAdmin' in principals profile = self._get_profile(context, principals) if (whitelist or blacklist) and not is_admin: if profile and '@' in profile.email: domain = '@%s' % profile.email.split('@')[1] if domain in blacklist: restricted = True for principal in principals: if principal in blacklist: restricted = True break if whitelist: white = False if profile and '@' in profile.email: domain = '@%s' % profile.email.split('@')[1] if domain in whitelist: white = True for principal in principals: if principal in whitelist: white = True break if not white: restricted = True if restricted: request.session['access_blacklisted'] = True # piggyback password expiration here if profile and profile.auth_method.lower() == 'password': expiration_date = profile.password_expiration_date if expiration_date and expiration_date < datetime.utcnow(): url = request.resource_url(profile, 'change_password.html', query={'password_expired': 'true'}) # only allow change password page if expired if request.url != url: restricted = True request.session['change_url'] = url request.session['password_expired'] = True return restricted