Beispiel #1
0
def table_view(request):
    can_i_edit = has_permission('edit', request.context, request)
    can_i_edit = isinstance(can_i_edit, ACLAllowed)
    user_id = authenticated_userid(request)

    dbsession = DBSession()
    card, user = None, None
    try:
        card = dbsession.query(Cards).filter_by(id=request.matchdict['id']).one()
        user = dbsession.query(User).filter_by(id=user_id).one() if can_i_edit else None
        result = card.as_json_dict()
    except NoResultFound:
        result = {'success': False, 'msg': 'Результатов, соответствующих запросу, не найдено'}

    if not can_i_edit:
        # обнулим координаты перед показом
        result['lat'] = 0
        result['lon'] = 0

    if isinstance(has_permission('admin', request.context, request), ACLAllowed):
        is_editable = True
    else:
        is_editable = card.inserter == user.person_id if user else False

    dbsession.close()
    return {'data': result, 'editable': is_editable, 'success': True}
Beispiel #2
0
def get_profile_actions(profile, request):
    profile_url = request.resource_url(profile)
    actions = []
    same_user = (authenticated_userid(request) == profile.__name__)
    if has_permission('administer', profile, request):
        actions.append(('Edit', '%sadmin_edit_profile.html' % profile_url))
    elif same_user:
        actions.append(('Edit', '%sedit_profile.html' % profile_url))
    if same_user:
        actions.append(('Manage Communities', 'manage_communities.html'))
        actions.append(('Manage Tags', 'manage_tags.html'))
    if has_permission('administer', profile, request):
        actions.append(('Advanced', '%sadvanced.html' % profile_url))
    if request.cookies.get('ux2') == 'true':
        if same_user:
            actions.append(('Deactivate My Account', 'javascript:deactivate()'))
        if has_permission('administer', profile, request) and not same_user:
            users = find_users(profile)
            userid = profile.__name__
            user = users.get_by_id(userid)
            if user is not None:
                is_active = True
            else:
                is_active = False
            if is_active:
                actions.append(('Deactivate This User', 'javascript:deactivate()'))
            if not is_active:
                actions.append(('Reactivate This User', 'javascript:reactivate()'))
    return actions
Beispiel #3
0
def navbar(context, request):
    def nav_item(name, url, icon=None):
        from phoenix.utils import root_path

        active = root_path(request.current_route_path()) == root_path(url)
        return dict(name=name, url=url, active=active, icon=icon)

    items = []
    if has_permission("edit", request.context, request):
        items.append(nav_item("Processes", request.route_path("processes")))
    if has_permission("submit", request.context, request):
        items.append(nav_item("Wizard", request.route_path("wizard")))
        items.append(nav_item("Monitor", request.route_path("monitor")))

    subitems = []
    if has_permission("edit", request.context, request):
        subitems.append(nav_item("Profile", request.route_path("profile", tab="account"), icon="fa fa-user"))
        subitems.append(nav_item("Dashboard", request.route_path("dashboard", tab="jobs"), icon="fa fa-dashboard"))
    if has_permission("admin", request.context, request):
        subitems.append(nav_item("Settings", request.route_path("settings"), icon="fa fa-wrench"))

    login = "******" in request.current_route_url()

    username = None
    try:
        user = get_user(request)
        if user:
            username = user.get("name")
    except:
        logger.exception("could not get username")

    return dict(title="Phoenix", items=items, subitems=subitems, username=username, login=login)
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
Beispiel #5
0
def table_view(request):
    can_i_edit = has_permission('edit', request.context, request)
    can_i_edit = isinstance(can_i_edit, ACLAllowed)
    user_id = authenticated_userid(request)

    try:
        model = table_by_name(request.matchdict['table'])
    except KeyError:
        return {'success': False, 'msg': 'Ошибка: отсутствует таблица с указанным именем'}
        
    dbsession = DBSession()
    try:
        entity = dbsession.query(model).filter_by(id=request.matchdict['id']).one()
        user = dbsession.query(User).filter_by(id=user_id).one() if can_i_edit else None
        result = {'data': entity.as_json_dict(), 'success': True}
    except NoResultFound:
        result = {'success': False, 'msg': 'Результатов, соответствующих запросу, не найдено'}

    if hasattr(entity, 'inserter'):
        if isinstance(has_permission('admin', request.context, request), ACLAllowed):
            is_editable = True
        else:
            is_editable = entity.inserter == user.person_id if user else False
    else:
        is_editable = True
    result['editable'] = is_editable

    dbsession.close()
    return result
Beispiel #6
0
def show_collection(request):
    user = get_user(request)
    collection_id = request.matchdict['collection_id']
    collection = DBSession.query(Collection).get(collection_id)
    assets = collection.assets
    page_assets, page_screenshots = [], {}
    for asset in assets:
        derivatives = asset.derivatives
        transcode_matches = [d.path for d in derivatives if d.derivative_type == 'transcode.480.mp4']
        screenshot_matches = [d.path for d in derivatives if d.derivative_type == 'screenshot.180.gif']
        thumbnail_matches = [d.path for d in derivatives if d.derivative_type == 'thumbnail.180.png']
        if transcode_matches and screenshot_matches and thumbnail_matches:
            transcode = transcode_matches[0]
            screenshot = screenshot_matches[0]
            thumbnail = thumbnail_matches[0]
            page_assets.append(asset)
            asset.screenshot = screenshot
            asset.thumbnail = thumbnail
    grant = DBSession.query(CollectionGrant).filter(CollectionGrant.collection_id==collection_id).filter(CollectionGrant.user_id==user.id).first()
    if user.superuser:
        admin_collections = DBSession.query(Collection).filter(Collection.active==True).all()
    else:
        admin_collections = DBSession.query(Collection).join(CollectionGrant).filter(CollectionGrant.user_id==user.id).filter(CollectionGrant.grant_type=='admin').filter(Collection.active==True).all()
    admin_collections = [c for c in admin_collections if c.id != collection_id]
    return {
      'collection' : collection,
      'page_assets' : page_assets,
      'base_media_url' : Config.BASE_MEDIA_URL,
      'user' : user,
      'show_admin_link' : has_permission('admin', request.context, request),
      'show_asset_checkboxes' : has_permission('admin', request.context, request),
      'admin_collections' : admin_collections,
    }
Beispiel #7
0
def list_collections(request):
    user = get_user(request)
    if user.superuser:
        collections = DBSession.query(Collection, func.count(Asset.id)) \
                               .outerjoin(Asset) \
                               .group_by(Collection.id) \
                               .order_by(Collection.name) \
                               .filter(Collection.active==True) \
                               .all()
        collections = [(collection, count, True) for collection, count in collections]
    else:
        collections = DBSession.query(Collection, func.count(Asset.id), func.max(CollectionGrant.grant_type)) \
                               .outerjoin(Asset) \
                               .group_by(Collection.id) \
                               .order_by(Collection.name) \
                               .join(CollectionGrant) \
                               .filter(CollectionGrant.user_id==user.id) \
                               .filter(Collection.active==True) \
                               .all()
        collections = [(collection, count, grant_type=='admin') for collection, count, grant_type in collections]
    return {
      'collections' : collections,
      'user' : user,
      'show_add_collection_link' : has_permission('admin', request.context, request),
      'is_user_admin' : has_permission('admin', request.context, request),
    }
Beispiel #8
0
def do_approve(request):
    APPROVE_THREDHOLD = 10
    
    user_id = request.matchdict['user_id']
    try:
        user = models.User.objects.with_id(user_id)
    except Exception as e:
        return HTTPFound(location=request.route_path('manager.users.approve'))
    
    
    approver = models.Approver(user=request.user,
                               ip_address=request.environ.get('REMOTE_ADDR'))
    user.approvers.append(approver)
    user.save()
    
    if len(user.approvers) >= APPROVE_THREDHOLD \
        or has_permission('admin', request.context, request)\
        or has_permission('moderator', request.context, request):
        
        user.status = 'activate'
        role = user.get_role('anonymous')
        user.roles.remove(role)
        role = models.Role.objects(name='member').first()
        user.roles.append(role)
        user.save()
    
    return HTTPFound(location=request.route_path('manager.users.approve'))
