def start(self, context, request, appstruct, **kw): user = get_current() context.state = PersistentList(['published']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() published = [context] if getattr(context, '_tree', None): tree = getattr(context, '_tree') request.get_site_folder.merge_tree(tree) getSite().merge_tree(tree) not_published_artists = [a for a in context.artists if 'published' not in a.state] published.extend(not_published_artists) for artist in not_published_artists: publish_artist(artist, request, user) not_published_directors = [a for a in context.directors if 'published' not in a.state] published.extend(not_published_directors) for director in not_published_directors: publish_artist(director, request, user) request.registry.notify(ActivityExecuted(self, published, user)) return {}
def start(self, context, request, appstruct, **kw): context.state = PersistentList(['published']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() if getattr(context, '_tree', None): tree = getattr(context, '_tree') request.get_site_folder.merge_tree(tree) getSite().merge_tree(tree) return {}
def start(self, context, request, appstruct, **kw): context.state = PersistentList(['published']) filters = getattr(context, 'filters', []) for filter_ in filters: tree = filter_.get('metadata_filter', {}).get('tree', None) if tree: request.get_site_folder.merge_tree(tree) getSite().merge_tree(tree) context.reindex() return {}
def keywords_choice(node, kw): root = getSite() values = [(k, k) for k in root.keywords_ids] values.insert(0, ('', _('- Select -'))) return Select2Widget( values=values, create=True)
def get_zipcodes(zipcodes, country=None): root = getSite() resourcemanager = root.resourcemanager queries = [] for zipcode in zipcodes: queries.append({"regexp": {"zipcode": zipcode}}) query = {"bool": {"should": queries, "minimum_should_match": 1}} if country: country_query = { "must": [{"match": {"country_name": {"query": country, "operator": "and"}}}]} query["bool"].update(country_query) result = resourcemanager.get_entries( key='city', query=query, params={"from": 0, "size": 100000}, fields=["zipcode"]) if result[1] == 0: return [] return result[0]
def start(self, context, request, appstruct, **kw): root = getSite() explanation = appstruct['explanation'] context.state = PersistentList(['archived']) context.reindex() user = context.author alert('internal', [root], [user], internal_kind=InternalAlertKind.moderation_alert, subjects=[context], alert_kind='object_archive') if getattr(user, 'email', ''): mail_template = root.get_mail_template( 'archive_content_decision', user.user_locale) subject = mail_template['subject'].format( subject_title=context.title) email_data = get_user_data(user, 'recipient', request) email_data.update(get_entity_data(context, 'subject', request)) message = mail_template['template'].format( explanation=explanation, novaideo_title=root.title, **email_data ) alert('email', [root.get_site_sender()], [user.email], subject=subject, body=message) return {}
def get_zipcodes_from_cities(cities, country=None): root = getSite() resourcemanager = root.resourcemanager queries = [] for city in cities: queries.append({"match": {"city_normalized_name": city}}) query = {"bool": {"should": queries, "minimum_should_match": 1}} if country: country_query = { "must": [{"match": {"country_name": {"query": country, "operator": "and"}}}]} query["bool"].update(country_query) result = resourcemanager.get_entries( key='city', query=query, params={"from": 0, "size": 100000}, fields=["zipcode"]) if result[1] == 0: return [] result = list(set([str(item) for c in result[0] for item in c['fields']['zipcode']])) return result
def challenge_choice(node, kw): request = node.bindings['request'] root = getSite() values = [('', _('- Select -'))] def title_getter(id): try: obj = get_obj(int(id), None) if obj: return obj.title else: return id except Exception as e: log.warning(e) return id ajax_url = request.resource_url( root, '@@novaideoapi', query={'op': 'find_challenges'}) return AjaxSelect2Widget( values=values, ajax_url=ajax_url, ajax_item_template="related_item_template", title_getter=title_getter, multiple=False, page_limit=20, add_clear=True, item_css_class='challenge-input')
def find_advertistings(self): #TODO frequence root = getSite() context, is_root = self.get_context(root) keywords = [] if hasattr(context, 'get_all_keywords'): keywords = list(context.get_all_keywords()) else: keywords = list(getattr(context, 'keywords', [])) if not keywords: keywords = [ROOT_TREE] advertisings = getattr(self.request, 'cache_advertisings', None) if advertisings is None: site = str(get_oid(self.request.get_site_folder)) advertisings = find_entities( interfaces=[IWebAdvertising], keywords=keywords, metadata_filter={'states': ['published']}, other_filter={'sources': [site]}, force_publication_date=True) self.request.cache_advertisings = advertisings advertisings = [a for a in advertisings if self.name in getattr(a, 'positions', [])] if not is_root: advertisings = sorted( advertisings, key=lambda e: getattr(e, 'tree', {}).get(ROOT_TREE, {}) and 1 or 2) return advertisings
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() artist = appstruct['_object_data'] root.addtoproperty('artists', artist) artist.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', artist), )) artist.setproperty('author', user) artist.add_contributors(context.contributors) artist.add_contributors([user]) artist.setproperty('original', context) artist.set_metadata(appstruct) artist.hash_picture_fp() artist.hash_artist_data() source = request.GET.get('source', '') if source: source_artist = get_obj(int(source)) if source_artist: replaced = source_artist.replace_by(artist) if replaced: request.registry.notify(ObjectReplaced( old_object=source_artist, new_object=artist )) root.delfromproperty('artists', source_artist) artist.reindex() request.registry.notify(ActivityExecuted(self, [artist], user)) return {'newcontext': artist}
def start(self, context, request, appstruct, **kw): root = getSite() copy_of_amendment = copy(context, (context.proposal, 'amendments'), omit=('created_at', 'modified_at', 'explanations')) keywords_ids = appstruct.pop('keywords') result, newkeywords = root.get_keywords(keywords_ids) for nkw in newkeywords: root.addtoproperty('keywords', nkw) result.extend(newkeywords) appstruct['keywords_ref'] = result copy_of_amendment.set_data(appstruct) copy_of_amendment.text = normalize_text(copy_of_amendment.text) copy_of_amendment.setproperty('originalentity', context) copy_of_amendment.state = PersistentList(['draft']) copy_of_amendment.setproperty('author', get_current()) localizer = request.localizer # copy_of_amendment.title = context.proposal.title + \ # localizer.translate(_('_Amended version ')) + \ # str(getattr(context.proposal, # '_amendments_counter', 1)) copy_of_amendment.title = localizer.translate(_('Amended version ')) + \ str(getattr(context.proposal, '_amendments_counter', 1)) grant_roles(roles=(('Owner', copy_of_amendment), )) copy_of_amendment.text_diff = get_text_amendment_diff( context.proposal, copy_of_amendment) copy_of_amendment.reindex() context.proposal._amendments_counter = getattr(context.proposal, '_amendments_counter', 1) + 1 context.reindex() return {'newcontext': copy_of_amendment}
def start(self, context, request, appstruct, **kw): site = get_site_folder(True, request) user = get_current(request) is_manager = has_any_roles( user=user, roles=('Admin', ('SiteAdmin', site))) or\ is_site_moderator(request) if is_manager or all(has_role(user=user, role=('Owner', v)) for v in appstruct['targets'] if 'published' not in v.state): root = getSite() source = appstruct['source'] targets = appstruct['targets'] for artist in targets: replaced = artist.replace_by(source) if replaced: request.registry.notify(ObjectReplaced( old_object=artist, new_object=source )) root.delfromproperty('artists', artist) else: return {'error': True} return {}
def start(self, context, request, appstruct, **kw): correlation = appstruct['_object_data'] correlation.setproperty('source', context) correlation.setproperty('author', get_current()) root = getSite() root.addtoproperty('correlations', correlation) return {}
def publish_artist(context, request=None, user=None): context.state = PersistentList(['published']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.origin_oid = get_oid(context) site = get_site_folder(True, request) root = getattr(request, 'root', None) if request else getSite() author = getattr(context, 'author', None) if author and user is not author: alert('internal', [site], [author], {'kind': InternalAlertKind.moderation_alert, 'subjects': [context]}) original = context.original if original: replaced = original.replace_by(context) if replaced: request.registry.notify(ObjectReplaced( old_object=original, new_object=context )) author = getattr(original, 'author', None) if author and user is not author: alert('internal', [site], [author], {'kind': InternalAlertKind.content_alert, 'subjects': [context], 'alert_kind': 'replaced', 'replaced_title': original.title}) root.delfromproperty('artists', original) context.reindex()
def update(self): self.execute(None) root = getSite() try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(root, '')) result = {} user = get_current() parent = self.context.__parent__ can_access_parent = False if not (parent is root) and can_access(user, parent): can_access_parent = True values = {'object': self.context, 'navbar_body': navbars['navbar_body'], 'can_access_parent': can_access_parent} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def artists_choice(node, kw): context = node.bindings['context'] request = node.bindings['request'] root = getSite() values = [] if context is not root: values = [(a.get_id(), a.title) for a in context.artists] ajax_url = request.resource_url(context, '@@creationculturelapi', query={'op': 'find_artists'}) def title_getter(id): try: obj = get_obj(int(id), None) if obj: return obj.title else: return id except Exception as e: log.warning(e) return id return AjaxSelect2Widget( values=values, ajax_url=ajax_url, css_class="artists-container review-artists", multiple=True, create=True, title_getter=title_getter, ajax_item_template="artist_item_template", ajax_selection_template='formatArtist' )
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current(request) mask = user.get_mask(root) if hasattr(user, 'get_mask') else user author = mask if appstruct.get('anonymous', False) and mask else user answer = appstruct['_object_data'] context.addtoproperty('answers', answer) answer.init_title() answer.format(request) answer.state = PersistentList(['published']) answer.reindex() if getattr(answer, 'option', None) is not None: answer.question.add_selected_option(user, answer.option) transaction.commit() grant_roles(user=author, roles=(('Owner', answer), )) answer.setproperty('author', author) if appstruct.get('associated_contents', []): answer.set_associated_contents( appstruct['associated_contents'], author) self._alert_users(context, request, author, answer) context.reindex() user.set_read_date(answer.channel, datetime.datetime.now(tz=pytz.UTC)) return {}
def add(self): user = get_current() path = self.params('path') dir_ = None if path is not None: #dir_ = traversal.traverse(self.context, path).get('context', None) dir_ = get_file(path) if dir_ is None: dir_ = user field_storage = self.params('newfile') new_img = Image( fp=field_storage.file, title=field_storage.filename) new_img.mimetype = field_storage.type new_img.fp.seek(0) if hasattr(dir_, 'files'): dir_.addtoproperty('files', new_img) else: root = getSite() root.addtoproperty('files', new_img) grant_roles(user=user, roles=(('Owner', new_img), )) result = { 'Path': get_file_url(new_img, self.request), 'Name': new_img.title, 'Code': 0 } return '<textarea>'+json.dumps(result)+'</textarea>'
def remind_users_evolve(root, registry): from lac.ips.mailer import mailer_send from lac.utilities.utils import to_localized_time from lac.mail import ( PREREGISTRATION_SUBJECT, PREREGISTRATION_MESSAGE) root = getSite() request = get_current_request() site = request.get_site_folder for preregistration in root.preregistrations: url = request.resource_url(preregistration, "") deadline_date = preregistration.init_deadline( datetime.datetime.now(tz=pytz.UTC)) localizer = request.localizer deadline_str = to_localized_time( deadline_date, request, format_id='defined_literal', ignore_month=True, ignore_year=True, translate=True) log.info(getattr(preregistration, 'title', 'user')) message = PREREGISTRATION_MESSAGE.format( preregistration=preregistration, user_title=localizer.translate( _(getattr(preregistration, 'user_title', ''))), url=url, deadline_date=deadline_str.lower(), lac_title=request.root.title) mailer_send(subject=PREREGISTRATION_SUBJECT, recipients=[preregistration.email], sender=site.get_site_sender(), body=message) log.info('Remind users evolved.')
def update(self): self.execute(None) root = getSite() try: navbars = generate_navbars( self.request, self.context) except ObjectRemovedException: return HTTPFound(self.request.resource_url(root, '')) user = self.get_binding('user') is_censored = 'censored' in self.context.state to_hide = is_censored and not has_any_roles( user=user, roles=(('Owner', self.context), 'Moderator')) evaluation_chart = render_object_evaluation_stat(self.context, self.request) examination_chart = render_object_examination_stat(self.context, self.request) result = {} values = { 'challenge': self.context, 'to_hide': to_hide, 'is_censored': is_censored, 'text': self.context.text, 'current_user': user, 'navbar_body': navbars['navbar_body'], 'footer_body': navbars['footer_body'], 'evaluation_chart': evaluation_chart, 'examination_chart': examination_chart } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['isactive'] = True result['coordinates'] = {self.coordinates: [item]} # result.update(resources) return result
def start(self, context, request, appstruct, **kw): newsletter = appstruct.pop('newsletter') user = appstruct.pop('user', None) if user and getattr(newsletter, 'allow_unsubscribing', True): parts = user.split('@@') key = parts[0] user_id = parts[1] subscribed = newsletter.subscribed.get(key, None) if subscribed and user_id == subscribed.get('id', None): newsletter.subscribed.pop(key) first_name = subscribed.get('first_name') last_name = subscribed.get('last_name') email = subscribed.get('email') root = getSite() mail_template = root.get_mail_template( 'newsletter_unsubscription') email_data = get_entity_data( newsletter, 'newsletter', request) subject = mail_template['subject'].format( newsletter_title=newsletter.title, novaideo_title=root.title) mail = mail_template['template'].format( first_name=first_name, last_name=last_name, novaideo_title=root.title, **email_data) alert('email', [root.get_site_sender()], [email], subject=subject, body=mail) return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) result = {} user = get_current() related_contents, len_contents = self.get_related_contents(user) values = { 'object': self.context, 'state': get_states_mapping(user, self.context, self.context.state[0]), 'related_contents': related_contents, 'len_contents': len_contents, 'navbar_body': navbars['navbar_body'], 'actions_bodies': navbars['body_actions'], 'footer_body': navbars['footer_body'], 'get_oid': get_oid, 'is_portalmanager': has_role(user=user, role=('PortalManager',)) } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): self.execute(None) try: navbars = generate_navbars(self.request, self.context) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) user = get_current() subfolders = [sf for sf in self.context.children if can_access(user, sf)] subfolders = sorted(subfolders, key=lambda e: e.get_order()) result_body, result = render_listing_objs( self.request, subfolders, user) values = {'object': self.context, 'subfolders': result_body, 'navbar_body': navbars['navbar_body'], 'body_actions': navbars['body_actions'] } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): email = appstruct.pop('email') newnewsletters = appstruct.pop('newsletters') first_name = appstruct.get('first_name') last_name = appstruct.get('last_name') random_key = gen_random_token() root = getSite() mail_template = root.get_mail_template('newsletter_subscription') for newsletter in newnewsletters: newsletter.subscribe(first_name, last_name, email, random_key) url = request.resource_url( context, '@@userunsubscribenewsletter', query={'oid': get_oid(newsletter), 'user': email+'@@'+random_key}) email_data = get_entity_data( newsletter, 'newsletter', request) subject = mail_template['subject'].format( newsletter_title=newsletter.title, novaideo_title=root.title) mail = mail_template['template'].format( first_name=first_name, last_name=last_name, unsubscribeurl=url, novaideo_title=root.title, **email_data) alert('email', [root.get_site_sender()], [email], subject=subject, body=mail) return {}
def remind_state_validation(process, context): root = getSite() moderate_registration = getattr(root, 'moderate_registration', False) if moderate_registration: return 'accepted' in context.state return True
def start(self, context, request, appstruct, **kw): from ..proposal_management.behaviors import exclude_participant_from_wg root = getSite() context.state.remove('active') context.state.append('deactivated') context.set_organization(None) proposals = getattr(context, 'participations', []) anonymous_proposals = getattr(context.mask, 'participations', []) for proposal in proposals: exclude_participant_from_wg( proposal, request, context, root) for proposal in anonymous_proposals: exclude_participant_from_wg( proposal, request, context.mask, root) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() pref_author = list(get_users_by_preferences(context)) alert('internal', [request.root], pref_author, internal_kind=InternalAlertKind.content_alert, subjects=[context], alert_kind='user_deactivated') request.registry.notify(ActivityExecuted( self, [context], get_current())) return {}
def _alert_users(self, context, request, user, answer): root = getSite() users = self._get_users_to_alerts(context, request) if user in users: users.remove(user) author_data = get_user_data(user, 'author', request) alert_data = get_entity_data(answer, 'comment', request) alert_data.update(author_data) alert('internal', [root], users, internal_kind=InternalAlertKind.content_alert, alert_kind='new_answer', subjects=[context], **alert_data) subject_data = get_entity_data(context, 'subject', request) alert_data.update(subject_data) for user_to_alert in [u for u in users if getattr(u, 'email', '')]: mail_template = root.get_mail_template( 'alert_answer', user_to_alert.user_locale) subject = mail_template['subject'].format( **subject_data) email_data = get_user_data(user_to_alert, 'recipient', request) email_data.update(alert_data) message = mail_template['template'].format( novaideo_title=root.title, **email_data ) alert('email', [root.get_site_sender()], [user_to_alert.email], subject=subject, body=message)
def announcement_choice(node, kw): context = node.bindings['context'] request = node.bindings['request'] root = getSite() values = [] if context is not root: announcement = context.announcement if announcement: values = [(get_oid(announcement), announcement.title)] ajax_url = request.resource_url(context, '@@creationculturelapi', query={'op': 'find_cultural_events'}) def title_getter(id): try: obj = get_obj(int(id), None) if obj: return obj.title else: return id except Exception as e: log.warning(e) return id return AjaxSelect2Widget( values=values, ajax_url=ajax_url, multiple=False, title_getter=title_getter )
def start(self, context, request, appstruct, **kw): root = getSite() comment = appstruct['_object_data'] user = get_current(request) mask = user.get_mask(root) author = mask if appstruct.get('anonymous', False) and mask else user channel = root.channel #TODO get if channel: channel.addtoproperty('comments', comment) channel.add_comment(comment) comment.state = PersistentList(['published']) comment.reindex() comment.format(request) comment.setproperty('author', author) grant_roles(user=author, roles=(('Owner', comment), )) if appstruct.get('associated_contents', []): comment.set_associated_contents( appstruct['associated_contents'], user) self._alert_users(context, request, author, comment, channel) context.reindex() user.set_read_date(channel, datetime.datetime.now(tz=pytz.UTC)) return {}
def __call__(self): root = getSite() search_action, search_view = _getaction(self, 'novaideoviewmanager', 'search') search_view_instance = search_view(root, self.request, behaviors=[search_action]) search_view_instance.viewid = 'usermenu' + search_view_instance.viewid posted_formid = None if self.request.POST : if '__formid__' in self.request.POST: posted_formid = self.request.POST['__formid__'] if posted_formid and \ posted_formid.startswith(search_view_instance.viewid): search_view_instance.postedform = self.request.POST.copy() self.request.POST.clear() search_view_instance.schema = select(search_view_instance.schema, ['text_to_search']) search_view_result = search_view_instance() search_body = '' if isinstance(search_view_result, dict) and \ 'coordinates' in search_view_result: search_body = search_view_instance.render_item( search_view_result['coordinates'][search_view_instance.coordinates][0], search_view_instance.coordinates, None) result = {} result['search_body'] = search_body result['view'] = self return result
def start(self, context, request, appstruct, **kw): root = getSite() mail_template = root.get_mail_template('invitation') localizer = request.localizer roles_translate = [ localizer.translate(APPLICATION_ROLES.get(r, r)) for r in getattr(context, 'roles', []) ] subject = mail_template['subject'].format(novaideo_title=root.title) email_data = get_user_data(context, 'recipient', request) email_data.update(get_entity_data(context, 'invitation', request)) message = mail_template['template'].format( roles=", ".join(roles_translate), novaideo_title=root.title, **email_data) alert('email', [root.get_site_sender()], [context.email], subject=subject, body=message) context.state.remove('refused') context.state.append('pending') return {}
def start(self, context, request, appstruct, **kw): challenges = find_entities(interfaces=[IChallenge], metadata_filter={'states': ['pending']}) for challenge in challenges: if challenge.is_expired: challenge.state = PersistentList(['closed', 'published']) challenge.reindex() root = getSite() users = find_entities(interfaces=[IPerson], metadata_filter={'states': ['active']}) time_constant = getattr(root, 'time_constant', 6) for user in users: user.calculate_confidence_index(time_constant) events = find_entities(interfaces=[IEvent], metadata_filter={'states': ['published']}) for event in events: event.update() return {}
def evolve_related_correlation(root, registry): from novaideo.views.filter import find_entities from novaideo.content.interface import IComment, IAnswer contents = find_entities(interfaces=[IComment, IAnswer]) root = getSite() len_entities = str(len(contents)) for index, node in enumerate(contents): if node.related_correlation: targets = node.related_correlation.targets if node in targets: targets.remove(node) node.set_associated_contents(targets, node.related_correlation.author) root.delfromproperty('correlations', node.related_correlation) node.reindex() log.info(str(index) + "/" + len_entities) log.info('Related correlations evolved')
def bind(self): bindings = {} bindings['navbars'] = None bindings['vote_actions'] = None vote_actions = get_vote_actions_body(self.context, self.request) try: navbars = generate_navbars(self.request, self.context, text_action=vote_actions['activators']) bindings['navbars'] = navbars bindings['vote_actions'] = vote_actions except ObjectRemovedException: return bindings['user'] = get_current() bindings['root'] = getSite() bindings['is_censored'] = 'censored' in self.context.state bindings['to_hide'] = bindings['is_censored'] and not has_any_roles( user=bindings['user'], roles=(('Owner', self.context), 'Moderator')) setattr(self, '_bindings', bindings)
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current(request) mask = user.get_mask(root) if hasattr(user, 'get_mask') else user author = mask if appstruct.get('anonymous', False) and mask else user idea = appstruct['_object_data'] root.addtoproperty('ideas', idea) idea.state.append('to work') grant_roles(user=author, roles=(('Owner', idea), )) idea.setproperty('author', author) idea.subscribe_to_channel(user) if isinstance(context, (Comment, Answer)): content = context.subject correlations = connect( content, [idea], {'comment': context.comment, 'type': getattr(context, 'intention', 'Transformation from another content')}, author, ['transformation'], CorrelationType.solid) for correlation in correlations: correlation.setproperty('context', context) context_type = context.__class__.__name__.lower() # Add Nia comment alert_comment_nia( idea, request, root, internal_kind=InternalAlertKind.content_alert, subject_type='idea', alert_kind='transformation_'+context_type, content=context ) idea.format(request) idea.reindex() request.registry.notify(ActivityExecuted(self, [idea], author)) return {'newcontext': idea}
def smartfolder_deserializer(args): root = getSite() children = args.get('children', []) for subfolder in children: root.addtoproperty('smart_folders', subfolder) if 'style' not in args: args['style'] = {"usual_color": "white, black", "hover_color": "white, black"} if 'filters' not in args: args['filters'] = [FILTER_DEFAULT_DATA] else: new_filters = args['filters'] for new_filter in new_filters: keys = [key for key in FILTER_DEFAULT_DATA if key not in new_filter] for key in keys: new_filter[key] = FILTER_DEFAULT_DATA[key] args['filters'] = new_filters return args
def has_role(role, user=None, ignore_superiors=False, root=None): if root is None: root = getSite() if user is None: user = get_current() normalized_roles = {} if len(role) == 1: role = (role[0], root) normalized_roles[role[0]] = role[1] if not ignore_superiors: normalized_roles.update(dict(_get_allsuperiors(role[0], root))) if isinstance(user, Anonymous): return RoleAnonymous.name in normalized_roles #TODO use cookies to find roles if 'Admin' in normalized_roles: principals = find_service('principals') sd_admin = principals['users']['admin'] if sd_admin is user: return True groups = list(getattr(user, 'user_groups', [])) groups.append(user) for role in normalized_roles: context = normalized_roles[role] opts = { u'source_id': ('any', tuple(sorted([get_oid(g) for g in groups]))), u'target_id': get_oid(context) } opts[u'relation_id'] = role opts[u'reftype'] = 'Role' if find_relations(root, opts): return True return False
def merge_artists(artists): root = getSite() new_artists = [] from lac.utilities.duplicates_utility import (find_duplicates_artist) for artist in artists: old_artists = find_duplicates_artist(artist) published_old_artists = [ a for a in old_artists if 'published' in a.state ] if old_artists: old_artist = published_old_artists[0] if \ published_old_artists else old_artists[0] new_artists.append(old_artist) else: new_artists.append(artist) artist.state = PersistentList(['editable']) root.addtoproperty('artists', artist) artist.reindex() import transaction transaction.commit() return new_artists
def get_users_with_role(role=None, root=None): if role is None: return [] if root is None: root = getSite() normalized_role = role if isinstance(role, basestring): normalized_role = (role, root) opts = {u'target_id': get_oid(normalized_role[1])} opts[u'relation_id'] = normalized_role[0] opts[u'reftype'] = 'Role' users = list( set([r.source for r in find_relations(normalized_role[1], opts).all()])) result = [u for u in users if isinstance(u, User)] groups = [g.members for g in users if isinstance(g, Group)] groups = [item for sublist in groups for item in sublist] result.extend(groups) return list(set(result))
def start(self, context, request, appstruct, **kw): site_folder = appstruct['_object_data'] site_folder.modified_at = datetime.datetime.now(tz=pytz.UTC) site_folder.filters = PersistentList( getattr(site_folder, 'filters', [])) filters = getattr(site_folder, 'filters', []) root = getSite() for filter_ in filters: sources = filter_.get('other_filter', {}).get('sources', []) if sources and 'self' in sources: sources_ = list(sources) sources_.remove('self') sources_.append(str(get_oid(site_folder))) filter_['other_filter']['sources'] = list(set(sources_)) tree = filter_.get('metadata_filter', {}).get('tree', None) if tree: site_folder.merge_tree(tree) root.merge_tree(tree) site_folder.reindex() return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) result = {} user = get_current() site = get_site_folder(True, self.request) diff_marker = "#diff" values = { 'object': self.context, 'state': get_states_mapping( user, self.context, getattr(self.context, 'state_or_none', [None])[0]), 'navbar_body': navbars['navbar_body'], 'services_body': navbars['services_body'], 'footer_body': navbars['footer_body'], 'is_portalmanager': has_role(user=user, role=('PortalManager', )), 'tree_diff': json.dumps(tree_diff(site.tree, self.context.tree, diff_marker)), 'diff_marker': diff_marker } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result.update(self.requirements) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): self.execute(None) result = {} try: navbars = generate_navbars( self.request, self.context) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) history = getattr(self.context, 'annotations', {}).get( 'newsletter_history', []) values = {'object': self.context, 'len_subscribed': len(self.context.subscribed), 'footer_body': navbars['footer_body'], 'navbar_body': navbars['navbar_body']} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() artists, new_artists = extract_artists( appstruct.get('artists', []), request) directors, new_directors = extract_artists( appstruct.get('directors', []), request, is_directors=True) newfilmsynopses = appstruct[OBJECT_DATA] root.addtoproperty('reviews', newfilmsynopses) newfilmsynopses.state.append('draft') newfilmsynopses.setproperty('artists', artists) newfilmsynopses.setproperty('directors', directors) grant_roles(roles=(('Owner', newfilmsynopses), )) newfilmsynopses.setproperty('author', user) newfilmsynopses.set_metadata(appstruct) newfilmsynopses.reindex() new_objects = new_artists new_objects.extend(new_directors) new_objects.append(newfilmsynopses) request.registry.notify(ActivityExecuted(self, new_objects, user)) return {'newcontext': newfilmsynopses}
def start(self, context, request, appstruct, **kw): root = getSite() user = context.author last_version = context.version copy_of_idea = copy( context, (context, 'version'), new_name=context.__name__, select=('modified_at',), omit=('created_at',), roles=True) copy_of_idea.keywords = context.keywords copy_of_idea.setproperty('version', last_version) copy_of_idea.setproperty('originalentity', context.originalentity) if last_version is not None: grant_roles(user=user, roles=(('Owner', last_version), )) files = [f['_object_data'] for f in appstruct.pop('attached_files')] appstruct['attached_files'] = files copy_of_idea.state = PersistentList(['version', 'archived']) copy_of_idea.setproperty('author', user) note = appstruct.pop('note', '') context.note = note context.set_data(appstruct) context.modified_at = datetime.datetime.now(tz=pytz.UTC) copy_of_idea.reindex() context.format(request) context.reindex() if 'archived' in context.state: recuperate_actions = getBusinessAction(context, request, 'ideamanagement', 'recuperate') if recuperate_actions: recuperate_actions[0].execute(context, request, appstruct, **kw) request.registry.notify(ActivityExecuted(self, [context], user)) return {}
def start(self, context, request, appstruct, **kw): user = get_current() context.state = PersistentList(['published']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) published = [context] root = getSite() if getattr(context, '_tree', None): tree = getattr(context, '_tree') request.get_site_folder.merge_tree(tree) root.merge_tree(tree) not_published_artists = [ a for a in context.artists if 'published' not in a.state ] published.extend(not_published_artists) for artist in not_published_artists: publish_artist(artist, request, user) not_published_directors = [ a for a in getattr(context, 'directors', []) if 'published' not in a.state ] published.extend(not_published_directors) for director in not_published_directors: publish_artist(director, request, user) context.release_date = datetime.datetime.now(tz=pytz.UTC) context.reindex() author = getattr(context, 'author', None) if author and user is not author: site = get_site_folder(True, request) alert('internal', [site], [author], { 'kind': InternalAlertKind.moderation_alert, 'subjects': [context] }) request.registry.notify(ActivityExecuted(self, published, user)) return {}
def validate_action(action, context, request, **kw): if not context.__provides__(action.context): return False, _('Context is not valid') process = kw.get('process', action.process) if not getattr(action.relation_validation, '__func__', MARKER_FUNC)( process, context): return False, _('Context is not valid') if action.isexecuted: return False, _('Action is executed') if not action.workitem.validate(): return False, _('Workitem is not valid') if getattr(action, 'isSequential', False) and action.is_locked(request): return False, _('Action is locked') elif not getattr(action.roles_validation, '__func__', MARKER_FUNC)( process, context): return False, _('Role is not valid') if not getattr(action.processsecurity_validation, '__func__', MARKER_FUNC)( process, context): return False, _('Security is violated') if not getattr(action.state_validation, '__func__', MARKER_FUNC)(process, context): return False, _('Context state is not valid') _assigned_to = list(action.assigned_to) if _assigned_to: _assigned_to.append(getSite()['principals']['users']['admin']) current_user = get_current(request) if current_user not in _assigned_to: return False, _('Action is assigned to an other user') return True, _('Valid action')
def start(self, context, request, appstruct, **kw): site = get_site_folder(True, request) user = get_current(request) is_manager = has_any_roles( user=user, roles=('Admin', ('SiteAdmin', site))) or\ is_site_moderator(request) if is_manager or all( has_role(user=user, role=('Owner', v)) for v in appstruct['targets'] if 'published' not in v.state): root = getSite() source = appstruct['source'] targets = appstruct['targets'] for venue in targets: replaced = venue.replace_by(source) if replaced: request.registry.notify( ObjectReplaced(old_object=venue, new_object=source)) root.delfromproperty('venues', venue) else: return {'error': True} return {}
def start(self, context, request, appstruct, **kw): new_roles = list(appstruct['roles']) site = get_site_folder(True) if 'global_site' in kw: site = getSite() current_roles = [ r for r in get_roles(context, root=site, ignore_groups=True) if not getattr(DACE_ROLES.get(r, None), 'islocal', False) ] roles_to_revoke = [(r, site) for r in current_roles if r not in new_roles] roles_to_grant = [(r, site) for r in new_roles if r not in current_roles] revoke_roles(context, roles_to_revoke) grant_roles(context, roles_to_grant) if 'Member' in roles_to_grant: grant_roles(context, ('Member', )) context.reindex() request.registry.notify( ActivityExecuted(self, [context], get_current())) return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) result = {} user = get_current() values = { 'object': self.context, 'state': get_states_mapping( user, self.context, getattr(self.context, 'state_or_none', [None])[0]), 'navbar_body': navbars['navbar_body'] } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def get_objects_with_role(user=None, role=None, root=None): if role is None: return [] if user is None: user = get_current() if isinstance(user, Anonymous): return False #TODO use cookies to find objects if root is None: root = getSite() opts = {u'source_id': get_oid(user)} opts[u'relation_id'] = role opts[u'reftype'] = 'Role' objects = [r.target for r in find_relations(root, opts).all()] objects = list(set(objects)) if root in objects: objects.remove(root) return objects
def start(self, context, request, appstruct, **kw): email = appstruct.pop('email') key = email subscribed = context.subscribed.get(key, None) if subscribed: context.subscribed.pop(key) first_name = subscribed.get('first_name') last_name = subscribed.get('last_name') email = subscribed.get('email') root = getSite() mail_template = root.get_mail_template('newsletter_unsubscription') email_data = get_entity_data(context, 'newsletter', request) subject = mail_template['subject'].format( newsletter_title=context.title, novaideo_title=root.title) mail = mail_template['template'].format(first_name=first_name, last_name=last_name, novaideo_title=root.title, **email_data) alert('email', [root.get_site_sender()], [email], subject=subject, body=mail) return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self.request, self.context, process_id='reportsmanagement', descriminators=['plus-action'], flatten=True) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) result = {} values = { 'navbar_body': navbars['navbar_body'], 'object': self.context } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): root = getSite() valid_sites = get_valid_sites(root) #recuperate the source url: json file (see servicies: digitick...) source = self.params('source') if source: entities_file = urllib.request.urlopen(source) entities_str = entities_file.read().decode('utf8') #load the json file (all entities) all_imported_entities = json.loads(entities_str) #recuperate new entities entities_to_import, current_objects = get_new_entities( all_imported_entities) len_entities = str(len(entities_to_import)) for index, entity in enumerate(entities_to_import): #recuperate the type of the entitie entity_type = entity.pop('type') #recuperate the factory factory = FACTORIES.get(entity_type, None) if factory: #add the entitie try: factory(entity, 'submitted', root, sites=valid_sites) log.info(str(index) + "/" + len_entities) except Exception as error: log.warning(error) if index % NB_AFTER_COMMIT == 0: log.info("**** Commit ****") transaction.commit() result = {} values = {'context': self.context} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def venue_choice(node, kw): context = node.bindings['context'] request = node.bindings['request'] default_venues = node.bindings.get('venues', []) default_venues = [(v.get_id(), v.title) for v in default_venues] root = getSite() venues = [] if hasattr(context, 'schedules') and context is not root: venues = [(s.venue.get_id(), s.venue.title) for s in context.schedules if s.venue] venues.extend(default_venues) venues.insert(0, ('', _('- Select -'))) ajax_url = request.resource_url(context, '@@culturaleventmanagement', query={'op': 'find_venues'}) def title_getter(id): try: obj = get_obj(int(id), None) if obj: return obj.title else: return id except Exception as e: log.warning(e) return id return AjaxSelect2Widget( values=venues, ajax_url=ajax_url, dependencies=['venue_history'], title_getter=title_getter, ajax_item_template="venue_item_template", css_class="venue-title select2-preload", create_message=_("Create a new venue"), create=True)
def start(self, context, request, appstruct, **kw): root = getSite() xlfile = appstruct['file']['_object_data'] organizations = get_data_from_xl(file=xlfile, properties={ 'title': ('String', False), 'description': ('String', False), 'address': ('String', False), 'phone': ('String', False), 'email': ('String', False), 'website': ('String', False), 'fax': ('String', False), }) for organization_data in organizations: title = organization_data.get('title', None) if title: current_organizations = list( get_entities_by_title([IOrganization], title).all()) if not current_organizations: description = organization_data.get('description', title) or title contact = { 'title': request.localizer.translate(_('Contact')), 'address': organization_data.get('address', ''), 'phone': organization_data.get('phone', ''), 'email': organization_data.get('email', ''), 'website': organization_data.get('website', ''), 'fax': organization_data.get('fax', ''), } organization = Organization(title=title, description=description, contacts=[contact]) root.addtoproperty('organizations', organization) request.registry.notify( ActivityExecuted(self, organizations, get_current())) return {}
def start(self, context, request, appstruct, **kw): root = getSite() moderators = self.process.execution_context.get_involved_collection( 'electors') alert('internal', [root], moderators, internal_kind=InternalAlertKind.moderation_alert, subjects=[context], alert_kind='moderate_report') subject_data = get_entity_data(context, 'subject', request) subject_data.update(get_user_data(context, 'subject', request)) duration = getattr(root, 'duration_moderation_vote', 7) date_end = datetime.datetime.now() + \ datetime.timedelta(days=duration) date_end_vote = to_localized_time(date_end, request, translate=True) subject_data['url_moderation_rules'] = request.resource_url( root.moderation_rules, '@@index') for moderator in [a for a in moderators if getattr(a, 'email', '')]: mail_template = root.get_mail_template('moderate_report', moderator.user_locale) subject = mail_template['subject'].format( novaideo_title=root.title) email_data = get_user_data(moderator, 'recipient', request) email_data.update(subject_data) message = mail_template['template'].format( novaideo_title=root.title, subject_email=getattr(context, 'email', ''), date_end_vote=date_end_vote, duration=duration, **email_data) alert('email', [root.get_site_sender()], [moderator.email], subject=subject, body=message) request.registry.notify( ActivityExecuted(self, [context], get_current())) return {}
def __call__(self, has_contextual_help=False): root = getSite() navbar_actions = [SeeMyContents, SeeMyParticipations, SeeMySelections] if 'proposal' not in self.request.content_to_manage: navbar_actions = [SeeMyContents, SeeMySelections] if self.request.support_ideas or self.request.support_proposals: navbar_actions.append(SeeMySupports) actions_url = OrderedDict() for actionclass in navbar_actions: process_id, action_id = tuple( actionclass.node_definition.id.split('.')) action, view = get_action_view(process_id, action_id, self.request) if None not in (action, view): actions_url[action.title] = { 'action': action, 'action_id': action_id, 'icon': action.style_picto, 'url': action.url(root), 'view_name': getattr(view, 'name', None) } else: actions_url[actionclass.node_definition.title] = { 'action': None, 'action_id': action_id, 'icon': actionclass.style_picto, 'url': None, 'view_name': getattr(view, 'name', None) } result = {} result['actions'] = actions_url result['view'] = self result['has_contextual_help'] = has_contextual_help result['is_root'] = root is self.context and \ self.request.view_name in ('', 'index', '@@index') return result
def __call__(self): user = get_current() guide_tour_data = getattr(user, 'guide_tour_data', {}) guide_state = guide_tour_data.get('guide_state', 'first_start') if guide_state in ('pending', 'first_start'): page_resources = get_guide_tour_page(self.request, self.context, user, self.request.view_name) if page_resources: page_resources = merge_dicts(self.resources, page_resources) page_resources['request'] = self.request # if user is not an anonymous if self.request.user: root = getSite() page_resources['update_url'] = self.request.resource_url( root, 'novaideoapi', query={'op': 'update_guide_tour_data'}) guide = page_resources.get('guide', None) page = page_resources.get('page', None) if guide is not None and page is not None: guide_data = guide_tour_data.get( guide + '_' + page, {}) page_state = guide_data.get('page_state', 'pending') if page_state == 'pending': page_resources['guide'] = guide page_resources['page'] = page page_resources['guide_value'] = guide_data.get( 'guide', -1) page_resources['page_value'] = guide_data.get( 'page', 0) page_resources['guide_state'] = guide_state else: return {} return page_resources return {}
def update(self): self.execute(None) vote_actions = get_vote_actions_body(self.context, self.request, ballot_ids=['vote_moderation']) try: navbars = generate_navbars(self.request, self.context, process_id='reportsmanagement', descriminators=['plus-action'], flatten=True, text_action=vote_actions['activators']) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) resources = merge_dicts(navbars['resources'], vote_actions['resources'], ('js_links', 'css_links')) resources['js_links'] = list(set(resources['js_links'])) resources['css_links'] = list(set(resources['css_links'])) messages = vote_actions['messages'] if not messages: messages = navbars['messages'] result = {} values = { 'navbar_body': navbars['navbar_body'], 'object': self.context, 'vote_actions_body': vote_actions['body'] } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = messages item['isactive'] = vote_actions['isactive'] or navbars['isactive'] result.update(resources) result['coordinates'] = {self.coordinates: [item]} return result
def __call__(self): root = getSite() options = {} options['locations'] = {} options['show_all'] = True resources = deepcopy( getattr(self.request, 'resources', { 'js_links': [], 'css_links': [] })) search_view_instance = GeoSearchForm(self.context, self.request) search_view_result = search_view_instance() search_body = '' result = {'css_links': [], 'js_links': []} if isinstance(search_view_result, dict) and \ 'coordinates' in search_view_result: search_body = search_view_result['coordinates'][ search_view_instance.coordinates][0]['body'] result['css_links'] = [ c for c in search_view_result['css_links'] if c not in resources['css_links'] ] result['js_links'] = [ c for c in search_view_result['js_links'] if c not in resources['js_links'] ] result['search_body'] = search_body result['options'] = json.dumps(options) result['url'] = self.request.resource_url( root, '@@creationculturelapi', query={'op': 'find_geo_cultural_event'}) update_resources(self.request, result) return result