def __call__(self, node, value): root = find_root(self.context) try: find_resource(root, value) except KeyError: raise colander.Invalid( node, _("Not an existing valid path."))
def move_content(root, src, dst, wf_state): try: context = find_resource(root, src) except KeyError: print >> sys.stderr, "Source content not found: %s" % src sys.exit(-1) try: dest_folder = find_resource(root, dst) except KeyError: print >> sys.stderr, "Destination folder not found: %s" % dst sys.exit(-1) src_community = find_community(context) catalog = find_catalog(root) assert catalog is not None users = find_users(root) assert users is not None if src_community is not None: move_header = ('<p><em>This was originally authored ' 'in the "%s" community.</em></p>' % src_community.title) else: move_header = '' src_folder = context.__parent__ name = context.__name__ log.info("Moving %s", resource_path(context)) for obj in postorder(context): if hasattr(obj, 'docid'): docid = obj.docid catalog.document_map.remove_docid(docid) catalog.unindex_doc(docid) del src_folder[name] if (context.creator != 'admin' and users.get_by_id(context.creator) is None): # give the entry to the system admin log.warning("User %s not found; reassigning to admin", context.creator) context.creator = 'admin' if name in dest_folder: name = make_unique_name(dest_folder, context.title) dest_folder[name] = context for obj in postorder(context): if hasattr(obj, 'docid'): docid = obj.docid catalog.document_map.add(resource_path(obj), docid) catalog.index_doc(docid, obj) if wf_state is not None: wf = get_workflow(get_content_type(context), 'security', context) wf.transition_to_state(context, None, wf_state) if hasattr(context, 'text'): context.text = "%s\n%s" % (move_header, context.text)
def _find_resources(root, entry: dict) -> (IUser, IBadge, sheets.badge.IBadgeable): userpath = entry.get('user') user = find_resource(root, userpath) badgepath = entry.get('badge') badge = find_resource(root, badgepath) badgeablepath = entry.get('badgeable') badgeable = find_resource(root, badgeablepath) return user, badge, badgeable
def linkFrom(validator, linkFrom, instance, schema): # avoid circular import from .contentbase import Item linkType, linkProp = linkFrom.split('.') if validator.is_type(instance, "string"): request = get_current_request() base = request.root.by_item_type[linkType] try: item = find_resource(base, instance.replace(':', '%3A')) if item is None: raise KeyError() except KeyError: error = "%r not found" % instance yield ValidationError(error) return if not isinstance(item, Item): error = "%r is not a linkable resource" % instance yield ValidationError(error) return if linkType not in set([item.item_type] + item.base_types): error = "%r is not of type %s" % (instance, repr(linkType)) yield ValidationError(error) return pass else: path = instance.get('@id') request = get_current_request() if validator._serialize: lv = len(validator._validated) if '@id' in instance: del instance['@id'] # treat the link property as not required # because it will be filled in when the child is created/updated subtype = request.root.by_item_type.get(linkType) subschema = request.registry['calculated_properties'].schema_for( subtype.Item) subschema = copy.deepcopy(subschema) if linkProp in subschema['required']: subschema['required'].remove(linkProp) for error in validator.descend(instance, subschema): yield error if validator._serialize: validated_instance = validator._validated[lv] del validator._validated[lv:] if path is not None: item = find_resource(request.root, path.replace(':', '%3A')) validated_instance['uuid'] = str(item.uuid) elif 'uuid' in validated_instance: # where does this come from? del validated_instance['uuid'] validator._validated[-1] = validated_instance
def linkFrom(validator, linkFrom, instance, schema): # avoid circular import from snovault import Item, TYPES, COLLECTIONS request = get_current_request() collections = request.registry[COLLECTIONS] linkType, linkProp = linkFrom.split('.') if validator.is_type(instance, "string"): base = collections[linkType] try: item = find_resource(base, instance.replace(':', '%3A')) if item is None: raise KeyError() except KeyError: error = "%r not found" % instance yield ValidationError(error) return if not isinstance(item, Item): error = "%r is not a linkable resource" % instance yield ValidationError(error) return if linkType not in set([item.type_info.name] + item.type_info.base_types): error = "%r is not of type %s" % (instance, repr(linkType)) yield ValidationError(error) return pass else: path = instance.get('@id') if validator._serialize: lv = len(validator._validated) if '@id' in instance: del instance['@id'] # treat the link property as not required # because it will be filled in when the child is created/updated subschema = request.registry[TYPES][linkType].schema subschema = copy.deepcopy(subschema) if linkProp in subschema['required']: subschema['required'].remove(linkProp) for error in validator.descend(instance, subschema): yield error if validator._serialize: validated_instance = validator._validated[lv] del validator._validated[lv:] if path is not None: item = find_resource(request.root, path.replace(':', '%3A')) validated_instance['uuid'] = str(item.uuid) elif 'uuid' in validated_instance: # where does this come from? del validated_instance['uuid'] validator._validated[-1] = validated_instance
def _deserialize_location_or_url(self, node, value): if value.startswith('/'): context = node.bindings['context'] return find_resource(context, value) else: context = node.bindings['context'] request = node.bindings['request'] application_url_len = len(request.application_url) if application_url_len > len(str(value)): raise KeyError # Fixme: This does not work with :term:`virtual hosting` path = value[application_url_len:] return find_resource(context, path)
def isReport(self, name): """ See IMailinDispatcher. """ root = find_root(self.context) if name in root.list_aliases: return True pd = find_peopledirectory(self.context) tokens = name.split('+') try: find_resource(pd, tokens) except KeyError: return False return True
def _deserialize_location_or_url(self, node, value): if value.startswith('/'): context = node.bindings['context'] return find_resource(context, value) else: context = node.bindings['context'] request = node.bindings['request'] root_url = request.resource_url(request.root, route_name=API_ROUTE_NAME) root_url_len = len(root_url) if root_url_len > len(str(value)): raise KeyError path = value[root_url_len:] return find_resource(context, path)
def _deserialize_location_or_url(self, node, value): if value.startswith('/'): assert 'context' in node.bindings context = node.bindings['context'] return find_resource(context, value) else: assert 'request' in node.bindings request = node.bindings['request'] application_url_len = len(request.application_url) if application_url_len > len(str(value)): raise KeyError # Fixme: This does not work with :term:`virtual hosting` path = value[application_url_len:] return find_resource(request.root, path)
def should_show_calendar_tab(self): """whether to show the calendar tab in the header menu user must be staff, and the calendar object must exist""" if self._should_show_calendar_tab is None: if not self.user_is_staff: self._should_show_calendar_tab = False else: calendar_path = "/offices/calendar" try: find_resource(self.site, calendar_path) self._should_show_calendar_tab = True except KeyError: self._should_show_calendar_tab = False return self._should_show_calendar_tab
def should_show_calendar_tab(self): """whether to show the calendar tab in the header menu user must be staff, and the calendar object must exist""" if self._should_show_calendar_tab is None: if not self.user_is_staff: self._should_show_calendar_tab = False else: calendar_path = '/offices/calendar' try: find_resource(self.site, calendar_path) self._should_show_calendar_tab = True except KeyError: self._should_show_calendar_tab = False return self._should_show_calendar_tab
def main(): parser = argparse.ArgumentParser() parser.add_argument("config_uri", help="Paster ini file to load settings from") parser.add_argument("path", help="Which path to extract info from") args = parser.parse_args() env = bootstrap(args.config_uri) root = env['root'] request = env['request'] print "Reading poll times from path %r" % args.path #Just to make sure path exists find_resource(root, args.path) query = "path == '%s'" % args.path query += " and type_name == 'Poll'" docids = root.catalog.query(query)[1] for poll in request.resolve_docids(docids, perm=None): print_voting_timestamps(poll, request)
def forbidden(request): if not hasattr(request, 'user'): locale = get_localizer(request) request.session.flash(locale.translate(_("Login required"))) request.session['came_from'] = request.url return HTTPFound(request.resource_url(request.root, 'login')) homes = request.user.find_home() at_root = not request.path_info.strip('/') if at_root and len(homes) == 1: return HTTPFound(request.application_url.rstrip('/') + homes[0]) at_root = at_root and homes homes = [find_resource(request.root, path) for path in homes] homes = [{'title': home.title, 'url': request.resource_url(home)} for home in homes] request.layout_manager.use_layout('anonymous') layout = request.layout_manager.layout if at_root: layout.page_title = _("Welcome to Gathr") else: layout.page_title = _('Forbidden') return { 'at_root': at_root, 'homes': homes, }
def get_moderator_actions(self, context): """ A.k.a. the cogwheel-menu. context might be a brain here, but the view component must have an object context.""" if not IBaseContent.providedBy(context): #Assume brain - might need to change this later context = find_resource(self.root, context['path']) return self.render_single_view_component(context, self.request, 'main', 'moderator_actions')
def test_username_is_resolved_to_his_path(self, registry): from adhocracy_core.scripts import import_resources from .import_users import _get_user_locator (self._tempfd, filename) = mkstemp() with open(filename, 'w') as f: f.write(json.dumps([ {"path": "/principals/users/badge_assignments", "content_type": "adhocracy_core.resources.badge.IBadgeAssignment", "data": {"adhocracy_core.sheets.badge.IBadgeAssignment": {"subject": "user_by_login:god", "badge": "/orga/badges/badge0", "object": "/principals/users/0000000" }, "adhocracy_core.sheets.name.IName": {"name": "assign0"}} }])) root = registry.content.create(IRootPool.__identifier__) appstructs = {'adhocracy_core.sheets.name.IName': {'name': 'orga'}} orga = registry.content.create(IOrganisation.__identifier__, root, appstructs=appstructs, registry=registry) add_badges_service(orga, registry, {}) badge_appstructs = {'adhocracy_core.sheets.name.IName': {'name': 'badge0'}} registry.content.create(IBadge.__identifier__, orga['badges'], appstructs=badge_appstructs, registry=registry) import_resources(root, registry, filename) assignments = find_resource(root, '/principals/users/badge_assignments/') assignment = list(assignments.values())[0] subject = get_sheet_field(assignment, IBadgeAssignment, 'subject') user_locator = _get_user_locator(root, registry) god = user_locator.get_user_by_login('god') assert subject == god
def update_gallery_attribute_date_from_to(self): context, request = self.context, self.request assert isinstance(context, GalleryContainer) #print 'JSON request with id=%s, name=%s' \ #% (request.params['pg-id'], request.params['pg-name']) result = {'pg-status': 'failed'} pg_context = find_resource(context, request.params['pg-context']) pg_name = request.params['pg-name'] pg_value = json.loads(request.params['pg-value']) date_from, date_to = [ datetime.datetime.strptime(date, '%Y-%m-%d').date() \ for date in (pg_value['from'], pg_value['to']) ] if date_to < date_from: raise AssertionError('date_to < date_from') if pg_name == '__date_from_to': pg_context.date_from = date_from pg_context.date_to = date_to else: pg_context.__setattr__(pg_name, (date_from, date_to)) date_str = '%d' % date_from.day if date_from.month != date_to.month: date_str += ' %s' % date_from.strftime('%B') if date_from.year != date_to.year: date_str += ' %d' % date_from.year date_str += ' - %d %s %d' % (date_to.day, date_to.strftime('%B'), date_to.year) result['pg-date-from-to'] = date_str result['pg-status'] = 'success' return result
def retrieve_pictures(self): context, request = self.context, self.request assert isinstance(context, GalleryContainer) result = {'pg-status': 'failed'} pg_context = find_resource(context, request.params['pg-context']) if 'pg-slice' in request.params: pg_slice = [int(x) for x in request.params['pg-slice'].split(':')] pg_slice = slice(*pg_slice) else: pg_slice = slice(None) indices = range(len(pg_context))[pg_slice] pg_pictures = [] for index, child in enumerate(pg_context.itervalues()): if index not in indices: continue if isinstance(child, GalleryContainer): thumbnail = child.preview_picture elif isinstance(child, GalleryPicture): thumbnail = child else: raise Exception("Can't retrieve thumbnails " "for this kind of object") pg_pictures.append({ 'index': index, 'name': child.name, 'big_url': self.big_url(thumbnail), 'regular_url': self.regular_url(thumbnail), 'width': self.regular_width(thumbnail), 'height': self.regular_height(thumbnail), }) result['pg-pictures'] = json.dumps(pg_pictures) result['pg-status'] = 'success' return result
def _fetch_organisation_by_name(root, organisation_path): organisation = find_resource(root, organisation_path) if organisation is None: print('could not find organisation %s' % (organisation)) sys.exit() else: return organisation
def main(argv=sys.argv): def usage(msg): print msg sys.exit(2) description = "Postprocess new recordings as they are made." usage = "usage: %prog config_uri" parser = optparse.OptionParser(usage, description=description) opts, args = parser.parse_args(argv[1:]) try: config_uri = args[0] except KeyError: usage("Requires a config_uri as an argument") setup_logging(config_uri) env = bootstrap(config_uri) root = env["root"] redis = get_redis(env["request"]) while True: path = redis.blpop("yss.new-recordings", 0)[1] time.sleep(1) transaction.abort() recording = find_resource(root, path) try: postprocess(recording) except: redis.rpush("yss.new-recorings", path) raise
def test_testing_resources(self): from pyramid.traversal import find_resource from pyramid.interfaces import ITraverser ob1 = object() ob2 = object() resources = {'/ob1': ob1, '/ob2': ob2} config = self._makeOne(autocommit=True) config.testing_resources(resources) adapter = config.registry.getAdapter(None, ITraverser) result = adapter(DummyRequest({'PATH_INFO': '/ob1'})) self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (text_('ob1'), )) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) result = adapter(DummyRequest({'PATH_INFO': '/ob2'})) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (text_('ob2'), )) self.assertEqual(result['virtual_root'], ob2) self.assertEqual(result['virtual_root_path'], ()) self.assertRaises(KeyError, adapter, DummyRequest({'PATH_INFO': '/ob3'})) try: config.begin() self.assertEqual(find_resource(None, '/ob1'), ob1) finally: config.end()
def url_to_resource(self, url): """ Returns the resource that is addressed by the given URL. :param str url: URL to convert :return: member or collection resource :note: If the query string in the URL has multiple values for a query parameter, the last definition in the query string wins. """ parsed = urlparse.urlparse(url) parsed_path = parsed.path # namedtupble problem pylint: disable=E1101 rc = find_resource(self.__request.root, traversal_path(parsed_path)) if ICollectionResource in provided_by(rc): # In case we found a collection, we have to filter, order, slice. parsed_query = parsed.query # namedtuple problem pylint: disable=E1101 params = dict(parse_qsl(parsed_query)) filter_string = params.get('q') if not filter_string is None: rc.filter = \ UrlPartsConverter.make_filter_specification(filter_string) order_string = params.get('sort') if not order_string is None: rc.order = \ UrlPartsConverter.make_order_specification(order_string) start_string = params.get('start') size_string = params.get('size') if not (start_string is None or size_string is None): rc.slice = \ UrlPartsConverter.make_slice_key(start_string, size_string) elif not IMemberResource in provided_by(rc): raise ValueError('Traversal found non-resource object "%s".' % rc) return rc
def test_testing_resources(self): from pyramid.traversal import find_resource from pyramid.interfaces import ITraverser ob1 = object() ob2 = object() resources = {'/ob1':ob1, '/ob2':ob2} config = self._makeOne(autocommit=True) config.testing_resources(resources) adapter = config.registry.getAdapter(None, ITraverser) result = adapter(DummyRequest({'PATH_INFO':'/ob1'})) self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (text_('ob1'),)) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) result = adapter(DummyRequest({'PATH_INFO':'/ob2'})) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (text_('ob2'),)) self.assertEqual(result['virtual_root'], ob2) self.assertEqual(result['virtual_root_path'], ()) self.assertRaises(KeyError, adapter, DummyRequest({'PATH_INFO':'/ob3'})) try: config.begin() self.assertEqual(find_resource(None, '/ob1'), ob1) finally: config.end()
def user_tagged_content(event): if ITagAddedEvent.providedBy(event): request = get_current_request() context = getattr(request, 'context', None) if context is None: return events = find_events(context) if not events: return site = find_site(context) catalog = find_catalog(context) path = catalog.document_map.address_for_docid(event.item) tagged = find_resource(site, path) if tagged is None: return profile_id = event.user if profile_id in (None, 'None'): return profile = site['profiles'][profile_id] info = _getInfo(profile, tagged) if info is None: return if info['content_type'] == 'Community': info['flavor'] = 'tagged_community' elif info['content_type'] == 'Person': info['flavor'] = 'tagged_profile' else: info['flavor'] = 'tagged_other' info['operation'] = 'tagged' info['tagname'] = event.name events.push(**info)
def deserialize(self, node, cstruct): if not cstruct: return colander.null bindings = node.bindings or {} request = bindings.get('request', None) if not request: raise RuntimeError('"request" has not found inside of schema node bindings') if not isinstance(cstruct, str): raise colander.Invalid( node, colander._( '${val} is not a string with URL', mapping={'val': cstruct}, ), ) try: resource_path = urlsplit(cstruct).path except ValueError as e: raise colander.Invalid( node, colander._( '${val} is not a valid URL: ${err}', mapping={'val': cstruct, 'err': e}, ), ) try: resource = find_resource(request.root, resource_path) except KeyError: raise colander.Invalid(node, colander._('Resource has not found')) return resource
def recent_items(self): if self._recent_items is None: community = find_interface(self.context, ICommunity) if community is not None: stmt = """SELECT docid from pgtextindex WHERE community_docid='%s' AND content_type not in ('IInvitation', 'ICalendar', 'ICalendarLayer', 'ICalendarCategory', 'IBlog', 'ICommunityRootFolder', 'IWiki') ORDER BY modification_date DESC LIMIT 20""" catalog = find_catalog(self.context) index = catalog['texts'] docids = index.get_sql_catalog_results(stmt % community.docid) self._recent_items = [] for docid in docids: path = catalog.document_map.address_for_docid(docid[0]) try: model = find_resource(self.context, path) except (KeyError, TypeError): continue if not has_permission('view', model, self.request): continue try: adapted = getMultiAdapter((model, self.request), IGridEntryInfo) except ComponentLookupError: continue self._recent_items.append(adapted) return self._recent_items
def view_catalog(context, request): s = Template(""" <!DOCTYPE html> <html> <head> <title>Catalog $name</title> </head> <body> <p>BC: $breadcrumbs</p> <hr> <h3>title: $title</h3> $test1 <hr> <p>Tags: $keys</p> </body> </html> """) # try to find resource `test1` in context res1 = find_resource(context, 'test1') t_test1 = res1 if res1 else '' output = s.safe_substitute(breadcrumbs=getBreadCrumbs(request), name=context.__name__, title=context.title, test1='<p>test1 = %s</p>' % t_test1, keys=getCatalogTags(request)) return Response(body=output, charset='utf-8', content_type='text/html', content_language='ru')
def batch_upgrade(request): request.datastore = 'database' transaction.get().setExtendedInfo('upgrade', True) batch = request.json['batch'] root = request.root storage = request.registry[STORAGE].write session = storage.DBSession() results = [] for uuid in batch: item_type = None update = False error = False sp = session.begin_nested() try: item = find_resource(root, uuid) item_type = item.type_info.item_type update, errors = update_item(storage, item) except Exception: logger.exception('Error updating: /%s/%s', item_type, uuid) sp.rollback() error = True else: if errors: errortext = [ '%s: %s' % ('/'.join(error.path) or '<root>', error.message) for error in errors] logger.error( 'Validation failure: /%s/%s\n%s', item_type, uuid, '\n'.join(errortext)) sp.rollback() error = True else: sp.commit() results.append((item_type, uuid, update, error)) return {'results': results}
def checkPermission(self, info): """ Does user have permission to author content in the given context? Uses ACL security policy to test. """ users = find_users(self.context) for target in info['targets']: if 'error' in target: continue report_name = target.get('report') if report_name is not None: pd = find_peopledirectory(self.context) context = find_resource(pd, report_name.split('+')) permission = "email" else: communities = find_communities(self.context) community = communities[target['community']] context = community[target['tool']] permission = "create" # XXX In theory could depend on target user = users.get_by_id(info['author']) if user is not None: user = dict(user) user['repoze.who.userid'] = info['author'] # BFG Security API always assumes http request, so we fabricate a # fake request. request = Request.blank('/') request.environ['repoze.who.identity'] = user if not has_permission(permission, context, request): target['error'] = 'Permission Denied'
def update_children(context, request, propname_children): registry = request.registry conn = registry[CONNECTION] collections = registry[COLLECTIONS] schema_rev_links = context.type_info.schema_rev_links uuid = str(context.uuid) for propname, children in propname_children.items(): link_type, link_attr = schema_rev_links[propname] found = set() # Add or update children included in properties for i, child_props in enumerate(children): if isinstance(child_props, basestring): # IRI of (existing) child child = find_resource(collections[link_type], child_props) else: child_props = child_props.copy() child_type = child_props.pop('@type', None) if 'uuid' in child_props: # update existing child child_id = child_props.pop('uuid') child = conn.get_by_uuid(child_id) if not request.has_permission('edit', child): msg = u'edit forbidden to %s' % request.resource_path( child) raise ValidationFailure('body', [propname, i], msg) ensure_child_link(child_props, child.type_info, link_attr, uuid) try: update_item(child, request, child_props) except ValidationFailure as e: e.location = [propname, i] + e.location raise else: # add new child child_type = child_type[0] child_collection = collections[child_type] ensure_child_link(child_props, child_collection.type_info, link_attr, uuid) if not request.has_permission('add', child_collection): msg = u'add forbidden to %s' % request.resource_path( child_collection) raise ValidationFailure('body', [propname, i], msg) child = create_item(child_collection.type_info, request, child_props) found.add(child.uuid) # Remove existing children that are not in properties for link_uuid in context.get_rev_links(propname): if link_uuid in found: continue child = conn.get_by_uuid(link_uuid) if not request.has_permission('visible_for_edit', child): continue if not request.has_permission('edit', child): msg = u'edit forbidden to %s' % request.resource_path(child) raise ValidationFailure('body', [propname, i], msg) try: delete_item(child, request) except ValidationFailure as e: e.location = [propname, i] + e.location raise
def recent_items(self): if self._recent_items is None: community = find_interface(self.context, ICommunity) if community is not None: stmt = """SELECT docid from pgtextindex WHERE community_docid='%s' AND content_type not in ('IInvitation', 'ICalendar', 'ICalendarLayer', 'ICalendarCategory', 'IBlog', 'ICommunityRootFolder', 'IWiki') ORDER BY modification_date DESC LIMIT 20""" catalog = find_catalog(self.context) index = catalog['texts'] docids = index.get_sql_catalog_results(stmt % community.docid) self._recent_items = [] for docid in docids: path = catalog.document_map.address_for_docid(docid[0]) try: model = find_resource(self.context, path) except KeyError: continue if not has_permission('view', model, self.request): continue try: adapted = getMultiAdapter((model, self.request), IGridEntryInfo) except ComponentLookupError: continue self._recent_items.append(adapted) return self._recent_items
def test_it(self): ob1 = object() ob2 = object() resources = {'/ob1':ob1, '/ob2':ob2} from pyramid import testing testing.registerResources(resources) from pyramid.interfaces import ITraverser adapter = self.registry.getAdapter(None, ITraverser) result = adapter({'PATH_INFO':'/ob1'}) self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (u'ob1',)) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) result = adapter({'PATH_INFO':'/ob2'}) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (u'ob2',)) self.assertEqual(result['virtual_root'], ob2) self.assertEqual(result['virtual_root_path'], ()) self.assertRaises(KeyError, adapter, {'PATH_INFO':'/ob3'}) from pyramid.traversal import find_resource self.assertEqual(find_resource(None, '/ob1'), ob1)
def view_catalog(context, request): s = Template(""" <!DOCTYPE html> <html> <head> <title>Catalog $name</title> </head> <body> <p>BC: $breadcrumbs</p> <hr> <h3>title: $title</h3> $test1 <hr> <p>Tags: $keys</p> </body> </html> """) # try to find resource `test1` in context res1 = find_resource(context, 'test1') t_test1 = res1 if res1 else '' output = s.safe_substitute(breadcrumbs = getBreadCrumbs(request), name = context.__name__, title = context.title, test1 = '<p>test1 = %s</p>' % t_test1, keys = getCatalogTags(request)) return Response(body=output, charset='utf-8', content_type='text/html', content_language='ru')
def get_font(self): try: font = traversal.find_resource(traversal.find_root(self.get_model()), self.font) except: return None else: return font
def test_it(self): ob1 = object() ob2 = object() resources = {'/ob1': ob1, '/ob2': ob2} from pyramid import testing testing.registerResources(resources) from pyramid.interfaces import ITraverser adapter = self.registry.getAdapter(None, ITraverser) result = adapter({'PATH_INFO': '/ob1'}) self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (u'ob1', )) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) result = adapter({'PATH_INFO': '/ob2'}) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (u'ob2', )) self.assertEqual(result['virtual_root'], ob2) self.assertEqual(result['virtual_root_path'], ()) self.assertRaises(KeyError, adapter, {'PATH_INFO': '/ob3'}) from pyramid.traversal import find_resource self.assertEqual(find_resource(None, '/ob1'), ob1)
def checkPermission(self, info): """ Does user have permission to author content in the given context? Uses ACL security policy to test. """ users = find_users(self.context) for target in info['targets']: if 'error' in target: continue report_name = target.get('report') if report_name is not None: pd = find_peopledirectory(self.context) context = find_resource(pd, report_name.split('+')) permission = "email" else: communities = find_communities(self.context) community = communities[target['community']] context = community[target['tool']] permission = "create" # XXX In theory could depend on target user = users.get_by_id(info['author']) if user is not None: user = dict(user) # XXX check this! user['karl.identity'] = {'id': info['author']} # BFG Security API always assumes http request, so we fabricate a # fake request. request = Request.blank('/') request.environ['karl.identity'] = user request.context = self.context if not has_permission(permission, context, request): target['error'] = 'Permission Denied'
def add_actions(self, item): """ Add the "actions" field to an item according to the request's permissions, formatted identically to the calc props on items for a GET page view. :param item: dict item in object view :return item: dict item in object view with "actions" """ actions = [] root_resource = self.request.root item_path = item["@id"] item_resource = find_resource(root_resource, item_path) for action in ["edit", "create"]: if self.request.has_permission(action, item_resource): actions.append({ "name": action, "title": action.capitalize(), "profile": "/profiles/%s.json" % item_resource.type_info.name, "href": "%s?currentAction=%s" % ( self.request.resource_path(item_resource), action ) }) item["actions"] = actions return item
def user_tagged_content(event): if ITagAddedEvent.providedBy(event): request = get_current_request() context = getattr(request, "context", None) if context is None: return events = find_events(context) if not events: return site = find_site(context) catalog = find_catalog(context) path = catalog.document_map.address_for_docid(event.item) tagged = find_resource(site, path) if tagged is None: return profile_id = event.user if profile_id in (None, "None"): return profile = site["profiles"][profile_id] info = _getInfo(profile, tagged) if info is None: return if info["content_type"] == "Community": info["flavor"] = "tagged_community" elif info["content_type"] == "Person": info["flavor"] = "tagged_profile" else: info["flavor"] = "tagged_other" info["operation"] = "tagged" info["tagname"] = event.name events.push(**info)
def get_proposal_objects(self): """ Return proposal objects relevant to this poll. Will sort them in specified order. """ agenda_item = self.__parent__ if agenda_item is None: raise ValueError("Can't find any agenda item in the polls lineage") query = Any('uid', tuple(self.proposal_uids)) & Eq( 'type_name', 'Proposal') root = find_root(agenda_item) results = [] for docid in root.catalog.query(query)[1]: path = root.document_map.address_for_docid(docid) obj = find_resource(root, path) # Permission check shouldn't be needed at this point if obj: results.append(obj) if self.proposal_order: proposal_order = self.proposal_order else: meeting = find_interface(self, IMeeting) # During tests, we might not have a real meeting here :) proposal_order = getattr(meeting, 'poll_proposals_default_order', '') key_method = PROPOSAL_ORDER_KEY_METHODS.get( proposal_order, PROPOSAL_ORDER_KEY_METHODS[PROPOSAL_ORDER_DEFAULT]) return sorted(results, key=key_method)
def _set_workflow_state( root: IResource, registry: Registry, resource_path: str, states: [str], absolute=False, reset=False ): resource = find_resource(root, resource_path) states_to_transition = _get_states_to_transition(resource, registry, states, absolute, reset) transition_to_states(resource, states_to_transition, registry, reset=reset) transaction.commit()
def __call__(self, v): if not v: return site = find_site(self.context) try: target = find_resource(site, v) except KeyError, e: raise Invalid("Path not found: %s" % v)
def move_content_view(context, request): """ Move content from one community to another. Only blog entries supported for now. May or may not eventually expand to other content types. """ api = AdminTemplateAPI(context, request, 'Admin UI: Move Content') filtered_content = [] if 'filter_content' in request.params: # We're limiting ourselves to content that always lives in the same # place in each community, ie /blog, /calendar, /wiki, etc, so that # we can be pretty sure we can figure out where inside the destination # community we should move it to. filtered_content = _get_filtered_content( context, request, [IBlogEntry, IWikiPage, ICalendarEvent]) if not filtered_content: api.error_message = 'No content matches your query.' if 'move_content' in request.params: to_community = request.params.get('to_community', '') if not to_community: api.error_message = 'Please specify destination community.' else: try: paths = request.params.getall('selected_content') dst_community = find_resource(context, to_community) for path in paths: obj = find_resource(context, path) dst_container = _find_dst_container(obj, dst_community) name = make_unique_name(dst_container, obj.__name__) del obj.__parent__[obj.__name__] dst_container[name] = obj if len(paths) == 1: status_message = 'Moved one content item.' else: status_message = 'Moved %d content items.' % len(paths) redirect_to = resource_url( context, request, request.view_name, query=dict(status_message=status_message)) return HTTPFound(location=redirect_to) except _DstNotFound, error: api.error_message = str(error)
def mkCatalogFolderLinks(request): leaves = request.context.documents catalog = request.context.__parent__ catdb = find_resource(catalog, 'db') li = ['<li>' + '<a href="' + request.resource_url(catdb, i) + '">' + i + '</a></li>' for i in leaves] return "<ul>" + "\n".join(li) + "</ul>"
def move_content_view(context, request): """ Move content from one community to another. Only blog entries supported for now. May or may not eventually expand to other content types. """ request.layout_manager.use_layout('admin') api = AdminTemplateAPI(context, request, 'Admin UI: Move Content') filtered_content = [] if 'filter_content' in request.params: # We're limiting ourselves to content that always lives in the same # place in each community, ie /blog, /calendar, /wiki, etc, so that # we can be pretty sure we can figure out where inside the destination # community we should move it to. filtered_content = _get_filtered_content( context, request, [IBlogEntry, IWikiPage, ICalendarEvent]) if not filtered_content: api.error_message = 'No content matches your query.' if 'move_content' in request.params: to_community = request.params.get('to_community', '') if not to_community: api.error_message = 'Please specify destination community.' else: try: paths = request.params.getall('selected_content') dst_community = find_resource(context, to_community) for path in paths: obj = find_resource(context, path) dst_container = _find_dst_container(obj, dst_community) name = make_unique_name(dst_container, obj.__name__) del obj.__parent__[obj.__name__] dst_container[name] = obj if len(paths) == 1: status_message = 'Moved one content item.' else: status_message = 'Moved %d content items.' % len(paths) redirect_to = resource_url( context, request, request.view_name, query=dict(status_message=status_message) ) return HTTPFound(location=redirect_to) except _DstNotFound, error: api.error_message = str(error)
def resolver(docid): path = address(docid) if path is None: return None try: return find_resource(context, path) except KeyError: return None
def set_item_wood(context, request): try: data = json.loads(request.GET['data']) font = None if data.get('font') and data['font'] != context.font: font = traversal.find_resource(request.root, data['font']) if font: context.font = data['font'] _width, _height = font.getsize(context.name, 100) context.ratio = float(_width)/_height context.height = context.width/context.ratio else: raise Exception, "Not Found Resource Font in %s" % data['font'] if data.get('color') and data['color'] != context.color and re.match('^[0-9A-Fa-f]{6}$', data['color']): context.color = data['color'] #print data.get('left') , data.get('top'), 'asasass', data.get('left') and data.get('top') if data.has_key('left') and data.has_key('top'): context.left = data['left'] context.top = data['top'] #print data['left'], data['top'] if data.get('width') and data.get('height'): context.width = int(data['width']) context.height = int(data['height']) if not font: font = traversal.find_resource(request.root, context.font) except: _json = {'success': False} else: print context.ratio, context.width, context.height print context.left, context.top _json = {'success': True, 'font_url': request.resource_url(font), 'item': dict([(f, getattr(context, f)) for f in ['name', 'color'] ]), 'ratio': context.ratio, 'width': context.width, 'height': context.height } print _json['success'] return Response( json.dumps(_json), content_type="application/json")
def should_show_calendar_tab(self): path = self.settings.get('global_calendar_path', '/offices/calendar') try: calendar = find_resource(self.context, path) except KeyError: return False return has_permission(VIEW, calendar, self.request)
def user_tag_i_support(brain, request, va, **kw): """ Special view action for user tag 'support'. It requires catalog metadata + expects a brain as context, rather than a full object. """ api = kw['api'] obj = find_resource(api.root, brain['path']) # Only available on proposals if not obj.content_type == 'Proposal': return "" # only show form if users has the vote role show_form = False meeting = find_interface(obj, IMeeting) if ROLE_VOTER in meeting.get_groups(api.userid): show_form = True user_tags = request.registry.getAdapter(obj, IUserTags) userids = user_tags.userids_for_tag('support') #Note: It's not possible to have nested translation strings. So we do the translation here in advance. display_name = api.translate(_(u"Support")) expl_display_name = _(u"Support this") brain_url = "%s%s" % (request.application_url, brain['path']) response = dict( context_id=brain['uid'], toggle_url="%s/_support" % brain_url, tag='support', display_name=display_name, get_userinfo_url=api.get_userinfo_url, expl_display_name=expl_display_name, ) if api.userid and api.userid in userids: #Current user likes the current context response['button_label'] = _(u"Remove ${display_name}", mapping={'display_name': display_name}) response['selected'] = True response['do'] = "0" userids = list(userids) userids.remove(api.userid) else: #Current user hasn't selected the current context response['button_label'] = display_name response['selected'] = False response['do'] = "1" response['userids'] = userids response['has_entries'] = bool(response['selected'] or userids) response[ 'tagging_users_url'] = " %s/_tagging_users?tag=%s&display_name=%s&expl_display_name=%s" % ( brain_url, 'support', display_name, expl_display_name) response['show_form'] = show_form return render('voteit.core.views:templates/snippets/user_tag.pt', response, request=request)