Beispiel #9
0
 def models(self, **kwargs):
     """Models index page"""
     request = self.request
     models = {}
     if isinstance(request.models, list):
         for model in request.models:
             if has_permission('view', model, request):
                 key = model.__name__
                 models[key] = request.fa_url(key, request.format)
     else:
         for key, obj in request.models.__dict__.iteritems():
             if not key.startswith('_'):
                 if Document is not None:
                     try:
                         if issubclass(obj, Document):
                             if has_permission('view', obj, request):
                                 models[key] = request.fa_url(key, request.format)
                             continue
                     except:
                         pass
                 try:
                     class_mapper(obj)
                 except:
                     continue
                 if not isinstance(obj, type):
                     continue
                 if has_permission('view', obj, request):
                     models[key] = request.fa_url(key, request.format)
     if kwargs.get('json'):
         return models
     return self.render(models=models)
Beispiel #10
0
def get_admin_menus(request):
    """
        Build the admin menu
    """
    menu = Menu()

    if has_permission("admin", request.context, request):
        href = request.route_path("admin_index")
        menu.add_item(u"Configuration", icon="fa fa-cogs", href=href)

    documents = DropDown(label=u"Documents")
    href = request.route_path("invoices")
    documents.add_item(u"Factures", icon="fa fa-file", href=href)
    href = request.route_path('expenses')
    documents.add_item(u'Notes de frais', icon='fa fa-file-o', href=href)

    menu.add(documents)

    if has_permission("admin", request.context, request):
        treasury = DropDown(label=u"Comptabilité")

        href = request.route_path("sage_invoice_export")
        treasury.add_item(
            u"Export des factures",
            icon="fa fa-edit",
            href=href
        )

        href = request.route_path("sage_expense_export")
        treasury.add_item(
            u"Export des notes de frais",
            icon="fa fa-credit-card",
            href=href
        )
        href = request.route_path("admin_treasury_all")
        treasury.add_item(
            u"Bulletins de salaire",
            icon="fa fa-send-o",
            href=href
        )

        menu.add(treasury)

    accompagnement = DropDown(label=u"Accompagnement")

    href = request.route_path('activities')
    accompagnement.add_item(u"Rendez-vous", href=href, icon="fa fa-calendar")

    href = request.route_path('workshops')
    accompagnement.add_item(u"Ateliers", href=href, icon="fa fa-slideshare")

    menu.add(accompagnement)

    href = request.route_path('userdatas')
    menu.add_item(u"Gestion sociale", href=href, icon="fa fa-users")

    href = request.route_path("holidays")
    menu.add_item(u"Congés", icon="fa fa-space-shuttle", href=href)
    return menu
Beispiel #11
0
def dyn_ticket_uwiz_update(params, request):
	tid = int(params['ticketid'])
	del params['ticketid']
	sess = DBSession()
	model = ExtModel(Ticket)
	ticket = sess.query(Ticket).get(tid)
	if ticket is None:
		raise KeyError('Invalid ticket ID')

	for param in ('tstid', 'toid', 'name', 'descr'):
		if param in params:
			del params[param]

#	TODO: ENTITIES_LIST
	if not has_permission('TICKETS_CHANGE_STATE', request.context, request):
		if 'ttrid' in params:
			del params['ttrid']
	if not has_permission('TICKETS_CHANGE_FLAGS', request.context, request):
		if 'flags' in params:
			del params['flags']
#	TODO: USERS_LIST
#	TODO: GROUPS_LIST

	sess.execute(SetVariable('ticketid', ticket.id))
	if 'ttrid' in params:
		ttr_id = params['ttrid']
		if ttr_id:
			ttr_id = int(ttr_id)
			trans = sess.query(TicketStateTransition).get(ttr_id)
			if trans:
				sess.execute(SetVariable('ttrid', trans.id))
				trans.apply(ticket)
		del params['ttrid']
	if 'show_client' in params:
		show_cl = params['show_client'].lower()
		if show_cl in {'true', '1', 'on'}:
			show_cl = True
		else:
			show_cl = False
		del params['show_client']
	else:
		show_cl = False
	sess.execute(SetVariable('show_client', npbool(show_cl)))
	if ('comments' in params) and has_permission('TICKETS_COMMENT', request.context, request):
		sess.execute(SetVariable('comments', params['comments']))
		del params['comments']
	else:
		sess.execute(SetVariable('comments', None))
	model.set_values(ticket, params, request)
	sess.flush()
	sess.execute(SetVariable('tcid', None))
	return {
		'success' : True,
		'action'  : {
			'do'     : 'close',
			'redraw' : []
		}
	}
Beispiel #12
0
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,
        )
Beispiel #13
0
 def has_permissions(self, permissions):
     """ String or List Allowed """ 
     if isinstance(permissions, list):
         for permission in permissions:
             if has_permission(permission, self, self.request):
                 return True
         return False
     else:
         return has_permission(permissions, self, self.request)
Beispiel #14
0
def reference_outline_view(context, request):

    # Look for moveUp or moveDown in QUERY_STRING, telling us to
    # reorder something
    status_message = None
    subpath = request.params.get('subpath')

    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    user_can_edit = False
    actions = []
    if has_permission('create', context, request):
        addables = get_folder_addables(context, request)
        if addables is not None:
            actions.extend(addables())
    if has_permission('edit', context, request):
        user_can_edit = True
        actions.append(('Edit', 'edit.html'))
        if subpath:
            direction = request.params['direction']
            status_message = move_subpath(context, subpath, direction)
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    layout = layout_provider()

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox=get_tags_client_data(context, request),
        )

    previous, next = get_previous_next(context, request)

    api.status_message = status_message
    return render_to_response(
        'templates/show_referencemanual.pt',
        dict(api=api,
             actions=actions,
             user_can_edit=user_can_edit,
             head_data=convert_to_script(client_json_data),
             tree=getTree(context, request, api),
             backto=backto,
             layout=layout,
             previous_entry=previous,
             next_entry=next),
        request=request,
        )
Beispiel #15
0
    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_newsitem_view(context, request):
    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    previous, next = get_previous_next(context, request)

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    # Display photo
    photo = context.get('photo')
    if photo is not None:
        photo = {
            "url": thumb_url(photo, request, PHOTO_DISPLAY_SIZE),
        }

    # 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_newsitem.pt',
        dict(api=api,
             actions=actions,
             attachments=fetch_attachments(context['attachments'], request),
             formfields=api.formfields,
             head_data=convert_to_script(client_json_data),
             backto=backto,
             previous=previous,
             next=next,
             old_layout=layout,
             photo=photo),
        request=request,
        )
Beispiel #17
0
def get_profile_actions(profile, request):
    actions = []
    same_user = (authenticated_userid(request) == profile.__name__)
    if has_permission('administer', profile, request):
        actions.append(('Edit', 'admin_edit_profile.html'))
    elif same_user:
        actions.append(('Edit', 'edit_profile.html'))
    if same_user:
        actions.append(('Manage Communities', 'manage_communities.html'))
        actions.append(('Manage Tags', 'manage_tags.html'))
    if has_permission('administer', profile, request):
        actions.append(('Advanced', 'advanced.html'))
    return actions
Beispiel #18
0
def GetSaleItems(request):
    print "SaleItems requested!"
    can_create = False
    try:
        items = DBSession().query(SaleItem).all()
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    print has_permission("create_items", request.context, request)
    if (isinstance(has_permission("create_items", request.context, request),ACLAllowed)):
        print "Can create new items: true"
        can_create = True

    return {"items" : items, "can_create": can_create}
Beispiel #19
0
def show_community_view(context, request):
    assert ICommunity.providedBy(context), str(type(context))

    user = authenticated_userid(request)
    page_title = 'View Community ' + context.title
    api = TemplateAPI(context, request, page_title)

    # provide client data for rendering current tags in the tagbox
    tagquery = getMultiAdapter((context, request), ITagQuery)
    client_json_data = {'tagbox': {'docid': tagquery.docid,
                                   'records': tagquery.tagswithcounts,
                                  },
                       }

    # add tagbox to template
    layout = request.layout_manager.layout

    # inject tagbox data to panel header data
    panel_data = layout.head_data['panel_data']
    panel_data['tagbox'] = client_json_data['tagbox']

    # Filter the actions based on permission
    actions = []
    if has_permission(MODERATE, context, request):
        actions.append(('Edit', 'edit.html'))

    # If user has permission to see this view then has permission to join.
    if not(user in context.member_names or user in context.moderator_names):
        actions.append(('Join', 'join.html'))

    if has_permission(DELETE_COMMUNITY, context, request):
        actions.append(('Delete', 'delete.html'))

    if has_permission(ADMINISTER, context, request):
        actions.append(('Advanced', 'advanced.html'))

    recent_items = []
    recent_items_batch = get_recent_items_batch(context, request)
    for item in recent_items_batch["entries"]:
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        recent_items.append(adapted)

    feed_url = resource_url(context, request, "atom.xml")

    return {'api': api,
            'actions': actions,
            'recent_items': recent_items,
            'batch_info': recent_items_batch,
            'head_data': convert_to_script(client_json_data),
            'feed_url': feed_url
           }
