def evolve(context): # add default category and layer to all calendars # Prevent 'set_created' event handler from being called since it will, # in turn, set the content_modified attribute of community which is used # as the "Last Activity" in the user interface. We don't want this tweak # to impact a community's last activity. This means we need to set created # and modified on the new layers and categories ourselves. registry = getSiteManager() registry.adapters.unsubscribe( (IContent, IObjectWillBeAddedEvent), None, set_created) try: search = ICatalogSearch(context) default_category_name = ICalendarCategory.getTaggedValue('default_name') default_layer_name = ICalendarLayer.getTaggedValue('default_name') now = datetime.now() cnt, docids, resolver = search(interfaces=[ICalendar]) for docid in docids: calendar = resolver(docid) default_category = create_content(ICalendarCategory, 'Default') default_category.created = default_category.modified = now if not default_category_name in calendar: calendar[default_category_name] = default_category local_layer = create_content(ICalendarLayer, "This Calendar's Events Only", 'blue', [resource_path(default_category)]) local_layer.created = local_layer.modified = now if not default_layer_name in calendar: calendar[default_layer_name] = local_layer finally: registry.adapters.subscribe( (IContent, IObjectWillBeAddedEvent), None, set_created)
def handle_submit(self, converted): context = self.context request = self.request parent = self.parent creator = authenticated_userid(request) log.debug('add_comment.html converted: %s, ctx: %s' % (str(converted), self.context)) comment = create_content( IComment, parent.title, converted['add_comment'], extract_description(converted['add_comment']), creator, ) if not 'comments' in parent.keys(): parent['comments'] = create_content(ICommentsFolder) comments = parent['comments'] next_id = comments.next_id comments[next_id] = comment if support_attachments(comment): upload_attachments(converted['attachments'], comment, creator, request) return self.status_response('Comment added')
def evolve(context): # add default category and layer to all calendars # Prevent 'set_created' event handler from being called since it will, # in turn, set the content_modified attribute of community which is used # as the "Last Activity" in the user interface. We don't want this tweak # to impact a community's last activity. This means we need to set created # and modified on the new layers and categories ourselves. registry = getSiteManager() registry.adapters.unsubscribe((IContent, IObjectWillBeAddedEvent), None, set_created) try: search = ICatalogSearch(context) default_category_name = ICalendarCategory.getTaggedValue( 'default_name') default_layer_name = ICalendarLayer.getTaggedValue('default_name') now = datetime.now() cnt, docids, resolver = search(interfaces=[ICalendar]) for docid in docids: calendar = resolver(docid) default_category = create_content(ICalendarCategory, 'Default') default_category.created = default_category.modified = now if not default_category_name in calendar: calendar[default_category_name] = default_category local_layer = create_content(ICalendarLayer, "This Calendar's Events Only", 'blue', [resource_path(default_category)]) local_layer.created = local_layer.modified = now if not default_layer_name in calendar: calendar[default_layer_name] = local_layer finally: registry.adapters.subscribe((IContent, IObjectWillBeAddedEvent), None, set_created)
def add_feed(argv=sys.argv): parser = create_karl_argparser(description='Add a new feed.') parser.add_argument('-t', '--title', help='Override title of feed.') parser.add_argument('-m', '--max', type=int, default=0, help='Maximum number of entries to keep at a time.') parser.add_argument('name', help='Identifier of feed in database.') parser.add_argument('url', help='URL of feed.') args = parser.parse_args(argv[1:]) env = args.bootstrap(args.config_uri) root, closer = env['root'], env['closer'] feed = get_feed(root, args.name) if feed is not None: args.parser.error("Feed already exists with name: %s" % args.name) name = args.name override_title = args.title max_entries = args.max url = args.url container = root.get('feeds') if container is None: container = create_content(IFeedsContainer) root['feeds'] = container assert name not in container, "Feed already exists: %s" % name feed = create_content(IFeed, override_title) feed.url = url feed.max_entries = max_entries container[name] = feed feed.override_title = bool(override_title) transaction.commit()
def add(self, context, request): default_category_name = ICalendarCategory.getTaggedValue('default_name') default_layer_name = ICalendarLayer.getTaggedValue('default_name') calendar = create_content(ICalendar) context['calendar'] = calendar calendar = context['calendar'] default_category = create_content(ICalendarCategory, 'Default') calendar[default_category_name] = default_category local_layer = create_content(ICalendarLayer, "This Calendar's Events Only",' blue', [resource_path(default_category)]) calendar[default_layer_name] = local_layer
def handle_photo_upload(context, form, thumbnail=False, handle_exc=True): upload = form.get("photo", None) if upload is not None and upload.file is not None: upload_file = upload.file if hasattr(upload, 'type'): upload_type = upload.type # FieldStorage else: upload_type = upload.mimetype # Formish File object assert upload_type if thumbnail: if not hasattr(upload_file, 'seek'): upload_file = StringIO(upload_file.read()) # save the source photo (in case we later decide to use # a different thumbnail size) source_photo = create_content(IImageFile, upload_file, upload_type) upload_file.seek(0) # make the thumbnail try: upload_file, upload_type = make_thumbnail( upload_file, upload_type) except IOError, e: if not handle_exc: raise transaction.get().doom() raise CustomInvalid({"photo": str(e)}) if 'source_photo' in context: del context['source_photo'] context['source_photo'] = source_photo photo = context.get_photo() if photo is None: photo = create_content( IImageFile, upload_file, upload_type ) name = "photo.%s" % photo.extension context[name] = photo else: if photo.mimetype != upload_type: del context[photo.__name__] photo.mimetype = upload_type name = "photo.%s" % photo.extension context[name] = photo photo.upload(upload_file) check_upload_size(context, photo, 'photo')
def add_feed(site, name, url, override_title=None, max_entries=0): container = site.get('feeds') if container is None: container = create_content(IFeedsContainer) site['feeds'] = container assert name not in container, "Feed already exists: %s" % name feed = create_content(IFeed, override_title) feed.url = url feed.max_entries = max_entries container[name] = feed feed.override_title = bool(override_title) return feed
def add(self, context, request): default_category_name = ICalendarCategory.getTaggedValue( 'default_name') default_layer_name = ICalendarLayer.getTaggedValue('default_name') calendar = create_content(ICalendar) context['calendar'] = calendar calendar = context['calendar'] default_category = create_content(ICalendarCategory, 'Default') calendar[default_category_name] = default_category local_layer = create_content(ICalendarLayer, "This Calendar's Events Only", ' blue', [resource_path(default_category)]) calendar[default_layer_name] = local_layer
def store_attachments(attachments_folder, params, creator): """Given some request data, pick apart and store attachments""" # Get the attachments out of the form data. We do iteritems # becauser there might be multiple with the name prefixed by # attachment. new_attachments = [] for key, value in params.iteritems(): if key.startswith('attachment') and value != '': new_attachments.append(value) # Iterate through the new attachments and create content to store in # the attachments folder. for attachment in new_attachments: filename = make_unique_name(attachments_folder, basename_of_filepath(attachment.filename)) attachments_folder[filename] = obj = create_content( ICommunityFile, title = filename, stream = attachment.file, mimetype = attachment.type, filename = filename, creator = creator, ) check_upload_size(attachments_folder, obj, 'attachment')
def handle_submit(self, converted): request = self.request context = self.context ordering = getattr(context, 'ordering', None) if ordering is not None: ordering.sync(context.keys()) creator = authenticated_userid(request) reference_object = create_content( self.content_iface, converted['title'], converted['description'], creator, ) name = make_unique_name(context, converted['title']) context[name] = reference_object if ordering is not None: ordering.add(name) # save the tags set_tags(reference_object, request, converted['tags']) location = resource_url(reference_object, request) return HTTPFound(location=location)
def __init__(self): super(Site, self).__init__() self.catalog = CachingCatalog() self.update_indexes() self.catalog.document_map = DocumentMap() profiles = create_content(IProfiles) self['profiles'] = profiles communities = create_content(ICommunities) self['communities'] = communities people = create_content(IPeopleDirectory) self['people'] = people self.users = KARLUsers(self) self.tags = Tags(self) self.sessions = SessionDataManager(3600, 5) self.filestore = PersistentMapping()
def evolve(root): former_id = None # Create lazily, in case we don't need it profiles = find_profiles(root) search = ICatalogSearch(root) catalog = find_catalog(root) creators = catalog['creator']._fwd_index.keys() modifiers = catalog['modified_by']._fwd_index.keys() userids = set(creators) | set(modifiers) for userid in userids: if userid not in profiles: if former_id is None: former_id = make_unique_name(profiles, 'formeruser') print "Creating profile for former user content:", former_id former_profile = create_content( IProfile, firstname='Former', lastname='User' ) profiles[former_id] = former_profile count, docids, resolver = search(creator=userid) for docid in docids: doc = resolver(docid) print "Updating 'creator' for", resource_path(doc) doc.creator = former_id count, docids, resolver = search(modified_by=userid) for docid in docids: doc = resolver(docid) print "Updating 'modified_by' for", resource_path(doc) doc.modified_by = former_id
def handle_submit(self, converted): request = self.request context = self.context workflow = self.workflow forum = create_content( IForum, converted['title'], converted['description'], authenticated_userid(request), ) name = make_unique_name(context, converted['title']) context[name] = forum # Set up workflow if workflow is not None: workflow.initialize(forum) if 'security_state' in converted: workflow.transition_to_state(forum, request, converted['security_state']) if 'sendalert' in converted and converted['sendalert']: alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(forum, request) location = resource_url(forum, request) return HTTPFound(location=location)
def evolve(context): """ Replace OSI's old OSI-specific peopledir implementation with newer, universal peopledir. NOTE: We have to keep the old peopledir package around at least long enough to run this in production. """ if isinstance(context['people'], OSIPeople): print "Delete old peopledir" del context['people'] print "Create new peopledir" context['people'] = people = create_content(IPeopleDirectory) assert isinstance(people, NewPeople) print "Perform fresh gsa_sync" # Use local copy if available, to save time in testing here = os.path.dirname(os.path.dirname(sys.argv[0])) local_gsa = os.path.abspath(os.path.join(here, 'gsa_sync.xml')) if os.path.exists(local_gsa): url = 'file://%s' % local_gsa user = password = None else: url = GSA_URL user, password = '******', 'oBaMa2012' print "Using url:", url GsaSync(context, url, user, password)() print "Run peopleconf" config = get_default_config() run_peopleconf(context, config, force_reindex=True)
def test_measure_time_object_traversal(self): #"""Measure time object traversal level 10""" import datetime #add container object tx = self.graph.start_transaction() root = self.app.root_factory(None) from adhocracy.core.models.interfaces import IChildsDict from adhocracy.core.models.container import IContainerMarker from repoze.lemonade.content import create_content container = root for x in range(10): name = u"child" + str(x) child = create_content(IContainerMarker) IChildsDict(container)[name] = child container = IChildsDict(container)[name] self.graph.stop_transaction(tx) ##test object traversal start = datetime.datetime.now() self.browser.open('http://localhost:6543/child0/child1/child2/' + 'child3/child4/child5/child6/child7/child8/child9') end = datetime.datetime.now() #echo measured time output = """\n\n\n Measure time object traversal level 10 - 1. run =============================================== \n browser.open('http://localhost/child0/../child8/child9'):\n %s \n\n\n """ % (str(end - start)) print output start = datetime.datetime.now() self.browser.open('http://localhost:6543/child0/child1/child2/' + 'child3/child4/child5/child6/child7/child8/child9') end = datetime.datetime.now() #echo measured time output = """\n\n\n Measure time object traversal level 10 - 2. run ================================================ \n browser.open('http://localhost/child0/../child8/child9'):\n %s \n\n\n """ % (str(end - start)) print output start = datetime.datetime.now() self.browser.open('http://localhost:6543/child0/child1/child2/' + 'child3/child4/child5/child6/child7/child8/child9') end = datetime.datetime.now() #echo measured time output = """\n\n\n Measure time object traversal level 10 - 3. run ================================================ \n browser.open('http://localhost/child0/../child8/child9'):\n %s \n\n\n """ % (str(end - start)) print output
def evolve(root): former_id = None # Create lazily, in case we don't need it profiles = find_profiles(root) search = ICatalogSearch(root) catalog = find_catalog(root) creators = catalog['creator']._fwd_index.keys() modifiers = catalog['modified_by']._fwd_index.keys() userids = set(creators) | set(modifiers) for userid in userids: if userid not in profiles: if former_id is None: former_id = make_unique_name(profiles, 'formeruser') print "Creating profile for former user content:", former_id former_profile = create_content(IProfile, firstname='Former', lastname='User') profiles[former_id] = former_profile count, docids, resolver = search(creator=userid) for docid in docids: doc = resolver(docid) print "Updating 'creator' for", resource_path(doc) doc.creator = former_id count, docids, resolver = search(modified_by=userid) for docid in docids: doc = resolver(docid) print "Updating 'modified_by' for", resource_path(doc) doc.modified_by = former_id
def handle_submit(self, converted): context = self.context request = self.request userid = converted['login'] users = self.users if (users.get_by_id(userid) is not None or users.get_by_login(userid) is not None or userid in context): msg = "User ID '%s' is already in use" % userid raise ValidationError(login=msg) users.add(userid, userid, converted['password'], converted['groups']) # prepend http:// to the website URL if necessary if converted.get('website', '').startswith('www.'): converted['website'] = 'http://%s' % converted['website'] kw = {} for k, v in converted.items(): if k in ('login', 'password', 'password_confirm', 'photo', 'groups'): continue kw[k] = v profile = create_content(IProfile, **kw) context[userid] = profile workflow = get_workflow(IProfile, 'security', context) if workflow is not None: workflow.initialize(profile) handle_photo_upload(profile, converted, thumbnail=True) location = model_url(profile, request) return HTTPFound(location=location)
def handle_submit(self, converted): request = self.request context = self.context #create the news item and store it creator = authenticated_userid(request) newsitem = create_content( INewsItem, title=converted['title'], text=converted['text'], creator=creator, publication_date=converted['publication_date'], caption=converted['caption'], ) name = make_unique_name(context, converted['title']) context[name] = newsitem # tags, attachments, and photos set_tags(newsitem, request, converted['tags']) attachments_folder = newsitem['attachments'] upload_attachments(converted['attachments'], attachments_folder, creator, request) handle_photo_upload(newsitem, converted) self.filestore.clear() location = model_url(newsitem, request) return HTTPFound(location=location)
def handle(self, message, info, text, attachments): """ See IMailinHandler. """ target = self.context['comments'] reply = create_content( IComment, title=info['subject'], creator=info['author'], text=text, description=extract_description(text), ) reply.title = info['subject'] reply.creator = info['author'] reply.created = info['date'] reply.text = text target[target.next_id] = reply workflow = get_workflow(IComment, 'security', target) if workflow is not None: workflow.initialize(reply) if attachments: _addAttachments(reply, info, attachments) # Mailin always sends alerts alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(reply, offline_request)
def handle(self, message, info, text, attachments): """ See IMailinHandler. """ entry = create_content( IBlogEntry, title=info['subject'], creator=info['author'], text=text, description=extract_description(text), ) entry.created = info['date'] if attachments: if 'attachments' not in entry: # XXX Not a likely code path, left here for safety entry['attachments'] = att_folder = AttachmentsFolder() att_folder.title = 'Attachments' att_folder.creator = info['author'] else: att_folder = entry['attachments'] _addAttachments(att_folder, info, attachments) entry_id = make_unique_name(self.context, entry.title) self.context[entry_id] = entry workflow = get_workflow(IBlogEntry, 'security', self.context) if workflow is not None: workflow.initialize(entry) alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(entry, offline_request)
def add_referencemanual_view(context, request): tags_list=request.POST.getall('tags') form = AddReferenceManualForm(tags_list=tags_list) if 'form.cancel' in request.POST: return HTTPFound(location=model_url(context, request)) if 'form.submitted' in request.POST: try: converted = form.validate(request.POST) # Create the reference manual and store it creator = authenticated_userid(request) reference_manual = create_content(IReferenceManual, converted['title'], converted['description'], creator, ) name = make_unique_name(context, converted['title']) context[name] = reference_manual # Save the tags on it. set_tags(reference_manual, request, converted['tags']) location = model_url(reference_manual, request) return HTTPFound(location=location) except Invalid, e: fielderrors = e.error_dict fill_values = form.convert(request.POST) tags_field = dict( records = [dict(tag=t) for t in request.POST.getall('tags')] )
def handle_photo_upload(context, form): upload = form.get("photo", None) if upload is not None and upload.file is not None: request = get_current_request() userid = authenticated_userid(request) upload_file = upload.file if hasattr(upload, 'type'): upload_type = upload.type # FieldStorage else: upload_type = upload.mimetype # Formish File object assert upload_type photo = create_content( ICommunityFile, title='Photo of ' + context.title, stream=upload_file, mimetype=upload_type, filename=basename_of_filepath(upload.filename), creator=userid, ) if not photo.is_image: transaction.get().doom() raise Invalid({'photo': 'Uploaded file is not a valid image.'}) if 'photo' in context: del context['photo'] alsoProvides(photo, IPhoto) context['photo'] = photo check_upload_size(context, photo, 'photo') # Handle delete photo (ignore if photo also uploaded) elif (form.get("photo_delete", False) or (upload and upload.metadata.get("remove", False))): if 'photo' in context: del context['photo']
def handle_submit(self, converted): context = self.context request = self.request # create the page and store it creator = authenticated_userid(request) page = create_content( IPage, converted['title'], converted['text'], extract_description(converted['text']), creator, ) name = make_unique_name(context, converted['title']) context[name] = page # tags and attachments set_tags(page, request, converted['tags']) attachments_folder = page['attachments'] upload_attachments(converted['attachments'], attachments_folder, creator, request) relocate_temp_images(page, request) # update ordering if in ordered container if hasattr(context, 'ordering'): context.ordering.add(name) location = resource_url(page, request) self.filestore.clear() return HTTPFound(location=location)
def handle_submit(self, converted): request = self.request context = self.context workflow = self.workflow wikipage = create_content( IWikiPage, converted['title'], converted['text'], extract_description(converted['text']), authenticated_userid(request), ) name = make_name(context, converted['title']) context[name] = wikipage if workflow is not None: workflow.initialize(wikipage) if 'security_state' in converted: workflow.transition_to_state(wikipage, request, converted['security_state']) # Save the tags on it. set_tags(wikipage, request, converted['tags']) relocate_temp_images(wikipage, request) if converted['sendalert']: alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(wikipage, request) msg = '?status_message=Wiki%20Page%20created' location = model_url(wikipage, request) + msg return HTTPFound(location=location)
def handle_submit(self, converted): context = self.context request = self.request parent = context.__parent__ creator = authenticated_userid(request) comment = create_content( IComment, 'Re: %s' % parent.title, converted['add_comment'], extract_description(converted['add_comment']), creator, ) next_id = parent['comments'].next_id parent['comments'][next_id] = comment workflow = get_workflow(IComment, 'security', context) if workflow is not None: workflow.initialize(comment) if 'security_state' in converted: workflow.transition_to_state(comment, request, converted['security_state']) if support_attachments(comment): upload_attachments(converted['attachments'], comment, creator, request) relocate_temp_images(comment, request) if converted.get('sendalert'): alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(comment, request) location = resource_url(parent, request) msg = 'Comment added' location = '%s?status_message=%s' % (location, urllib.quote(msg)) self.filestore.clear() return HTTPFound(location=location)
def upload_attachments(attachments, folder, creator, request): """ This creates *and removes* attachments based on information retrieved from a form""" for attachment in attachments: if attachment.filename: mimetype = get_upload_mimetype(attachment) filename = make_unique_name( folder, basename_of_filepath(attachment.filename) ) folder[filename] = obj = create_content( ICommunityFile, title = filename, stream = attachment.file, mimetype = mimetype, filename = filename, creator = creator, ) max_size = int(get_setting(folder, 'upload_limit', 0)) if max_size and obj.size > max_size: msg = 'File size exceeds upload limit of %d.' % max_size raise ValueError(msg) else: meta = attachment.metadata if meta.get('remove') and meta.get('default'): name = meta['default'] if name in folder: ob = folder[name] if has_permission('delete', ob, request): del folder[name]
def handle_submit(self, converted): request = self.request context = self.context workflow = self.workflow wikipage = create_content( IWikiPage, converted['title'], converted['text'], extract_description(converted['text']), authenticated_userid(request), ) name = make_name(context, converted['title']) context[name] = wikipage if workflow is not None: workflow.initialize(wikipage) if 'security_state' in converted: workflow.transition_to_state(wikipage, request, converted['security_state']) # Save the tags on it. set_tags(wikipage, request, converted['tags']) relocate_temp_images(wikipage, request) if converted['sendalert']: alerts = queryUtility(IAlerts, default=Alerts()) alerts.emit(wikipage, request) msg = '?status_message=Wiki%20Page%20created' location = resource_url(wikipage, request) + msg return HTTPFound(location=location)
def handle_submit(self, converted): request = self.request context = self.context #create the news item and store it creator = authenticated_userid(request) newsitem = create_content( INewsItem, title=converted['title'], text=converted['text'], creator=creator, publication_date=converted['publication_date'], caption=converted['caption'], ) name = make_unique_name(context, converted['title']) context[name] = newsitem # tags, attachments, and photos set_tags(newsitem, request, converted['tags']) attachments_folder = newsitem['attachments'] upload_attachments(converted['attachments'], attachments_folder, creator, request) try: handle_photo_upload(newsitem, converted) except Invalid, e: raise ValidationError(**e.error_dict)
def evolve(root): former_id = 'formeruser' profiles = find_profiles(root) search = ICatalogSearch(root) catalog = find_catalog(root) creators = catalog['creator']._fwd_index.keys() modifiers = catalog['modified_by']._fwd_index.keys() userids = set(creators) | set(modifiers) for userid in userids: if userid not in profiles: if former_id not in profiles: workflow = get_workflow(IProfile, 'security') former_id = make_unique_name(profiles, 'formeruser') print "Creating profile for former user content:", former_id former_profile = create_content(IProfile, firstname='Former', lastname='User') profiles[former_id] = former_profile workflow.initialize(former_profile) workflow.transition_to_state(former_profile, None, 'inactive') count, docids, resolver = search(creator=userid) for docid in docids: doc = resolver(docid) print "Updating 'creator' for", resource_path(doc) doc.creator = former_id count, docids, resolver = search(modified_by=userid) for docid in docids: doc = resolver(docid) print "Updating 'modified_by' for", resource_path(doc) doc.modified_by = former_id
def create(self, profiles): element = self.element login = self._element_value(element, 'username') username = login.replace(' ', '') password = get_random_password() groups = self._groups(element) users = find_users(profiles) users.add(username, login, password, groups, encrypted=False) profile = create_content(IProfile) profiles[username] = profile self._populate(profile) workflow = get_workflow(IProfile, 'security', profile) if workflow is not None: workflow.initialize(profile) profile.created_by = profile.modified_by = username profile.created = profile.modified = datetime.datetime.now() # Profile was indexed before workflow was initialized, so there is a # a bogus value for the 'allowed' index. Unfortunately, we can't just # add the profile to the profiles folder (which triggers indexing) # after the workflow is initialized, because the workflow # initialization code for profiles requires that the profile already # be in the content tree since a call to 'find_users' is made. The # work around is to just remove the profile and add it back again to # trigger reindexing. del profiles[username] profiles[username] = profile
def handle_submit(self, converted): context = self.context request = self.request # create the page and store it creator = authenticated_userid(request) page = create_content(IPage, converted['title'], converted['text'], extract_description(converted['text']), creator, ) name = make_unique_name(context, converted['title']) context[name] = page # tags and attachments set_tags(page, request, converted['tags']) attachments_folder = page['attachments'] upload_attachments(converted['attachments'], attachments_folder, creator, request) relocate_temp_images(page, request) # update ordering if in ordered container if hasattr(context, 'ordering'): context.ordering.add(name) location = resource_url(page, request) self.filestore.clear() return HTTPFound(location=location)
def evolve(root): former_id = 'formeruser' profiles = find_profiles(root) search = ICatalogSearch(root) catalog = find_catalog(root) creators = catalog['creator']._fwd_index.keys() modifiers = catalog['modified_by']._fwd_index.keys() userids = set(creators) | set(modifiers) for userid in userids: if userid not in profiles: if former_id not in profiles: workflow = get_workflow(IProfile, 'security') former_id = make_unique_name(profiles, 'formeruser') print "Creating profile for former user content:", former_id former_profile = create_content( IProfile, firstname='Former', lastname='User' ) profiles[former_id] = former_profile workflow.initialize(former_profile) workflow.transition_to_state(former_profile, None, 'inactive') count, docids, resolver = search(creator=userid) for docid in docids: doc = resolver(docid) print "Updating 'creator' for", model_path(doc) doc.creator = former_id count, docids, resolver = search(modified_by=userid) for docid in docids: doc = resolver(docid) print "Updating 'modified_by' for", model_path(doc) doc.modified_by = former_id
def handle_photo_upload(context, form): upload = form.get("photo", None) if upload is not None and upload.file is not None: request = get_current_request() userid = authenticated_userid(request) upload_file = upload.file if hasattr(upload, "type"): upload_type = upload.type # FieldStorage else: upload_type = upload.mimetype # Formish File object assert upload_type photo = create_content( ICommunityFile, title="Photo of " + context.title, stream=upload_file, mimetype=upload_type, filename=basename_of_filepath(upload.filename), creator=userid, ) if not photo.is_image: transaction.get().doom() raise Invalid({"photo": "Uploaded file is not a valid image."}) if "photo" in context: del context["photo"] alsoProvides(photo, IPhoto) context["photo"] = photo check_upload_size(context, photo, "photo") # Handle delete photo (ignore if photo also uploaded) elif form.get("photo_delete", False) or (upload and upload.metadata.get("remove", False)): if "photo" in context: del context["photo"]
def handle_submit(self, converted): context = self.context request = self.request workflow = self.workflow name = make_unique_name(context, converted['title']) creator = authenticated_userid(request) folder = create_content(ICommunityFolder, converted['title'], creator, ) context[name] = folder if workflow is not None: workflow.initialize(folder) if 'security_state' in converted: workflow.transition_to_state(folder, request, converted['security_state']) # Tags, attachments, alerts set_tags(folder, request, converted['tags']) # Make changes post-creation based on policy in src/osi customizer = queryMultiAdapter((folder, request), IFolderCustomizer) if customizer: for interface in customizer.markers: alsoProvides(folder, interface) location = model_url(folder, request) return HTTPFound(location=location)
def handle_submit(self, converted): context = self.context request = self.request workflow = self.workflow name = make_unique_name(context, converted['title']) creator = authenticated_userid(request) topic = create_content(IForumTopic, converted['title'], converted['text'], creator, ) topic.description = extract_description(converted['text']) context[name] = topic # Set up workflow if workflow is not None: workflow.initialize(topic) if 'security_state' in converted: workflow.transition_to_state(topic, request, converted['security_state']) # Tags and attachments set_tags(context, request, converted['tags']) if support_attachments(topic): upload_attachments(converted['attachments'], topic['attachments'], creator, request) location = model_url(topic, request) return HTTPFound(location=location)
def handle_submit(self, converted): request = self.request context = self.context #create the news item and store it creator = authenticated_userid(request) newsitem = create_content( INewsItem, title=converted['title'], text=converted['text'], creator=creator, publication_date=converted['publication_date'], caption=converted['caption'], ) name = make_unique_name(context, converted['title']) context[name] = newsitem relocate_temp_images(newsitem, request) # tags, attachments, and photos set_tags(newsitem, request, converted['tags']) attachments_folder = newsitem['attachments'] upload_attachments(converted['attachments'], attachments_folder, creator, request) try: handle_photo_upload(newsitem, converted) except Invalid, e: raise ValidationError(**e.error_dict)
def handle_submit(self, validated): context = self.context request = self.request name = make_unique_name(context, validated['title']) creator = authenticated_userid(request) text = safe_html(validated['description']) topic = create_content(IForumTopic, validated['title'], text, creator, ) if text: topic.description = extract_description(text) else: topic.description = validated['title'] context[name] = topic if request.POST.get('return_to') is not None: location = request.POST['return_to'] return render_template_to_response('templates/javascript_redirect.pt', url=location) else: location = model_url(topic, request) return HTTPFound(location=location)
def upload_attachments(attachments, folder, creator, request): """ This creates *and removes* attachments based on information retrieved from a form""" for attachment in attachments: if attachment.filename: mimetype = get_upload_mimetype(attachment) filename = make_unique_name( folder, basename_of_filepath(attachment.filename)) folder[filename] = obj = create_content( ICommunityFile, title=filename, stream=attachment.file, mimetype=mimetype, filename=filename, creator=creator, ) max_size = int(get_setting(folder, 'upload_limit', 0)) if max_size and obj.size > max_size: msg = 'File size exceeds upload limit of %d.' % max_size raise ValueError(msg) else: meta = attachment.metadata if meta.get('remove') and meta.get('default'): name = meta['default'] if name in folder: ob = folder[name] if has_permission('delete', ob, request): del folder[name]
def handle_submit(self, converted): context = self.context request = self.request workflow = self.workflow name = make_unique_name(context, converted['title']) creator = authenticated_userid(request) topic = create_content(IForumTopic, converted['title'], converted['text'], creator, ) topic.description = extract_description(converted['text']) context[name] = topic # Set up workflow if workflow is not None: workflow.initialize(topic) if 'security_state' in converted: workflow.transition_to_state(topic, request, converted['security_state']) # send the temp images to their final place relocate_temp_images(topic, request) # Tags and attachments set_tags(topic, request, converted['tags']) if support_attachments(topic): upload_attachments(converted['attachments'], topic['attachments'], creator, request) location = resource_url(topic, request) return HTTPFound(location=location)
def __init__(self, communities_name=None): super(Site, self).__init__() self.catalog = CachingCatalog() self.update_indexes() self.catalog.document_map = DocumentMap() profiles = create_content(IProfiles) self['profiles'] = profiles communities = create_content(ICommunities) self.communities_name = communities_name or 'communities' self[self.communities_name] = communities self.users = KARLUsers(self) self.tags = TopicFilteredTags(self) self.sessions = SessionDataManager(3600, 5) self.filestore = PersistentMapping() self.list_aliases = OOBTree() self['signup'] = Folder()
def test_create_content(self): self._setupContentTypes() from repoze.lemonade.tests.fixtureapp import content from repoze.lemonade.content import create_content ob = create_content(content.IFoo, 'arg1', kw1='kw1', kw2='kw2') self.failUnless(isinstance(ob, content.Foo)) self.assertEqual(ob.arg, ('arg1',)) self.assertEqual(ob.kw, {'kw1':'kw1', 'kw2':'kw2'})
def __init__(self): super(Site, self).__init__() self.catalog = CachingCatalog() self.update_indexes() self.catalog.document_map = DocumentMap() profiles = create_content(IProfiles) self['profiles'] = profiles communities = create_content(ICommunities) self['communities'] = communities people = create_content(IPeopleDirectory) self['people'] = people self.users = KARLUsers(self) self.tags = Tags(self) self.sessions = SessionDataManager(3600, 5) self.filestore = PersistentMapping() self.list_aliases = OOBTree()
def _create_front_page(self): self['front_page'] = create_content( IWikiPage, u'Front Page', FRONT_PAGE_CONTENT, FRONT_PAGE_DESCRIPTION, self.creator, )
def test_create_content(self): self._setupContentTypes() from repoze.lemonade.tests.fixtureapp import content from repoze.lemonade.content import create_content ob = create_content(content.IFoo, 'arg1', kw1='kw1', kw2='kw2') self.failUnless(isinstance(ob, content.Foo)) self.assertEqual(ob.arg, ('arg1', )) self.assertEqual(ob.kw, {'kw1': 'kw1', 'kw2': 'kw2'})
def calendar_setup_layers_view(context, request): form = CalendarLayersForm() default_layer_name = ICalendarLayer.getTaggedValue('default_name') layers = filter(lambda x: x.__name__ != default_layer_name, _get_calendar_layers(context)) layer_titles = [ x.title for x in layers] layer_names = [ x.__name__ for x in layers ] default_category_name = ICalendarCategory.getTaggedValue('default_name') categories = filter(lambda x: x.__name__ != default_category_name, _get_calendar_categories(context)) if 'form.delete' in request.POST: layer_name = request.POST['form.delete'] if layer_name == default_layer_name: message = 'Cannot delete default layer' elif layer_name and layer_name in layer_names: title = context[layer_name].title del context[layer_name] message = '%s layer removed' % title else: message = 'Layer is invalid' location = model_url(context, request, 'layers.html', query={'status_message': message}) return HTTPFound(location=location) fielderrors_target = None fielderrors = {} if 'form.submitted' in request.POST: try: converted = form.validate(request.POST) category_paths = list(set(request.POST.getall('category_paths'))) layer_name = generate_name(context) layer_title = converted['layer_title'] layer_color = converted['layer_color'] if layer_title in layer_titles: msg = "Name is already used" raise Invalid(value=layer_title, state=None, msg=msg, error_list=None, error_dict={'layer_title': msg}) layer = create_content(ICalendarLayer, layer_title, layer_color, category_paths) context[layer_name] = layer location = model_url( context, request, 'layers.html', query={'status_message':'Calendar layer added'}) return HTTPFound(location=location) except Invalid, e: fielderrors_target = '__add_layer__' fielderrors = e.error_dict
def add(self, context, request): intranets = create_content(IIntranetsTool) context['intranets'] = intranets # Mark the context (e.g. /osi) as providing IIntranets alsoProvides(context, IIntranets) # Since context now provides IIntranets it needs a feature context.feature = u''
def evolve(site): """ upgrade site settings """ if 'invitations' in site: del site['invitations'] if hasattr(site, 'invitations'): del site.invitations site['invitations'] = create_content(IInvitationsFolder)
def handle_submit(self, converted): request = self.request context = self.context name = make_name(context, converted['title']) userid = authenticated_userid(request) community = create_content( ICommunity, converted['title'], converted['description'], converted['text'], userid, ) community.sendalert_default = converted.get('sendalert_default', True) # this *must* directly follow content creation because the # toolinfo add stuff depends on the community having a full # path. context[name] = community # required to use moderators_group_name and # members_group_name community.__name__ = name tools_present = [] for toolinfo in self.available_tools: if toolinfo['name'] in converted.get('tools', []): toolinfo['component'].add(community, request) tools_present.append(toolinfo['name']) # Set the default tool if converted.get('default_tool') in tools_present: community.default_tool = converted['default_tool'] else: community.default_tool = None users = find_users(context) moderators_group_name = community.moderators_group_name members_group_name = community.members_group_name for group_name in moderators_group_name, members_group_name: users.add_group(userid, group_name) if self.workflow is not None: if 'security_state' in converted: self.workflow.transition_to_state(community, request, converted['security_state']) # Save the tags on it. set_tags(community, request, converted['tags']) # Adding a community should take you to the Add Existing # User screen, so the moderator can include some users. location = resource_url(community, request, 'members', 'add_existing.html', query={'status_message': 'Community added'}) return HTTPFound(location=location)
def add_sample_users(site): profiles = site['profiles'] users = site.users for login, firstname, lastname, email, groups in [ ('staff1','Staff','One','*****@*****.**', ('group.KarlStaff',)), ('staff2','Staff','Two','*****@*****.**', ('group.KarlStaff',)), ('staff3','Staff','Three','*****@*****.**', ('group.KarlStaff',)), ('staff4','Staff','Four','*****@*****.**', ('group.KarlStaff',)), ('staff5','Staff','Five','*****@*****.**', ('group.KarlStaff',)), ('staff6','Staff','Six','*****@*****.**', ('group.KarlStaff',)), ('staff7','Staff','Seven','*****@*****.**', ('group.KarlStaff',)), ('staff8','Staff','Eight','*****@*****.**', ('group.KarlStaff',)), ('staff9','Staff','Nine','*****@*****.**', ('group.KarlStaff',)), ('affiliate1','Affiliate','One','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate2','Affiliate','Two','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate3','Affiliate','Three','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate4','Affiliate','Four','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate5','Affiliate','Five','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate6','Affiliate','Six','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate7','Affiliate','Seven','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate8','Affiliate','Eight','*****@*****.**', ('groups.KarlAffiliate',)), ('affiliate9','Affiliate','Nine','*****@*****.**', ('groups.KarlAffiliate',)), ]: if users.get(login=login) is None: users.add(login, login, login, groups) if not login in profiles: profile = profiles[login] = create_content( IProfile, firstname=firstname, lastname=lastname, email=email, ) workflow = get_workflow(IProfile, 'security', profiles) if workflow is not None: workflow.initialize(profile)
def _addAttachments(att_folder, info, attachments): for filename, mimetype, data in attachments: stream = StringIO(data) name = make_unique_name(att_folder, filename) attachment = create_content( ICommunityFile, title=filename, stream=stream, mimetype=mimetype, filename=filename, creator=info['author'], ) att_folder[name] = attachment
def test_content_factory(self): from repoze.lemonade.testing import registerContentFactory from repoze.lemonade.content import create_content from karl.models.interfaces import IInvitation class DummyInvitation: def __init__(self, email): self.email = email registerContentFactory(DummyInvitation, IInvitation) invitation = create_content(IInvitation, u'[email protected]') self.failUnless(invitation.__class__ is DummyInvitation) self.assertEqual(invitation.email, u'[email protected]')
def test_default_view(self): #add container object root = self.app.root_factory(None) from adhocracy.core.models.interfaces import IChildsDict rootchilds = IChildsDict(root) tx = self.graph.start_transaction() from repoze.lemonade.content import create_content from adhocracy.core.models.container import IContainerMarker content = create_content(IContainerMarker) rootchilds["child"] = content self.graph.stop_transaction(tx) #test object traversal self.browser.open("http://localhost:6543/child") assert ("container" in self.browser.contents)
def __init__(self): super(Site, self).__init__() self.catalog = CachingCatalog() self.update_indexes() self.catalog.document_map = DocumentMap() profiles = create_content(IProfiles) self['profiles'] = profiles communities = create_content(ICommunities) self['communities'] = communities people = create_content(IPeopleDirectory) self['people'] = people self.users = KARLUsers(self) self.tags = Tags(self) self.sessions = SessionDataManager(3600, 5) self.filestore = PersistentMapping() self.list_aliases = OOBTree() self.settings = OOBTree(self._default_settings) self.access_requests = OOBTree() self.failed_login_attempts = OOBTree() self.email_templates = OOBTree() self.denial_tracker = OOBTree() self['email_images'] = EmailFolder() self['invitations'] = create_content(IInvitationsFolder)