Beispiel #20
0
def show_wikipage_view(context, request):
    layout = request.layout_manager.layout
    is_front_page = (context.__name__ == 'front_page')
    if is_front_page:
        community = find_interface(context, ICommunity)
        layout.page_title = '%s Community Wiki Page' % community.title
        backto = False
    else:
        layout.page_title = context.title
        backto = {
            'href': resource_url(context.__parent__, request),
            'title': context.__parent__.title,
            }

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', resource_url(context, request, 'edit.html')))
    if has_permission('delete', context, request) and not is_front_page:
        actions.append(('Delete', resource_url(context, request, 'delete.html')))
    repo = find_repo(context)
    show_trash = False
    if not find_interface(context, IIntranets):
        if repo is not None and has_permission('edit', context, request):
            actions.append(('History', resource_url(context, request, 'history.html')))
            show_trash = True
    if has_permission('administer', context, request):
        actions.append(('Advanced', resource_url(context, request, 'advanced.html')))

    api = TemplateAPI(context, request, layout.page_title)

    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    panel_data = layout.head_data['panel_data']
    panel_data['tagbox'] = client_json_data['tagbox']
    layout.add_portlet('recent_activity')

    wiki = find_interface(context, IWiki)
    feed_url = resource_url(wiki, request, "atom.xml")
    return dict(
        api=api,
        actions=actions,
        head_data=convert_to_script(client_json_data),
        feed_url=feed_url,
        backto=backto,
        is_front_page=is_front_page,
        show_trash=show_trash,
        lock_info=lock.lock_info_for_view(context, request),
        )
Beispiel #21
0
 def items(self):
     if not self._items:
         request = self.request
         self._items = OrderedDict()
         maps = deepcopy(mapping_apps)
         is_useradmin = has_permission(P['global_useradmin'], self, request)
         is_authadmin = has_permission(P['global_authadmin'], self, request)
         if is_useradmin:
             maps['auths'] = AuthenticationBackends
         if is_authadmin:
             maps['users'] = Users
         for item in maps:
             self._items[item] = maps[item](parent=self, name=item)
     return self._items
Beispiel #22
0
def users_manager(request):
    if not security.has_permission('admin', request.context, request):
        raise exc.HTTPForbidden()

    session = DBSession()
    users = session.query(User).options(joinedload('person')).all()
    session.close()

    return {
        'title': u'Управление пользователями',
        'users': users,
        'is_auth': security.authenticated_userid(request),
        'is_admin': security.has_permission('admin', request.context, request)
    }
Beispiel #23
0
def get_profile_actions(profile, request):
    profile_url = request.resource_url(profile)
    actions = []
    same_user = (authenticated_userid(request) == profile.__name__)
    if has_permission('administer', profile, request):
        actions.append(('Edit', '%sadmin_edit_profile.html' % profile_url))
    elif same_user:
        actions.append(('Edit', '%sedit_profile.html' % profile_url))
    if same_user:
        actions.append(('Community Alerts and Memberships', 'manage_communities.html'))
        actions.append(('Manage Tags', 'manage_tags.html'))
    if has_permission('administer', profile, request):
        actions.append(('Advanced', '%sadvanced.html' % profile_url))
    return actions
Beispiel #24
0
def reference_viewall_view(context, request):

    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    actions = []
    if has_permission('create', context, request):
        addables = get_folder_addables(context, request)
        if addables is not None:
            actions.extend(addables())
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    old_layout = layout_provider('intranet')

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    previous, next = get_previous_next(context, request, 'view_all.html')

    intranet = find_intranet(context)
    if intranet is not None:
        ux2_layout = request.layout_manager.layout
        ux2_layout.section_style = "none"

    return render_to_response(
        'templates/viewall_referencemanual.pt',
        dict(api=api,
             actions=actions,
             head_data=convert_to_script(client_json_data),
             tree=getTree(context, request, api),
             backto=backto,
             old_layout=old_layout,
             previous_entry=previous,
             next_entry=next),
        request=request,
        )
Beispiel #25
0
    def mode_for(self, name):
        """Calculate mode by checking permission defined in
        ``self.attribute_permissions`` for attribute ``name`` against model.

        If no permissions defined for attribute name, return
        ``self.attribute_default_mode``
        """
        permissions = self.attribute_permissions.get(name)
        if not permissions:
            permissions = self.attribute_default_permissions
        if has_permission(permissions[0], self.model, self.request):
            return 'edit'
        if has_permission(permissions[1], self.model, self.request):
            return 'display'
        return 'skip'
Beispiel #26
0
Datei: page.py Projekt: hj91/karl
def show_page_view(context, request):

    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    previous, next = get_previous_next(context, request)

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    # Get a layout
    community = find_community(context)
    layout_provider = get_layout_provider(context, request)
    if community is not None:
        layout = layout_provider('community')
    else:
        layout = layout_provider('generic')

    ux2_layout = request.layout_manager.layout
    ux2_layout.section_style = "none"
    return render_to_response(
        'templates/show_page.pt',
        dict(api=api,
             actions=actions,
             attachments=fetch_attachments(context['attachments'], request),
             formfields=api.formfields,
             head_data=convert_to_script(client_json_data),
             backto=backto,
             previous_entry=previous,
             next_entry=next,
             old_layout=layout),
        request = request,
        )
Beispiel #27
0
def show_blogentry_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    client_json_data = dict(
        tagbox=get_tags_client_data(context, request))

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
        }

    comments = get_comment_data(context, context['comments'], api, request)
    comment_form = get_comment_form(context, context['comments'], api, request)

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(
            context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
        )
Beispiel #28
0
def peopledirectory_view(context, request):
    # show the first accessible tab
    for section_id in context.order:
        section = context[section_id]
        if has_permission('view', section, request):
            return HTTPFound(location=resource_url(section, request))
    raise Forbidden("No accessible sections")
Beispiel #29
0
 def prepare(_next, self):
     """Hook after prepare and set expiration widget to
     ``self.form``.
     """
     _next(self)
     cfg = ugm_general(self.model)
     if cfg.attrs["users_account_expiration"] != "True":
         return
     mode = "edit"
     if not has_permission("manage_expiration", self.model.parent, self.request):
         mode = "display"
     if self.action_resource == "edit":
         attr = cfg.attrs["users_expires_attr"]
         unit = int(cfg.attrs["users_expires_unit"])
         value = int(self.model.attrs.get(attr, 0))
         # if format days, convert to seconds
         if unit == 0:
             value *= 86400
     else:
         value = UNSET
     expires_widget = factory(
         "field:label:expiration", name="active", value=value, props={"label": _("active", "Active")}, mode=mode
     )
     save_widget = self.form["save"]
     self.form.insertbefore(expires_widget, save_widget)
Beispiel #30
0
def paste_node(context, request):
    session = DBSession()
    id, action = request.session['kotti.paste']
    item = session.query(Node).get(id)
    if item is not None:
        if action == 'cut':
            if not has_permission('edit', item, request):
                raise Forbidden()
            item.__parent__.children.remove(item)
            context.children.append(item)
            del request.session['kotti.paste']
        elif action == 'copy':
            copy = item.copy()
            name = copy.name
            if not name:  # for root
                name = copy.title
            name = title_to_name(name, blacklist=context.keys())
            copy.name = name
            context.children.append(copy)
        request.session.flash(_(u'${title} pasted.',
                                mapping=dict(title=item.title)), 'success')
    else:
        request.session.flash(_(u'Could not paste node. It does not exist anymore.'), 'error')
    if not request.is_xhr:
        location = resource_url(context, request)
        return HTTPFound(location=location)
Beispiel #31
0
 def has_perm(self, perm):
     return has_permission(perm, self.context, self)
Beispiel #32
0
    def __call__(self):
        context, request = self.context, self.request
        api = AdminTemplateAPI(context, request, 'Admin UI: Send Email')
        admin_email = get_setting(context, 'admin_email')
        system_name = get_setting(context, 'system_name')
        profiles = find_profiles(context)
        admin = profiles[authenticated_userid(request)]
        from_emails = [
            ('self', '%s <%s>' % (admin.title, admin.email)),
            ('admin', '%s Administrator <%s>' % (system_name, admin_email)),
        ]

        if 'send_email' in request.params:
            mailer = getUtility(IMailDelivery)
            group = request.params['to_group']
            users = find_users(context)
            search = ICatalogSearch(context)
            count, docids, resolver = search(interfaces=[IProfile])
            n = 0
            for docid in docids:
                profile = resolver(docid)
                if getattr(profile, 'security_state', None) == 'inactive':
                    continue
                userid = profile.__name__
                if group and not users.member_of_group(userid, group):
                    continue

                message = Message()
                if request.params['from_email'] == 'self':
                    message['From'] = from_emails[0][1]
                    message_from = admin.email
                else:
                    message['From'] = from_emails[1][1]
                    message_from = admin_email
                message['To'] = '%s <%s>' % (profile.title, profile.email)
                message['Subject'] = request.params['subject']
                body = u'<html><body>%s</body></html>' % (
                    request.params['text'])
                message.set_payload(body.encode('UTF-8'), 'UTF-8')
                message.set_type('text/html')

                mailer.send([profile.email], message)
                n += 1

            status_message = "Sent message to %d users." % n
            if has_permission(ADMINISTER, context, request):
                redirect_to = resource_url(
                    context,
                    request,
                    'admin.html',
                    query=dict(status_message=status_message))
            else:
                redirect_to = resource_url(
                    find_communities(context),
                    request,
                    'all_communities.html',
                    query=dict(status_message=status_message))

            return HTTPFound(location=redirect_to)

        return dict(
            api=api,
            menu=_menu_macro(),
            to_groups=self.to_groups,
            from_emails=from_emails,
        )
Beispiel #33
0
 def _callFUT(self, *arg):
     from pyramid.security import has_permission
     return has_permission(*arg)
Beispiel #34
0
def tests_view(request):
    run = request.rundb.get_run(request.matchdict["id"])
    if run is None:
        raise exception_response(404)
    results = request.rundb.get_results(run)
    run["results_info"] = format_results(results, run)
    run_args = [("id", str(run["_id"]), "")]
    if run.get("rescheduled_from"):
        run_args.append(("rescheduled_from", run["rescheduled_from"], ""))

    for name in [
            "new_tag",
            "new_signature",
            "new_options",
            "resolved_new",
            "new_net",
            "base_tag",
            "base_signature",
            "base_options",
            "resolved_base",
            "base_net",
            "sprt",
            "num_games",
            "spsa",
            "tc",
            "threads",
            "book",
            "book_depth",
            "auto_purge",
            "priority",
            "itp",
            "username",
            "tests_repo",
            "info",
    ]:

        if name not in run["args"]:
            continue

        value = run["args"][name]
        url = ""

        if name == "new_tag" and "msg_new" in run["args"]:
            value += "  (" + run["args"]["msg_new"][:50] + ")"

        if name == "base_tag" and "msg_base" in run["args"]:
            value += "  (" + run["args"]["msg_base"][:50] + ")"

        if name == "sprt" and value != "-":
            value = "elo0: %.2f alpha: %.2f elo1: %.2f beta: %.2f state: %s (%s)" % (
                value["elo0"],
                value["alpha"],
                value["elo1"],
                value["beta"],
                value.get("state", "-"),
                value.get("elo_model", "BayesElo"),
            )

        if name == "spsa" and value != "-":
            iter_local = value["iter"] + 1  # assume at least one completed,
            # and avoid division by zero
            A = value["A"]
            alpha = value["alpha"]
            gamma = value["gamma"]
            summary = (
                "Iter: %d, A: %d, alpha %0.3f, gamma %0.3f, clipping %s, rounding %s"
                % (
                    iter_local,
                    A,
                    alpha,
                    gamma,
                    value["clipping"] if "clipping" in value else "old",
                    value["rounding"]
                    if "rounding" in value else "deterministic",
                ))
            params = value["params"]
            value = [summary]
            for p in params:
                value.append([
                    p["name"],
                    "{:.2f}".format(p["theta"]),
                    int(p["start"]),
                    int(p["min"]),
                    int(p["max"]),
                    "{:.3f}".format(p["c"] / (iter_local**gamma)),
                    "{:.3f}".format(p["a"] / (A + iter_local)**alpha),
                ])
        if "tests_repo" in run["args"]:
            if name == "new_tag":
                url = (run["args"]["tests_repo"] + "/commit/" +
                       run["args"]["resolved_new"])
            elif name == "base_tag":
                url = (run["args"]["tests_repo"] + "/commit/" +
                       run["args"]["resolved_base"])
            elif name == "tests_repo":
                url = value

        if name == "spsa":
            run_args.append(("spsa", value, ""))
        else:
            try:
                strval = str(value)
            except:
                strval = value.encode("ascii", "replace")
            if name not in ["new_tag", "base_tag"]:
                strval = html.escape(strval)
            run_args.append((name, strval, url))

    active = 0
    cores = 0
    for task in run["tasks"]:
        if task["active"]:
            active += 1
            cores += task["worker_info"]["concurrency"]
        last_updated = task.get("last_updated", datetime.datetime.min)
        task["last_updated"] = last_updated

    if run["args"].get("sprt"):
        page_title = "SPRT {} vs {}".format(run["args"]["new_tag"],
                                            run["args"]["base_tag"])
    elif run["args"].get("spsa"):
        page_title = "SPSA {}".format(run["args"]["new_tag"])
    else:
        page_title = "{} games - {} vs {}".format(run["args"]["num_games"],
                                                  run["args"]["new_tag"],
                                                  run["args"]["base_tag"])
    return {
        "run":
        run,
        "run_args":
        run_args,
        "page_title":
        page_title,
        "approver":
        has_permission("approve_run", request.context, request),
        "chi2":
        calculate_residuals(run),
        "totals":
        "(%s active worker%s with %s core%s)" %
        (active, ("s" if active != 1 else ""), cores,
         ("s" if cores != 1 else "")),
    }
Beispiel #35
0
def actions(request):
    search_action = request.params.get("action", "")
    search_user = request.params.get("user", "")

    actions_list = []
    for action in request.actiondb.get_actions(100, search_action,
                                               search_user):
        item = {
            "action": action["action"],
            "time": action["time"],
            "username": action["username"],
        }
        if action["action"] == "update_stats":
            item["user"] = ""
            item["description"] = "Update user statistics"
        elif action["action"] == "upload_nn":
            item["user"] = ""
            item["description"] = "Upload " + action["data"]
        elif action["action"] == "block_user":
            item["description"] = ("blocked" if action["data"]["blocked"] else
                                   "unblocked")
            item["user"] = action["data"]["user"]
        elif action["action"] == "modify_run":
            item["run"] = action["data"]["before"]["args"]["new_tag"]
            item["_id"] = action["data"]["before"]["_id"]
            item["description"] = []

            before = action["data"]["before"]["args"]["priority"]
            after = action["data"]["after"]["args"]["priority"]
            if before != after:
                item["description"].append(
                    "priority changed from {} to {}".format(before, after))

            before = action["data"]["before"]["args"]["num_games"]
            after = action["data"]["after"]["args"]["num_games"]
            if before != after:
                item["description"].append(
                    "games changed from {} to {}".format(before, after))

            before = action["data"]["before"]["args"]["throughput"]
            after = action["data"]["after"]["args"]["throughput"]
            if before != after:
                item["description"].append(
                    "throughput changed from {} to {}".format(before, after))

            before = action["data"]["before"]["args"]["auto_purge"]
            after = action["data"]["after"]["args"]["auto_purge"]
            if before != after:
                item["description"].append(
                    "auto-purge changed from {} to {}".format(before, after))

            item["description"] = "modify: " + ", ".join(item["description"])
        else:
            item["run"] = action["data"]["args"]["new_tag"]
            item["_id"] = action["data"]["_id"]
            item["description"] = " ".join(action["action"].split("_"))
            if action["action"] == "stop_run":
                item["description"] += ": {}".format(action["data"].get(
                    "stop_reason", "User stop"))

        actions_list.append(item)

    return {
        "actions": actions_list,
        "approver": has_permission("approve_run", request.context, request),
    }
Beispiel #36
0
    def get_default_buttons(self):
        """ The default buttons content-type hook """
        context = self.context
        request = self.request

        buttons = []
        finish_buttons = []

        if 'tocopy' in request.session:
            finish_buttons.extend([
                {
                    'id': 'copy_finish',
                    'name': 'form.copy_finish',
                    'class': 'btn-primary btn-sdi-act',
                    'value': 'copy_finish',
                    'text': _('Copy here')
                },
                {
                    'id': 'cancel',
                    'name': 'form.copy_finish_cancel',
                    'class': 'btn-danger btn-sdi-act',
                    'value': 'cancel',
                    'text': _('Cancel')
                },
            ])

        if 'tomove' in request.session:
            finish_buttons.extend([{
                'id': 'move_finish',
                'name': 'form.move_finish',
                'class': 'btn-primary btn-sdi-act',
                'value': 'move_finish',
                'text': _('Move here')
            }, {
                'id': 'cancel',
                'name': 'form.move_finish_cancel',
                'class': 'btn-danger btn-sdi-act',
                'value': 'cancel',
                'text': _('Cancel')
            }])

        if finish_buttons:
            buttons.append({'type': 'single', 'buttons': finish_buttons})

        if not 'tomove' in request.session and not 'tocopy' in request.session:

            can_manage = bool(
                has_permission('sdi.manage-contents', context, request))

            def delete_enabled_for(folder, resource, request):
                """
                This function considers a subobject 'deletable' if the user has
                the ``sdi.manage-contents`` permission on ``folder`` or if the
                subobject has a ``__sdi_deletable__`` attribute which resolves
                to a boolean ``True`` value.

                This function honors one subobject hook::
                ``__sdi_deletable__``.  If a subobject has an attribute named
                ``__sdi_deletable__``, it is expected to be either a boolean or
                a callable.  If ``__sdi_deletable__`` is a boolean, the value
                is used verbatim.  If ``__sdi_deletable__`` is a callable, the
                callable is called with two positional arguments: the subobject
                and the request; the result is expected to be a boolean.  If a
                subobject has an ``__sdi_deletable__`` attribute, and its
                resolved value is not ``None``, the delete button will be off
                if it's a boolean False.  If ``__sdi_deletable__`` does not
                exist on a subobject or resolves to ``None``, the delete button
                will be turned off if current user does not have the
                ``sdi.manage-contents`` permission on the ``folder``.
                """
                deletable = getattr(resource, '__sdi_deletable__', None)
                if deletable is not None:
                    if callable(deletable):
                        deletable = deletable(resource, request)
                if deletable is None:
                    deletable = can_manage
                deletable = bool(deletable)  # cast return/attr value to bool
                return deletable

            main_buttons = [{
                'id': 'rename',
                'name': 'form.rename',
                'class': 'btn-default btn-sdi-sel',
                'enabled_for': delete_enabled_for,
                'value': 'rename',
                'text': _('Rename')
            }, {
                'id': 'copy',
                'name': 'form.copy',
                'class': 'btn-default btn-sdi-sel',
                'value': 'copy',
                'text': _('Copy')
            }, {
                'id': 'move',
                'name': 'form.move',
                'class': 'btn-default btn-sdi-sel',
                'enabled_for': delete_enabled_for,
                'value': 'move',
                'text': _('Move')
            }, {
                'id': 'duplicate',
                'name': 'form.duplicate',
                'class': 'btn-default btn-sdi-sel',
                'value': 'duplicate',
                'text': _('Duplicate')
            }]

            buttons.append({'type': 'group', 'buttons': main_buttons})

            delete_buttons = [
                {
                    'id': 'delete',
                    'name': 'form.delete',
                    'class': 'btn-danger btn-sdi-sel',
                    'enabled_for': delete_enabled_for,
                    'value': 'delete',
                    'text': _('Delete')
                },
            ]

            buttons.append({'type': 'group', 'buttons': delete_buttons})

        return buttons
Beispiel #37
0
def tests_view(request):
    run = request.rundb.get_run(request.matchdict['id'])
    results = request.rundb.get_results(run)
    run['results_info'] = format_results(results, run)
    run_args = [('id', str(run['_id']), '')]

    for name in [
            'new_tag', 'new_signature', 'new_options', 'resolved_new',
            'base_tag', 'base_signature', 'base_options', 'resolved_base',
            'sprt', 'num_games', 'spsa', 'tc', 'threads', 'book', 'book_depth',
            'auto_purge', 'priority', 'internal_priority', 'username',
            'tests_repo', 'info'
    ]:

        if not name in run['args']:
            continue

        value = run['args'][name]
        url = ''

        if name == 'new_tag' and 'msg_new' in run['args']:
            value += '  (' + run['args']['msg_new'][:50] + ')'

        if name == 'base_tag' and 'msg_base' in run['args']:
            value += '  (' + run['args']['msg_base'][:50] + ')'

        if name == 'sprt' and value != '-':
            value = 'elo0: %.2f alpha: %.2f elo1: %.2f beta: %.2f state: %s' % \
                    (value['elo0'], value['alpha'], value['elo1'], value['beta'],
                     value.get('state', '-'))

        if name == 'spsa' and value != '-':
            iter_local = value[
                'iter'] + 1  # assume at least one completed, and avoid division by zero
            params = ['param: %s, best: %.2f, start: %.2f, min: %.2f, max: %.2f, c %f, a %f' % \
                      (p['name'], p['theta'], p['start'], p['min'], p['max'],
                       p['c'] / (iter_local ** value['gamma']),
                       p['a'] / (value['A'] + iter_local) ** value['alpha'])
                      for p in value['params']]
            value = 'Iter: %d, A: %d, alpha %f, gamma %f, clipping %s, rounding %s\n%s' \
                    % (iter_local, value['A'], value['alpha'], value['gamma'],
                    value['clipping'] if 'clipping' in value else 'old',
                    value['rounding'] if 'rounding' in value else 'deterministic',
                    '\n'.join(params))

        if 'tests_repo' in run['args']:
            if name == 'new_tag':
                url = run['args']['tests_repo'] + '/commit/' + run['args'][
                    'resolved_new']
            elif name == 'base_tag':
                url = run['args']['tests_repo'] + '/commit/' + run['args'][
                    'resolved_base']
            elif name == 'tests_repo':
                url = value

        try:
            strval = str(value)
        except:
            strval = value.encode('ascii', 'replace')
        run_args.append((name, strval, url))

    active = 0
    cores = 0
    for task in run['tasks']:
        if task['active']:
            active += 1
            cores += task['worker_info']['concurrency']
        last_updated = task.get('last_updated', datetime.datetime.min)
        task['last_updated'] = last_updated

    return {
        'run':
        run,
        'run_args':
        run_args,
        'chi2':
        calculate_residuals(run),
        'approver':
        has_permission('approve_run', request.context, request),
        'totals':
        '(%s active worker%s with %s core%s)' %
        (active, ('s' if active != 1 else ''), cores,
         ('s' if cores != 1 else ''))
    }
Beispiel #38
0
def can_modify_run(request, run):
    return run['args']['username'] == authenticated_userid(
        request) or has_permission('approve_run', request.context, request)
Beispiel #39
0
Datei: blog.py Projekt: zagy/karl
def show_blogentry_view(context, request):

    post_url = resource_url(context, request, "comments", "add_comment.html")
    karldates = getUtility(IKarlDates)
    profiles = find_profiles(context)
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    # Convert blog comments into a digestable form for the template
    comments = []

    page_title = context.title
    api = TemplateAPI(context, request, page_title)
    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 = api.static_url + "/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'])

    client_json_data = dict(tagbox=get_tags_client_data(context, request), )

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
    }

    # manually construct formish comment form
    controller = AddCommentFormController(context['comments'], request)
    form_schema = schemaish.Structure()
    form_fields = controller.form_fields()
    for fieldname, field in form_fields:
        form_schema.add(fieldname, field)
    form_action_url = '%sadd_comment.html' % resource_url(
        context['comments'], request)
    comment_form = Form(form_schema,
                        add_default_action=False,
                        name='save',
                        action_url=form_action_url)
    form_defaults = controller.form_defaults()
    comment_form.defaults = form_defaults
    request.form_defaults = form_defaults

    form_actions = [
        FormAction('submit', 'submit'),
        FormAction('cancel', 'cancel', validate=False)
    ]
    for action in form_actions:
        comment_form.add_action(action.name, action.title)

    widgets = controller.form_widgets(form_fields)
    for name, widget in widgets.items():
        comment_form[name].widget = widget

    # this is for enable imagedrawer for adding blog comments
    api.karl_client_data['text'] = dict(enable_imagedrawer_upload=True, )
    # ux2
    layout = request.layout_manager.layout
    panel_data = layout.head_data['panel_data']
    panel_data['tinymce'] = api.karl_client_data['text']
    panel_data['tagbox'] = client_json_data['tagbox']

    # add portlets to template
    layout.add_portlet('blog_archive')
    # editor width and height for comments textarea
    layout.tinymce_height = 250
    layout.tinymce_width = 700

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(context['attachments'],
                                      request),  # deprecated ux1
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
    )
Beispiel #40
0
 def has_permission(self, permission):
     return has_permission(permission, self.context, self.request)
Beispiel #41
0
Datei: blog.py Projekt: zagy/karl
def show_blog_view(context, request):
    # add portlets to template
    layout = request.layout_manager.layout
    layout.add_portlet('blog_archive')

    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])

        def filter_func(name, item):
            created = item.created
            return created.year == year and created.month == month

        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
    else:
        filter_func = None
        page_title = 'Blog'

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(('Add Blog Entry',
                        request.resource_url(context, 'add_blogentry.html')), )

    batch = get_container_batch(context,
                                request,
                                filter_func=filter_func,
                                interfaces=[IBlogEntry],
                                sort_index='creation_date',
                                reverse=True)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for entry in batch['entries']:
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
        }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    community = find_community(context)
    mailin_addr = '%s@%s' % (community.__name__, system_email_domain)
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,  # Deprecated UX1
        feed_url=feed_url,
        batch_info=batch,
        security_states=security_states,
        mailin_addr=mailin_addr,  # UX2
    )
Beispiel #42
0
def deferred_financial_year_widget(node, kw):
    request = kw['request']
    if has_permission('manage', request.context, request):
        return deform.widget.TextInputWidget(mask='9999')
    else:
        return deform.widget.HiddenWidget()
Beispiel #43
0
    def __init__(self, context, request, page_title=None):
        self.settings = get_settings() or {}
        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.js_devel_mode = self.settings.get('js_devel_mode', None)
        self.read_only = self.settings.get('read_only', False)
        self.static_url = '%s/static/%s' % (
            app_url, request.registry.settings.get('static_rev'))

        # 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.settings.get('system_name', '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')
        self.site_announcement = getattr(site, 'site_announcement', '')
        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.'

        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, )

        # propagate the head data to the client
        d = self.karl_client_data['kaltura'] = dict(self.kaltura_info)
        # remove secrets if needed
        if 'session_url' in d:
            # server side session management, do not send secrets to client
            del d['user_secret']
            del d['admin_secret']
Beispiel #44
0
def user(request):
    userid = authenticated_userid(request)
    if not userid:
        request.session.flash("Please login")
        return HTTPFound(location=request.route_url("login"))
    user_name = request.matchdict.get("username", userid)
    profile = user_name == userid
    if not profile and not has_permission("approve_run", request.context,
                                          request):
        request.session.flash("You cannot inspect users", "error")
        return HTTPFound(location=request.route_url("tests"))
    user_data = request.userdb.get_user(user_name)
    if "user" in request.POST:
        if profile:

            new_password = request.params.get("password")
            new_password_verify = request.params.get("password2", "")
            new_email = request.params.get("email")

            if len(new_password) > 0:
                if new_password == new_password_verify:
                    strong_password, password_err = password_strength(
                        new_password, user_name, user_data["email"],
                        (new_email if len(new_email) > 0 else None))
                    if strong_password:
                        user_data["password"] = new_password
                        request.session.flash("Success! Password updated")
                    else:
                        request.session.flash(
                            "Error! Weak password: "******"error")
                        return HTTPFound(location=request.route_url("tests"))
                else:
                    request.session.flash(
                        "Error! Matching verify password required", "error")
                    return HTTPFound(location=request.route_url("tests"))

            if len(new_email) > 0 and user_data["email"] != new_email:
                if "@" not in new_email:
                    request.session.flash("Error! Valid email required",
                                          "error")
                    return HTTPFound(location=request.route_url("tests"))
                else:
                    user_data["email"] = new_email
                    request.session.flash("Success! Email updated")

        else:
            user_data["blocked"] = "blocked" in request.POST
            request.userdb.last_pending_time = 0
            request.actiondb.block_user(
                authenticated_userid(request),
                {
                    "user": user_name,
                    "blocked": user_data["blocked"]
                },
            )
            request.session.flash(
                ("Blocked" if user_data["blocked"] else "Unblocked") +
                " user " + user_name)
        request.userdb.save_user(user_data)
        return HTTPFound(location=request.route_url("tests"))
    userc = request.userdb.user_cache.find_one({"username": user_name})
    hours = int(userc["cpu_hours"]) if userc is not None else 0
    return {
        "user": user_data,
        "limit": request.userdb.get_machine_limit(user_name),
        "hours": hours,
        "profile": profile,
    }
Beispiel #45
0
def canEdit(self):
    return has_permission('edit', self, self.request)
Beispiel #46
0
 def __sd_hidden__(self, context, request):
     # Don't show this item in folder contents view unless the viewer
     # has permission to add services in the SDI
     return not has_permission('sdi.add-services', context, request)
Beispiel #47
0
 def _secure(context, request):
     if not has_permission(permission, context, request):
         raise HTTPForbidden('no permission')
     else:
         return view(context, request)
Beispiel #48
0
def reference_outline_view(context, request):

    # Look for moveUp or moveDown in QUERY_STRING, telling us to
    # reorder something
    status_message = None
    subpath = request.params.get('subpath')

    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    user_can_edit = False
    actions = []
    if has_permission('create', context, request):
        addables = get_folder_addables(context, request)
        if addables is not None:
            actions.extend(addables())
    if has_permission('edit', context, request):
        user_can_edit = True
        actions.append(('Edit', 'edit.html'))
        if subpath:
            direction = request.params['direction']
            status_message = move_subpath(context, subpath, direction)
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    old_layout = layout_provider('intranet')

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    previous, next = get_previous_next(context, request)

    intranet = find_intranet(context)
    if intranet is not None:
        ux2_layout = request.layout_manager.layout
        ux2_layout.section_style = "none"

    api.status_message = status_message
    return render_to_response(
        'templates/show_referencemanual.pt',
        dict(api=api,
             actions=actions,
             user_can_edit=user_can_edit,
             head_data=convert_to_script(client_json_data),
             tree=getTree(context, request, api),
             backto=backto,
             old_layout=old_layout,
             previous_entry=previous,
             next_entry=next),
        request=request,
        )
Beispiel #49
0
def can_modify_run(request, run):
    return run["args"]["username"] == authenticated_userid(
        request) or has_permission("approve_run", request.context, request)
Beispiel #50
0
 def default_view(self):
     can_i_edit = has_permission("edit", self.context, self.request)
     return dict(page_title="Site View", can_i_edit=can_i_edit)
Beispiel #51
0
def show_members_view(context, request):
    """Default view of community members (with/without pictures)."""

    page_title = 'Community Members'
    api = TemplateAPI(context, request, page_title)

    # Filter the actions based on permission in the **community**
    community = find_interface(context, ICommunity)
    actions = _get_manage_actions(community, request)

    # Did we get the "show pictures" flag?
    list_view = request.view_name == 'list_view.html'

    pictures_href = request.resource_url(context)
    list_href = request.resource_url(context, 'list_view.html')
    submenu = [
        {
            'label': 'Show Pictures',
            'href': pictures_href,
            'make_link': list_view
        },
        {
            'label': 'Hide Pictures',
            'href': list_href,
            'make_link': not (list_view)
        },
    ]

    profiles = find_profiles(context)
    member_batch = _member_profile_batch(context, request)
    member_entries = member_batch['entries']
    moderator_names = community.moderator_names

    member_info = []
    for i in range(len(member_entries)):
        derived = {}
        entry = member_entries[i]
        derived['title'] = entry.title
        derived['href'] = resource_url(entry, request)
        derived['position'] = entry.position
        derived['organization'] = entry.organization
        derived['phone'] = entry.phone
        derived['department'] = entry.department
        derived['email'] = entry.email
        derived['city'] = entry.location

        photo = entry.get('photo')
        if photo is not None:
            derived['photo_url'] = thumb_url(photo, request,
                                             PROFILE_THUMB_SIZE)
        else:
            derived['photo_url'] = api.static_url + "/images/defaultUser.gif"

        derived['is_moderator'] = entry.__name__ in moderator_names
        # Chameleon's tal:repeat and repeat variable support for
        # things like index is pretty iffy.  Fix the entry info to
        # supply the CSS class information.
        derived['css_class'] = 'photoProfile'
        if derived['is_moderator']:
            derived['css_class'] += ' moderator'
        member_info.append(derived)

    moderator_info = []
    profiles = find_profiles(context)
    for moderator_name in moderator_names:
        if moderator_name in profiles:
            derived = {}
            profile = profiles[moderator_name]
            if not has_permission('view', profile, request):
                continue
            derived['title'] = profile.title
            derived['href'] = resource_url(profile, request)
            moderator_info.append(derived)

    renderer_data = dict(api=api,
                         actions=actions,
                         submenu=submenu,
                         moderators=moderator_info,
                         members=member_info,
                         batch_info=member_batch,
                         hide_pictures=list_view)

    if not list_view:
        renderer_data['rows'] = profile_photo_rows(member_batch['entries'],
                                                   request, api)

    return renderer_data
Beispiel #52
0
class CustomFolderView(object):
    _past_events = None
    past_events_url = None
    future_events_url = None

    def __init__(self, context, request):
        self.context = context
        self.request = request

        searchterm = request.params.get('searchterm', None)
        if searchterm == '':
            searchterm = None
        self.searchterm = searchterm

        year = request.params.get('year', None)
        if year == 'all':
            year = None
        self.year = year

        month = request.params.get('month', None)
        if month == 'all':
            month = None
        self.month = month

    def __call__(self):
        """ Folder contents for the INetworkEvents marker"""
        context = self.context
        request = self.request

        page_title = context.title
        api = TemplateAPI(context, request, page_title)

        # Data for the filter bar, get the list of possible years and months
        this_year = datetime.datetime.now().year
        fb_years = [str(i) for i in range(2007, this_year+1)]
        fb_months = [('1', 'January'), ('2', 'February'), ('3', 'March'),
                     ('4', 'April'), ('5', 'May'), ('6', 'June'),
                     ('7', 'July'), ('8', 'August'), ('9', 'September'),
                     ('10', 'October'), ('11', 'November'), ('12', 'December')]

        # Flatten the search results into ZPT data
        try:
            batch = self._get_batch()
        except ParseError, e:
            api.set_error_message('Error: %s' % e)
            batch = {'entries': (), 'batching_required': False}

        entries = []
        for entry in batch["entries"]:
            info = {}
            info['url'] = resource_url(entry, request)
            info['title'] = entry.title
            info['date'] = self._get_date(entry)
            entries.append(info)

        # Actions and backlink
        actions = []
        if has_permission('create', context, request):
            addables = get_folder_addables(context, request)
            if addables is not None:
                actions.extend(addables())

        if has_permission('edit', context, request):
            actions.append(('Edit', 'edit.html'))

        if has_permission('delete', context.__parent__, request):
            actions.append(('Delete', 'delete.html'))

        if has_permission('administer', context, request):
            # admins see an Advanced action that puts markers on a folder.
            actions.append(('Advanced', 'advanced.html'))

        back_target, extra_path = get_user_home(context, request)
        backto = {
            'href': resource_url(back_target, request, *extra_path),
            'title': getattr(back_target, "title", "Home")
            }

        client_json_data = dict(
            tagbox = get_tags_client_data(context, request),
            )

        # Get a layout
        layout_provider = get_layout_provider(context, request)
        layout = layout_provider('community')

        intranet = find_intranet(self.context)
        intranets = find_intranets(self.context)
        community = find_community(self.context)
        if intranet is not None or community == intranets:
            ux2_layout = self.request.layout_manager.layout
            ux2_layout.section_style = "none"

        return dict(
            api=api,
            actions=actions,
            head_data=convert_to_script(client_json_data),
            backto=backto,
            old_layout=layout,
            entries=entries,
            fb_years=fb_years,
            fb_months=fb_months,
            searchterm=self.searchterm,
            selected_year=self.year,
            selected_month=self.month,
            batch_info=batch,
            past_events_url=self.past_events_url,
            future_events_url=self.future_events_url,
            )
    def _do_route(self, action_name, method_name, params, metadata, trans_id,
                  request):
        """ Performs routing, i.e. calls decorated methods/functions """
        if params is None:
            params = list()
        settings = self.get_method(action_name, method_name)
        permission = settings.get('permission', None)
        ret = {
            "type": "rpc",
            "tid": trans_id,
            "action": action_name,
            "method": method_name,
            "result": None
        }

        callback = settings['callback']

        append_request = settings.get('request_as_last_param', False)
        permission_ok = True
        context = request.root

        prepend = []
        if settings['class']:
            instance = settings['class'](request)
            prepend.append(instance)
            context = instance
        elif append_request:
            params.append(request)

        if settings['metadata']:
            prepend.append(metadata)

        params = prepend + params

        if permission is not None:
            permission_ok = has_permission(permission, context, request)

        try:
            if not permission_ok:
                raise AccessDeniedException("Access denied")
            ret["result"] = callback(*params)
        except Exception as exc:
            ret["type"] = "exception"
            # Let a user defined view for specific exception prevent returning
            # a server error.
            exception_view = render_view_to_response(exc, request)
            if exception_view is not None:
                ret["result"] = exception_view
                return ret

            # Log Error
            LOG.error("%s: %s", str(exc.__class__.__name__), exc)
            LOG.info(traceback.format_exc())

            if self.expose_exceptions:
                ret["result"] = {
                    'error': True,
                    'message': str(exc),
                    'exception_class': str(exc.__class__),
                    'stacktrace': traceback.format_exc()
                }
            else:
                message = 'Error executing {}.{}'.format(
                    action_name, method_name)
                ret["result"] = {'error': True, 'message': message}

            if self.debug_mode:
                # if pyramid_debugtoolbar is enabled, generate an interactive page
                # and include the url to access it in the ext direct Exception response text
                from pyramid_debugtoolbar.tbtools import get_traceback
                from pyramid_debugtoolbar.utils import EXC_ROUTE_NAME
                import sys
                exc_history = request.exc_history
                if exc_history is not None:
                    tb = get_traceback(info=sys.exc_info(),
                                       skip=1,
                                       show_hidden_frames=False,
                                       ignore_system_exceptions=True)
                    for frame in tb.frames:
                        exc_history.frames[frame.id] = frame
                    exc_history.tracebacks[tb.id] = tb

                    qs = {'token': exc_history.token, 'tb': str(tb.id)}
                    exc_url = request.route_url(EXC_ROUTE_NAME, _query=qs)
                    ret['message'] = 'Exception: traceback url: {}'.format(
                        exc_url)
        return ret
Beispiel #54
0
    mgr = ILetterManager(context)
    letter_info = mgr.get_info(request)

    view_cookie = request.cookies.get(_VIEW_COOKIE)
    classes = []
    for name, title, description, urlname in _VIEWS:
        classes.append({'name': name,
                        'title': title,
                        'description': description,
                        'href': urlname,
                        'url': request.resource_url(context, urlname),
                        'selected': name == view_cookie,
                       })

    actions = []
    if has_permission('create', context, request):
        actions.append(('Add Community', 'add_community.html'))

    system_name = get_setting(context, 'system_name', 'KARL')
    page_title = '%s%s Communities' % (prefix, system_name)

    my_communities = get_my_communities(context, request)
    preferred_communities = get_preferred_communities(context, request)

    return {'communities': communities,
            'batch_info': batch_info,
            'letters': letter_info,
            'community_tabs': classes,
            'actions': actions,
            'my_communities': my_communities,
            'preferred_communities': preferred_communities,
Beispiel #55
0
 def _has_permission(name):
     return has_permission(name, RootFactory, event["request"])
Beispiel #56
0
def deferred_prefix_widget(node, kw):
    request = kw['request']
    if has_permission('manage', request.context, request):
        return deform.widget.TextInputWidget()
    else:
        return deform.widget.HiddenWidget()
Beispiel #57
0
def show_profile_view(context, request):
    """Show a profile with actions if the current user"""
    layout = request.layout_manager.layout
    layout.page_title = "Profile: %s" % context.title
    api = TemplateAPI(context, request, layout.page_title)

    # Create display values from model object
    profile = {}
    for name in [name for name in context.__dict__.keys()
                 if not name.startswith("_")]:
        profile_value = getattr(context, name)
        if profile_value is not None:
            # Don't produce u'None'
            profile[name] = unicode(profile_value)
        else:
            profile[name] = None

    if 'fax' not in profile:
        profile['fax'] = '' # BBB

    # 'websites' is a property, so the loop above misses it
    profile["websites"] = context.websites

    # ditto for 'title'
    profile["title"] = context.title

    if profile.has_key("languages"):
        profile["languages"] = context.languages

    if profile.has_key("department"):
        profile["department"] = context.department

    if profile.get("last_login_time"):
        stamp = context.last_login_time.strftime('%Y-%m-%dT%H:%M:%SZ')
        profile["last_login_time"] = stamp

    if profile.has_key("country"):
        # translate from country code to country name
        country_code = profile["country"]
        country = countries.as_dict.get(country_code, u'')
        profile["country"] = country

    # Display portrait
    photo = context.get('photo')
    display_photo = {}
    if photo is not None:
        display_photo["url"] = thumb_url(photo, request, PROFILE_THUMB_SIZE)
    else:
        display_photo["url"] = api.static_url + "/images/defaultUser.gif"
    profile["photo"] = display_photo

    # provide client data for rendering current tags in the tagbox
    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    # Get communities this user is a member of, along with moderator info
    #
    communities = {}
    communities_folder = find_communities(context)
    user_info = find_users(context).get_by_id(context.__name__)
    if user_info is not None:
        for group in user_info["groups"]:
            if group.startswith("group.community:"):
                unused, community_name, role = group.split(":")
                if (communities.has_key(community_name) and
                    role != "moderators"):
                    continue

                community = communities_folder.get(community_name, None)
                if community is None:
                    continue

                if has_permission('view', community, request):
                    communities[community_name] = {
                        "title": community.title,
                        "moderator": role == "moderators",
                        "url": resource_url(community, request),
                    }

    communities = communities.values()
    communities.sort(key=lambda x:x["title"])

    preferred_communities = []
    my_communities = None
    name = context.__name__
    # is this the current user's profile?
    if authenticated_userid(request) == name:
        preferred_communities = get_preferred_communities(communities_folder,
                                                          request)
        my_communities = get_my_communities(communities_folder, request)

    tagger = find_tags(context)
    if tagger is None:
        tags = ()
    else:
        tags = []
        names = tagger.getTags(users=[context.__name__])
        for name, count in sorted(tagger.getFrequency(names,
                                                      user=context.__name__),
                                  key=lambda x: x[1],
                                  reverse=True,
                                 )[:10]:
            tags.append({'name': name, 'count': count})

    # List recently added content
    num, docids, resolver = ICatalogSearch(context)(
        sort_index='creation_date', reverse=True,
        interfaces=[IContent], limit=5, creator=context.__name__,
        allowed={'query': effective_principals(request), 'operator': 'or'},
        )
    recent_items = []
    for docid in docids:
        item = resolver(docid)
        if item is None:
            continue
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        recent_items.append(adapted)
    recent_url = request.resource_url(context, 'recent_content.html')


    layout.add_portlet('my_tags', context, tags)
    layout.add_portlet('my_communities', my_communities,
                       preferred_communities, communities)

    panel_data = layout.head_data['panel_data']
    panel_data['tagbox'] = client_json_data['tagbox']

    return dict(api=api,
        profile=profile,
        actions=get_profile_actions(context, request),
        photo=photo,
        head_data=convert_to_script(client_json_data),
        communities=communities,
        my_communities=my_communities,
        preferred_communities=preferred_communities,
        tags=tags,
        recent_items=recent_items,
        recent_url=recent_url)
Beispiel #58
0
 def permitted(context, request):
     return has_permission(permission, context, request)
Beispiel #59
0
    def tile_render_tween(request):
        response = handler(request)
        if response.content_type == 'text/html':
            if isinstance(response, WSGIHTTPException):
                # the body of a WSGIHTTPException needs to be "prepared"
                response.prepare(request.environ)

            serializer = getHTMLSerializer(response.app_iter)
            tree = serializer.tree
            head_node = tree.getroot().find('head')

            for tile_node in TILE_XPATH(serializer.tree):
                # determine tile path
                tile_path = tile_node.attrib.get('path')
                tile_type = tile_node.attrib.get('type')
                if tile_path and tile_type:
                    if tile_path == '/':
                        path = '/tile:' + tile_type
                    else:
                        path = '/'.join((tile_path, 'tile:' + tile_type))
                elif tile_path:
                    path = tile_path
                elif tile_type:
                    path = request.resource_path(request.context,
                                                 'tile:' + tile_type)
                else:
                    # XXX how can we show a useful line number?
                    raise Exception('Tile must have a path or type')

                # fetch tile contents
                subrequest = Request.blank(path)
                subrequest.registry = registry
                tile_data = dict(tile_node.attrib)
                tile_data['innerHTML'] = (tile_node.text or '') + ''.join([
                    html.tostring(child) for child in tile_node.iterchildren()
                ])
                if tile_path:
                    edit_url = request.route_path(MANAGE_ROUTE_NAME,
                                                  'edit_tile',
                                                  traverse=tile_path)
                else:
                    edit_url = request.mgmt_path(request.context, 'edit_tile')
                edit_url += '?' + urlencode(tile_data)
                del tile_data['type']
                subrequest.tile_data = tile_data
                tile_response = handler(subrequest)
                tile_tree = getHTMLSerializer(tile_response.app_iter).tree
                tile_root = tile_tree.getroot()
                tile_body = tile_root.find('body')

                # add edit link
                if has_permission('Edit tile', subrequest.context, request):
                    edit_link = builder.E.a('', href=edit_url)
                    edit_link.append(etree.Entity('#9997'))
                    tile_body.append(edit_link)

                # insert tile content
                tile_head = tile_root.find('head')
                if tile_head is not None:
                    for child in tile_head:
                        head_node.append(child)
                if tile_tree is not None:
                    replace_content_with_children(tile_node, tile_body)

            response.app_iter = [serializer.serialize()]

        return response
Beispiel #60
0
def get_admin_menus(request):
    """
        Build the admin menu
    """
    menu = Menu()

    if has_permission("admin", request.context, request):
        href = request.route_path("admin_index")
        menu.add_item(u"Configuration", icon="fa fa-cogs", href=href)

    documents = DropDown(label=u"Documents")
    href = request.route_path("invoices")
    documents.add_item(u"Factures", icon="fa fa-file", href=href)
    href = request.route_path('expenses')
    documents.add_item(u'Notes de frais', icon='fa fa-file-o', href=href)

    menu.add(documents)

    if has_permission("admin", request.context, request):
        treasury = DropDown(label=u"Comptabilité")

        href = request.route_path("sage_invoice_export")
        treasury.add_item(u"Export des factures", icon="fa fa-edit", href=href)

        href = request.route_path("sage_expense_export")
        treasury.add_item(u"Export des notes de frais",
                          icon="fa fa-credit-card",
                          href=href)
        href = request.route_path("admin_treasury_all")
        treasury.add_item(u"Bulletins de salaire",
                          icon="fa fa-send-o",
                          href=href)

        menu.add(treasury)

    accompagnement = DropDown(label=u"Accompagnement")

    href = request.route_path('activities')
    accompagnement.add_item(u"Rendez-vous", href=href, icon="fa fa-calendar")

    href = request.route_path('workshops')
    accompagnement.add_item(u"Ateliers", href=href, icon="fa fa-slideshare")

    href = request.route_path('competences')
    accompagnement.add_item(u"Compétences", href=href, icon="fa fa-star")

    menu.add(accompagnement)

    gestion_sociale = DropDown(label=u"Gestion sociale")
    href = request.route_path('userdatas')
    gestion_sociale.add_item(u"Consulter", href=href, icon="fa fa-users")

    href = request.route_path('statistics')
    gestion_sociale.add_item(
        u"Statistiques",
        href=href,
        icon="fa fa-line-chart",
    )

    menu.add(gestion_sociale)

    href = request.route_path("holidays")
    menu.add_item(u"Congés", icon="fa fa-space-shuttle", href=href)
    return menu