def group_tmpl(portal, objs, **kwargs): keyer = lambda item: path_in_site(item['ob']) sorted_items = sorted(objs, key=keyer) items_str = ''.join('[%s]' % path_in_site(item['ob']) for item in sorted_items) body = '%s %s %s' % (template_name, items_str, portal.title_or_id()) return {'subject': 'notifications', 'body_text': body}
def test_walk_subscriptions(self): subs1 = list((path_in_site(obj), sub) for obj, n, sub in walk_subscriptions(self.portal)) self.assertEqual(len(subs1), 2) self.assertTrue(('f1/b/2', self.user2_sub) in subs1) self.assertTrue(('f1/b', self.user1_sub) in subs1) subs2 = list( (path_in_site(obj), sub) for obj, n, sub in walk_subscriptions(self.portal['f1']['b']['2'])) self.assertEqual(len(subs2), 1) self.assertTrue(('f1/b/2', self.user2_sub) in subs1) subs3 = list(walk_subscriptions(self.portal['f1']['a'])) self.assertEqual(len(subs3), 0)
def test_walk_subscriptions(self): subs1 = list((path_in_site(obj), sub) for obj, n, sub in walk_subscriptions(self.portal)) self.assertEqual(len(subs1), 2) self.assertTrue(('f1/b/2', self.user2_sub) in subs1) self.assertTrue(('f1/b', self.user1_sub) in subs1) subs2 = list((path_in_site(obj), sub) for obj, n, sub in walk_subscriptions(self.portal['f1']['b']['2'])) self.assertEqual(len(subs2), 1) self.assertTrue(('f1/b/2', self.user2_sub) in subs1) subs3 = list(walk_subscriptions(self.portal['f1']['a'])) self.assertEqual(len(subs3), 0)
def send_notifications_for_event(event, subscriber_data_default, template): """Send notifications to site maintainers and subscribers. Create event handler must be supressed when this action is run. """ folder = event.context portal = folder.getSite() notification_tool = portal.getNotificationTool() action_logger = portal.getActionLogger() subscribers_data = {} maintainers_data = {} #Get maintainers maintainers = portal.getMaintainersEmails(folder) for email in maintainers: data = dict(subscriber_data_default) data.update({ 'ob': folder, 'here': notification_tool, }) maintainers_data[email] = data #Get subscribers if notification_tool.config['enable_instant'] is True: subscribers_data = utils.get_subscribers_data(notification_tool, folder, **subscriber_data_default) subscribers_data.update(maintainers_data) notification_tool._send_notifications(subscribers_data, template.render_email) #Create log entry action_logger.create(type=constants.LOG_TYPES['bulk_import'], path=path_in_site(folder))
def handle_object_add(event): """An object has been created. Create a log entry. Notifications to subscribers are only sent in object-approved handler. Administrative notifications are only sent if the object is not approved. If it is already approved, then notifications were already sent in the object-approved handler. """ if not event.schema.get('_send_notifications', True): return ob = event.context portal = ob.getSite() contributor = event.contributor if not ob.approved: notification_tool = portal.getNotificationTool() notification_tool.notify_administrative(ob, contributor) notification_tool.notify_maintainer(ob, ob.aq_parent, contributor=contributor) if ob.approved: #Create log entry action_logger = portal.getActionLogger() action_logger.create(type=constants.LOG_TYPES['created'], contributor=contributor, path=path_in_site(ob))
def saved_emails(self, REQUEST=None, RESPONSE=None): """ Display all saved bulk emails """ emails = get_bulk_emails(self.getSite(), where_to_read=path_in_site(self.getMeeting())) import_non_local('email', 'std_email') from std_email import email as standard_email for email in emails: subject, encoding = standard_email.Header.decode_header( email['subject'])[0] if encoding: email['subject'] = subject.decode(encoding) else: email['subject'] = subject recipients = [] if email['recipients'] is None: email['recipients'] = [] for recp in email['recipients']: recipients.extend(re.split(',|;', recp.replace(' ', ''))) email['recipients'] = recipients cc_recipients = [] if email['cc_recipients'] is None: email['cc_recipients'] = [] for recp in email['cc_recipients']: cc_recipients.extend(re.split(',|;', recp.replace(' ', ''))) email['cc_recipients'] = cc_recipients return self.getFormsTool().getContent( {'here': self, 'emails': emails, 'meeting': self.getMeeting()}, 'naaya.content.meeting.email_archive')
def url_entry(self, parent_path, ob_id, filename, url, title, description, keywords, date, userid): parent = get_parent(self.context, parent_path) orig_path = join_parent_path(parent_path, ob_id) assert orig_path not in self.rename kwargs = { 'id': ob_id, 'contributor': userid or self.default_userid, 'releasedate': nydateformat(date), 'title': title, 'description': description, 'keywords': keywords, 'locator': url, '_send_notifications': False, } url_id = addNyURL(parent, **kwargs) if parent_path: self.rename[orig_path] = parent_path + '/' + url_id else: self.rename[orig_path] = url_id new_url = parent[url_id] logger.info("Added url: %r", path_in_site(new_url)) self.count['urls'] += 1
def xrjs_getGeoPoints(self, REQUEST): """ """ try: points = [] for res in self.search_geo_objects(REQUEST=REQUEST): if res.geo_location is None: continue points.append( { "lat": res.geo_location.lat, "lon": res.geo_location.lon, "id": path_in_site(res), "label": res.title_or_id(), "icon_name": "mk_%s" % res.geo_type, "tooltip": self.get_marker(res), } ) json_response = json.dumps({"points": points}, default=json_encode_helper) except: self.log_current_error() json_response = json.dumps({"error": err_info(), "points": {}}) REQUEST.RESPONSE.setHeader("Content-type", "application/json") return json_response
def saved_emails_export(self, REQUEST=None, RESPONSE=None): """ Aggregate an xcel file from emails on disk (just like saved_emails does to populate the web page)""" if not REQUEST: RESPONSE.badRequestError("MALFORMED_URL") headers = REQUEST.form.get('headers') keys = REQUEST.form.get('keys') ids = REQUEST.form.get('id') if not headers or not keys: RESPONSE.badRequestError("MALFORMED_URL") headers = headers.split(',') keys = keys.split(',') if len(headers) != len(keys): RESPONSE.badRequestError("MALFORMED_URL") RESPONSE.setHeader('Content-Type', 'application/vnd.ms-excel') RESPONSE.setHeader('Content-Disposition', ('attachment; filename=' 'consultation_invitation_emails.xls')) cols = zip(headers, keys) return export_email_list_xcel(self.getSite(), cols, ids, where_to_read=path_in_site( self.get_consultation()))
def _update(self, portal): notif_tool = portal.getNotificationTool() auth_tool = portal.getAuthenticationTool() admins = auth_tool.search_users('', role='Administrator', rkey=0, skey='name', all_users=True, location='_all_') self.log.debug('Started update in %s' % portal.getId()) for admin in admins: for role in admin.roles: if 'Administrator' in role[0]: user_id = admin.user_id own_site_location = path_in_site(role[1]) this_site_location = relative_object_path(role[1], portal) if own_site_location != this_site_location: self.log.debug('Location %s is probably in a subportal' % own_site_location) continue obj = portal.restrictedTraverse(this_site_location) if match_account_subscription( ISubscriptionContainer(obj), user_id, 'administrative', 'en'): self.log.debug('Subscription for user %s already present ' 'in location %s' %(user_id, this_site_location or '/')) else: notif_tool.add_account_subscription(user_id, this_site_location, 'administrative', 'en', []) self.log.debug('Subscription added for user %s in location %s' %(user_id, this_site_location or '/')) return True
def send_email(self, REQUEST): """ Send e-mail """ keys = ('to', 'cc', 'subject', 'message') formerrors = {} if REQUEST.REQUEST_METHOD == 'POST': formdata = dict((key, REQUEST.form.get(key, '')) for key in keys) email_tool = self.getEmailTool() acl_tool = self.getAuthenticationTool() emails_to = [] emails_cc = [] to = formdata['to'] cc = formdata['cc'] message = formdata['message'] if not to: formerrors['to'] = 'At least one recipinet is needed' if not formdata['subject']: formerrors['subject'] = 'Email subject is mandatory' if not message: formerrors['message'] = 'Message body is mandatory' if not formerrors: for item in to: if '@' in item: emails_to.append(item.strip()) else: user_info = acl_tool.get_user_info(item.strip()) emails_to.append(user_info.email) for item in cc: if '@' in item: emails_cc.append(item.strip()) else: user_info = acl_tool.get_user_info(item.strip()) emails_cc.append(user_info.email) email_tool.sendEmail(formdata['message'], emails_to, email_tool.get_addr_from(), formdata['subject'], p_cc=emails_cc) save_bulk_email(self.getSite(), emails_to, email_tool.get_addr_from(), formdata['subject'], formdata['message'], where_to_save=path_in_site( self.get_consultation()), addr_cc=emails_cc) self.setSessionInfoTrans( 'Email sent to %s and in CC to %s.' % (','.join(emails_to), ','.join(emails_cc))) return REQUEST.RESPONSE.redirect(self.absolute_url() + '/send_email') else: self.setSessionErrorsTrans('The form contains errors. Please ' 'correct them and try again.') else: formdata = dict((key, '') for key in keys) return self._create_email_html(formdata=formdata, formerrors=formerrors)
def handle_del_content(obj, event): """ Test whether this required adding pointers and perform the cleanup of pointers. """ site = obj.getSite() if not getattr(site, 'destinet.publisher', False): return None q_both = _qualifies_for_both(obj) q_topics = _qualifies_for_topics_only(obj) if q_topics or q_both: # clean-up all existing pointers cat = site.getCatalogTool() pointers = cat.search({ 'meta_type': 'Naaya Pointer', 'path': [ ofs_path(site.countries), ofs_path(site.topics), ofs_path(getattr(site, 'resources')), # kept for pointers prior to v 1.1 ofs_path(getattr(site, 'who-who')) ], 'pointer': path_in_site(obj) }) for brain in pointers: pointer = brain.getObject() pointer.aq_parent._delObject(pointer.id)
def get_linked_pointer_brains(obj): """ Tests if object had met condition to be synced with pointers and returns brains to existing ones. Used by handlers to keep them in sync. """ site = obj.getSite() q_both = _qualifies_for_both(obj) q_topics = _qualifies_for_topics_only(obj) pointers = [] if q_topics or q_both: cat = site.getCatalogTool() pointers = cat.search({ 'meta_type': 'Naaya Pointer', 'path': [ ofs_path(site.countries), ofs_path(site.topics), ofs_path(getattr(site, 'resources')), # kept for pointers prior to v 1.1 ofs_path(getattr(site, 'who-who')) ], 'pointer': path_in_site(obj) }) return pointers
def handle_edit_content(event): """ Test whether this requires adding pointers and perform the action """ obj = event.context site = obj.getSite() if not getattr(site, 'destinet.publisher', False): return None q_both = _qualifies_for_both(obj) q_topics = _qualifies_for_topics_only(obj) if q_topics or q_both: # clean-up all existing pointers, then re-add them cat = site.getCatalogTool() pointers = cat.search({'meta_type': 'Naaya Pointer', 'path': [ofs_path(site.countries), ofs_path(site.topics), ofs_path(getattr(site, 'resources')), # kept for pointers prior to v 1.1 ofs_path(getattr(site, 'who-who'))], 'pointer': path_in_site(obj)}) for brain in pointers: pointer = brain.getObject() pointer.aq_parent._delObject(pointer.id) if q_both: place_pointers(obj) else: place_pointers(obj, exclude=['target-groups'])
def xrjs_getGeoPoints(self, REQUEST): """ """ try: points = [] for res in self.search_geo_objects(REQUEST=REQUEST): if res.geo_location is None: continue points.append({ 'lat': res.geo_location.lat, 'lon': res.geo_location.lon, 'id': path_in_site(res), 'label': res.title_or_id(), 'icon_name': 'mk_%s' % res.geo_type, 'tooltip': self.get_marker(res), }) json_response = json.dumps({'points': points}, default=json_encode_helper) except: self.log_current_error() json_response = json.dumps({'error': err_info(), 'points': {}}) REQUEST.RESPONSE.setHeader('Content-type', 'application/json') return json_response
def test_contact_with_group(self): """ test destinet registration when group is selected """ self.portal.REQUEST.form.update(self.initial_data) self.portal.REQUEST.form.update(groups=['test-group']) process_create_account(self.context, self.portal.REQUEST) contact = self.portal['who-who']['destinet-users'].objectValues()[0] pointer = self.portal.resources._getOb(contact.getId()) self.assertEqual(pointer.pointer, path_in_site(contact))
def change_user_roles(event): """Update subscriptions when a user's roles were updated: If he now gets the Administrator role, he should be subscribed to administrative notifications. If he loses the role, his subscription should be revoked""" notif_tool = event.context.getNotificationTool() portal = event.context.getSite() if "Administrator" in event.assigned: if not utils.match_account_subscription( ISubscriptionContainer(event.context), event.user_id, "administrative", "en" ): notif_tool.add_account_subscription(event.user_id, path_in_site(event.context), "administrative", "en", []) if "Administrator" in event.unassigned: if utils.match_account_subscription( ISubscriptionContainer(event.context), event.user_id, "administrative", "en" ): notif_tool.remove_account_subscription(event.user_id, path_in_site(event.context), "administrative", "en")
def __call__(self, context, position): notif_tool = self.site.getNotificationTool() if not list(notif_tool.available_notif_types()): return '' macro = self.site.getPortletsTool()._get_macro(position) tmpl = self.template.__of__(context) return tmpl(macro=macro, notif_tool=notif_tool, location=path_in_site(context))
def saved_emails(self, REQUEST=None, RESPONSE=None): """ Display all saved invitation emails """ emails = get_bulk_emails(self.getSite(), where_to_read=path_in_site( self.get_consultation())) return self.getFormsTool().getContent( {'here': self, 'emails': emails, 'consultation': self.get_consultation()}, 'tbconsultation-email_archive')
def view_email(self, filename, REQUEST=None, RESPONSE=None): """ Display a specfic saved email """ email = get_bulk_email(self.getSite(), filename, where_to_read=path_in_site(self.getMeeting())) return self.getFormsTool().getContent( {'here': self, 'email': email, 'meeting': self.getMeeting()}, 'naaya.content.meeting.email_view_email')
def change_user_roles(event): """Update subscriptions when a user's roles were updated: If he now gets the Administrator role, he should be subscribed to administrative notifications. If he loses the role, his subscription should be revoked""" notif_tool = event.context.getNotificationTool() portal = event.context.getSite() if 'Administrator' in event.assigned: if not utils.match_account_subscription(ISubscriptionContainer(event.context), event.user_id, 'administrative', 'en'): notif_tool.add_account_subscription(event.user_id, path_in_site(event.context), 'administrative', 'en', []) if 'Administrator' in event.unassigned: if utils.match_account_subscription(ISubscriptionContainer(event.context), event.user_id, 'administrative', 'en'): notif_tool.remove_account_subscription(event.user_id, path_in_site(event.context), 'administrative', 'en')
def send_email(self, REQUEST): """ Send e-mail """ keys = ('to', 'cc', 'subject', 'message') formerrors = {} if REQUEST.REQUEST_METHOD == 'POST': formdata = dict((key, REQUEST.form.get(key, '')) for key in keys) email_tool = self.getEmailTool() acl_tool = self.getAuthenticationTool() emails_to = [] emails_cc = [] to = formdata['to'] cc = formdata['cc'] message = formdata['message'] if not to: formerrors['to'] = 'At least one recipinet is needed' if not formdata['subject']: formerrors['subject'] = 'Email subject is mandatory' if not message: formerrors['message'] = 'Message body is mandatory' if not formerrors: for item in to: if '@' in item: emails_to.append(item.strip()) else: user_info = acl_tool.get_user_info(item.strip()) emails_to.append(user_info.email) for item in cc: if '@' in item: emails_cc.append(item.strip()) else: user_info = acl_tool.get_user_info(item.strip()) emails_cc.append(user_info.email) email_tool.sendEmail(formdata['message'], emails_to, email_tool.get_addr_from(), formdata['subject'], p_cc=emails_cc) save_bulk_email(self.getSite(), emails_to, email_tool.get_addr_from(), formdata['subject'], formdata['message'], where_to_save=path_in_site( self.get_consultation()), addr_cc=emails_cc) self.setSessionInfoTrans('Email sent to %s and in CC to %s.' % (','.join(emails_to), ','.join(emails_cc))) return REQUEST.RESPONSE.redirect(self.absolute_url() + '/send_email') else: self.setSessionErrorsTrans('The form contains errors. Please ' 'correct them and try again.') else: formdata = dict((key, '') for key in keys) return self._create_email_html(formdata=formdata, formerrors=formerrors)
def view_email(self, filename, REQUEST=None, RESPONSE=None): """ Display a specfic saved email """ email = get_bulk_email(self.getSite(), filename, where_to_read=path_in_site( self.get_consultation())) return self.getFormsTool().getContent( {'here': self, 'email': email, 'consultation': self.get_consultation()}, 'tb_consultation-view_email')
def send_email(self, from_email, subject, body_text, cc_emails, REQUEST, to_uids=None): """ """ errors = [] if not to_uids: to_uids = [] if not (to_uids or cc_emails): errors.append('Please select at least on recipient') if not (subject or body_text): errors.append('Subject and message body cannot both be empty') for email in cc_emails: if not is_valid_email(email): errors.append('Invalid email "%s" in CC field' % email) if errors: self.setSessionErrorsTrans(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) participants = self.getParticipants() subscriptions = participants.getSubscriptions() signup_emails = [participants.getAttendeeInfo(uid)['email'] for uid in to_uids if subscriptions._is_signup(uid)] account_emails = [participants.getAttendeeInfo(uid)['email'] for uid in to_uids if not subscriptions._is_signup(uid)] to_emails = signup_emails + account_emails if (self.eionet_meeting() and '*****@*****.**' not in cc_emails): cc_emails.append('*****@*****.**') # TODO validate cc_emails # We need to send the emails to signups one by one since each email # might be different (if they contain links to documents for # which the authentication keys is inserted into the link) for uid in to_uids: if subscriptions._is_signup(uid): signup_email = participants.getAttendeeInfo(uid)['email'] signup_body_text = self.insert_auth_link(body_text, uid) result = self._send_email( from_email, [signup_email], cc_emails, subject, signup_body_text, only_to=True) if account_emails: result = self._send_email(from_email, account_emails, cc_emails, subject, body_text) save_bulk_email(self.getSite(), to_emails, from_email, subject, body_text, where_to_save=path_in_site(self.getMeeting()), addr_cc=cc_emails) return self.getFormsTool().getContent( {'here': self, 'meeting': self.getMeeting(), 'result': result}, 'naaya.content.meeting.email_sendstatus')
def mail_in_queue(self, filename): """ Check if a specific message is still in queue """ COMMON_KEYS = ['sender', 'recipients', 'subject', 'content', 'date'] check_values = {} archived_email = get_bulk_email(self.getSite(), filename, where_to_read=path_in_site( self.get_consultation())) for key in COMMON_KEYS: check_values[key] = archived_email[key] return _mail_in_queue(self.getSite(), filename, check_values)
def saved_emails(self, REQUEST=None, RESPONSE=None): """ Display all saved invitation emails """ emails = get_bulk_emails(self.getSite(), where_to_read=path_in_site( self.get_consultation())) return self.getFormsTool().getContent( { 'here': self, 'emails': emails, 'consultation': self.get_consultation() }, 'tbconsultation-email_archive')
def _send_invitation(self, name, email, organization, notes, message, inviter_userid, inviter_name, web_form=False, preview=False): errors = [] if not name: errors.append(('name', ValueError('Name is mandatory'))) if not email: errors.append(('email', ValueError('Email is mandatory'))) if errors: if web_form: raise FormError(errors) else: raise errors[0][1] mail_opts = { 'name': name, 'consultation': self.get_consultation(), 'inviter_name': inviter_name, 'inviter_message': message, } if preview: mail_opts['keyed_url'] = '[PRIVATE URL]' mail_data = self._invite_email.render_email(**mail_opts) return {'preview_mail': mail_data} invite_args = { 'inviter_userid': inviter_userid, 'name': name, 'email': email, 'organization': organization, 'notes': notes, } key = self._create_invitation(**invite_args) mail_opts['keyed_url'] = self.absolute_url() + '/welcome?key=' + key mail_data = self._invite_email.render_email(**mail_opts) email_tool = self.getEmailTool() email_tool.sendEmail(mail_data['body_text'], email, email_tool.get_addr_from(), mail_data['subject']) save_bulk_email(self.getSite(), [email], email_tool.get_addr_from(), mail_data['subject'], mail_data['body_text'], where_to_save=path_in_site(self.get_consultation()))
def handle_forum_object_add(event): obj = event.context portal = obj.getSite() contributor = event.contributor notification_tool = portal.getNotificationTool() notification_tool.notify_instant(obj, contributor) if obj.approved: #Create log entry action_logger = portal.getActionLogger() action_logger.create(type=LOG_TYPES['created'], contributor=contributor, path=path_in_site(obj))
def view_email(self, filename, REQUEST=None, RESPONSE=None): """ Display a specfic saved email """ email = get_bulk_email(self.getSite(), filename, where_to_read=path_in_site( self.get_consultation())) return self.getFormsTool().getContent( { 'here': self, 'email': email, 'consultation': self.get_consultation() }, 'tb_consultation-view_email')
def test_cut_paste(self): loginUnrestricted() addNyURL(self.portal.resources, id='url', title='url', coverage='Georgia, Not Existing', topics=['atopic'], url='http://eaudeweb.ro', contributor='simiamih') transaction.commit() cp = self.portal.resources.manage_cutObjects('url') self.portal.countries.manage_pasteObjects(cp) ob = self.portal.countries.url new_path = path_in_site(ob) self.assertEqual(self.portal.topics.atopic.url.pointer, new_path) self.assertTrue(self.portal.countries.georgia.url.pointer, new_path)
def mail_in_queue(self, filename): """ Check if a specific message is still in queue """ # removed recipients from COMMON_KEYS because of signup # recipients splitting COMMON_KEYS = ['sender', 'subject', 'content', 'date'] check_values = {} archived_email = get_bulk_email( self.getSite(), filename, where_to_read=path_in_site(self.getMeeting())) for key in COMMON_KEYS: check_values[key] = archived_email[key] return _mail_in_queue(self.getSite(), filename, check_values)
def manageMainTopics(self, maintopics=None, REQUEST=None): """ Update main topics. """ site = self.getSite() if maintopics is None: maintopics = [] else: maintopics = self.utConvertToList(maintopics) site.maintopics = [] for maintopic in maintopics: folder_ob = self.utGetObject(maintopic) site.maintopics.append(path_in_site(folder_ob)) site._p_changed = True if REQUEST: REQUEST.RESPONSE.redirect('manage_maintopics_html?save=ok')
def test_pointers_update_on_cut_paste_data(self): """ Moving an object that has a pointer to it, updates the pointer """ cat = self.portal.getCatalogTool() cat.addIndex('pointer', 'FieldIndex') addNyURL(self.portal.info, id='some_url_ob', title='Some Url', url='http://eaudeweb.ro', contributor='simiamih') addNyPointer(self.portal.info, id='point', title='point', lang='en', pointer='info/some_url_ob') addNyFolder(self.portal.info, id='sub_info') transaction.commit() cp = self.portal.info.manage_cutObjects('some_url_ob') self.portal.info.sub_info.manage_pasteObjects(cp) new_path = path_in_site(self.portal.info.sub_info.some_url_ob) self.assertEqual(self.portal.info.point.pointer, new_path)
def admin_get_subscriptions(self, user_query=''): user_query = user_query.strip() for obj, sub_id, subscription in utils.walk_subscriptions( self.getSite()): user = subscription.to_string(obj) if not user_query or re.match('.*%s.*' % user_query, user, re.IGNORECASE): yield { 'user': user, 'location': path_in_site(obj), 'sub_id': sub_id, 'lang': subscription.lang, 'notif_type': subscription.notif_type, }
def traverse(objects, level=0, stop_level=2, exclude_root=False): """ Create a dict with node properties and children. This is a fixed level recursion. On some sites there are a lot of objects so we don't need to get the whole tree. """ res = [] for ob in objects: if ISubscriptionTarget.providedBy(ob) is False: continue children_objects = [] if level != stop_level: # Stop if the level is reached # Create a list of object's children if hasattr(ob, 'objectValues'): # Get only naaya container objects for child in ob.objectValues( self.get_naaya_containers_metatypes()): # Skip unsubmited/unapproved if not getattr(child, 'approved', False): continue elif not getattr(child, 'submitted', False): continue else: children_objects.append(child) if hasattr(ob, 'approved'): icon = ob.approved and ob.icon or ob.icon_marked else: icon = ob.icon children = traverse(children_objects, level + 1, stop_level) if exclude_root: # Return only the children if this is set return children res.append({ 'data': { 'title': self.utStrEscapeHTMLTags( self.utToUtf8(ob.title_or_id())), 'icon': icon }, 'attributes': { 'title': path_in_site(ob) }, 'children': children }) return res
def traverse(objects, level=0, stop_level=2, exclude_root=False): """ Create a dict with node properties and children. This is a fixed level recursion. On some sites there are a lot of objects so we don't need to get the whole tree. """ res = [] for ob in objects: if ISubscriptionTarget.providedBy(ob) is False: continue children_objects = [] if level != stop_level: # Stop if the level is reached # Create a list of object's children if hasattr(ob, 'objectValues'): # Get only naaya container objects for child in ob.objectValues( self.get_naaya_containers_metatypes()): # Skip unsubmited/unapproved if not getattr(child, 'approved', False): continue elif not getattr(child, 'submitted', False): continue else: children_objects.append(child) if hasattr(ob, 'approved'): icon = ob.approved and ob.icon or ob.icon_marked else: icon = ob.icon children = traverse(children_objects, level+1, stop_level) if exclude_root: # Return only the children if this is set return children res.append({ 'data': { 'title': self.utStrEscapeHTMLTags( self.utToUtf8(ob.title_or_id())), 'icon': icon }, 'attributes': { 'title': path_in_site(ob) }, 'children': children }) return res
def __call__(self, context, position): notif_tool = self.site.getNotificationTool() #The portlet should only be rendered if at least one notification type #is activated, of if the user has administrative rights, so he should #be able to subscribe to administrative notifications if not list(notif_tool.available_notif_types()) and not \ self.site.checkPermissionPublishObjects(): return '' macro = self.site.getPortletsTool()._get_macro(position) tmpl = self.template.__of__(context) location = path_in_site(context) if context == notif_tool: location = '' return tmpl(macro=macro, notif_tool=notif_tool, location=location)
def list_my_subscriptions(self, REQUEST): """ Returns a list of mappings (location, notif_type, lang) for all subscriptions of logged-in user """ user = REQUEST.AUTHENTICATED_USER if user.getId() is None and not self.config.get('enable_anonymous', False): raise Unauthorized # to force login subscriptions = self.user_subscriptions(user) for subscription in subscriptions: subscription['location'] = path_in_site(subscription['object']) del subscription['object'] return subscriptions
def folder_entry(self, parent_path, folder_id, title, description, date, userid): parent = get_parent(self.context, parent_path) kwargs = { 'id': folder_id, 'contributor': userid or self.default_userid, 'releasedate': nydateformat(date), 'title': title, 'description': description, '_send_notifications': False, } new_folder_id = addNyFolder(parent, **kwargs) new_folder = parent[new_folder_id] logger.info("Added folder: %r", path_in_site(new_folder)) self.count['folders'] += 1
def handle_object_edit(event): """An object has been modified. Send instant notifications and create a log entry if the object is approved """ ob = event.context portal = ob.getSite() contributor = event.contributor notification_tool = portal.getNotificationTool() notification_tool.notify_instant(ob, contributor, ob_edited=True) if ob.approved: #Create log entry action_logger = portal.getActionLogger() action_logger.create(type=constants.LOG_TYPES['modified'], contributor=contributor, path=path_in_site(ob))
def place_pointers(ob, exclude=[]): """ Ads pointers to ob in target_groups, topics and countries """ props = { 'title': ob.title, 'description': getattr(ob, 'description', ''), 'topics': ob.__dict__.get('topics', []), 'target-groups': ob.__dict__.get('target-groups', []), 'geo_location.lat': '', 'geo_location.lon': '', 'geo_location.address': '', 'geo_type': getattr(ob, 'geo_type', ''), 'coverage': ob.__dict__.get('coverage', ''), 'keywords': ob.__dict__.get('keywords', ''), 'sortorder': getattr(ob, 'sortorder', ''), 'redirect': True, 'pointer': path_in_site(ob) } if ob.geo_location: if ob.geo_location.lat: props['geo_location.lat'] = unicode(ob.geo_location.lat) if ob.geo_location.lon: props['geo_location.lon'] = unicode(ob.geo_location.lon) if ob.geo_location.address: props['geo_location.address'] = ob.geo_location.address site = ob.getSite() target_groups = ob.__dict__.get("target-groups", []) topics = ob.__dict__.get("topics", []) locations = [] # pointer locations if 'target-groups' not in exclude and isinstance(target_groups, list): for tgrup in target_groups: locations.append( site.unrestrictedTraverse("resources/%s" % str(tgrup))) if isinstance(topics, list): for topic in topics: locations.append( site.unrestrictedTraverse("topics/%s" % str(topic))) locations.extend(get_countries(ob)) for loc in locations: if not props['sortorder']: props['sortorder'] = '200' p_id = addNyPointer(loc, '', contributor=ob.contributor, **props) pointer = getattr(loc, p_id) if pointer: if ob.approved: pointer.approveThis(1, ob.contributor) else: pointer.approveThis(0, None)
def xrjs_getGeoClusters(self, REQUEST): """ """ try: points = [] cluster_obs, single_obs = self.search_geo_clusters(REQUEST) for center, grouped_ids in cluster_obs: points.append( { "lat": center.lat, "lon": center.lon, "id": "", "label": "cluster", "icon_name": ("mk_cluster_%s" % self._pick_cluster(len(grouped_ids))), "tooltip": "", "num_records": len(grouped_ids), "point_ids": grouped_ids, } ) for res in single_obs: if res.geo_location is None: continue if not res.geo_type: # TODO: add logging? continue points.append( { "lat": res.geo_location.lat, "lon": res.geo_location.lon, "id": path_in_site(res), "label": res.title_or_id(), "icon_name": "mk_%s" % res.geo_type, "tooltip": self.get_marker(res), } ) response_data = {"points": points} except: self.log_current_error() response_data = {"error": err_info(), "points": {}} json_response = json.dumps(response_data, default=json_encode_helper) REQUEST.RESPONSE.setHeader("Content-type", "application/json") return json_response
def document_entry(self, parent_path, ob_id, filename, data_file, title, description, keywords, date, userid): from StringIO import StringIO assert isinstance(data_file, StringIO) data_file.filename = filename content_type, content_encoding = mimetypes.guess_type(filename) if content_type is None: content_type = 'application/octet-stream' bf = make_blobfile(data_file, content_type=content_type, removed=False, timestamp=datetime(date.year, date.month, date.day)) parent = get_parent(self.context, parent_path) orig_path = join_parent_path(parent_path, ob_id) if orig_path in self.rename: ob_path = self.rename.get(orig_path) the_file = self.context.restrictedTraverse(ob_path) logger.warn('new document version for %r' % orig_path) if keywords or description: logger.warn('ignoring keywords=%r, description=%r' % (keywords, description)) else: kwargs = { 'id': ob_id, 'contributor': userid or self.default_userid, 'releasedate': nydateformat(date), 'title': title, 'description': description, 'keywords': keywords, '_send_notifications': False, } assert ob_id not in parent.objectIds() the_file_id = addNyBFile(parent, **kwargs) if parent_path: self.rename[orig_path] = parent_path + '/' + the_file_id else: self.rename[orig_path] = the_file_id the_file = parent[the_file_id] the_file._versions.append(bf) logger.info("Added file: %r", path_in_site(the_file)) self.count['files'] += 1
def handle_object_approved(event): """ Called when an object has been approved """ if not event._send_notifications: return ob = event.context portal = ob.getSite() contributor = event.contributor notification_tool = portal.getNotificationTool() notification_tool.notify_administrative(ob, contributor) notification_tool.notify_maintainer(ob, ob.aq_parent, contributor=contributor) notification_tool.notify_instant(ob, contributor) action_logger = portal.getActionLogger() action_logger.create(type=constants.LOG_TYPES['approved'], contributor=contributor, path=path_in_site(ob))
def handle_edit_content(event): """ Test whether this requires adding pointers and perform the action """ obj = event.context site = obj.getSite() if not getattr(site, 'destinet.publisher', False): return None q_both = _qualifies_for_both(obj) q_topics = _qualifies_for_topics_only(obj) if q_topics or q_both: # clean-up all existing pointers, then re-add them cat = site.getCatalogTool() pointers = cat.search({ 'meta_type': 'Naaya Pointer', 'path': [ ofs_path(site.countries), ofs_path(site.topics), ofs_path(getattr(site, 'resources')), # kept for pointers prior to v 1.1 ofs_path(getattr(site, 'who-who')) ], 'pointer': path_in_site(obj) }) for brain in pointers: pointer = brain.getObject() pointer.aq_parent._delObject(pointer.id) if q_both: place_pointers(obj) else: place_pointers(obj, exclude=['target-groups']) # Make sure that the Destinet User keyword is added #langs = obj.aq_parent.gl_get_languages() if (obj.meta_type == "Naaya Contact"): set_address(obj) obj.geo_type = _get_geo_type(obj) if (obj.aq_parent.getId() == "destinet-users"): alter_contact(obj) obj.aq_parent.recatalogNyObject(obj)
def handle_comment_added(event): """An comment has been added to an object. Send notifications and create a log entry """ ob = event.context parent_ob = event.parent_ob portal = parent_ob.getSite() contributor = event.contributor notification_tool = portal.getNotificationTool() notification_tool.notify_comment_administrative(ob, parent_ob, contributor) notification_tool.notify_comment_maintainer(ob, parent_ob, contributor=contributor) notification_tool.notify_comment_instant(ob, parent_ob, contributor) action_logger = portal.getActionLogger() action_logger.create(type=constants.LOG_TYPES['commented'], contributor=contributor, path=path_in_site(parent_ob))
def handle_object_edit(event): """An object has been modified. Send instant notifications and create a log entry if the object is approved """ ob = event.context portal = ob.getSite() contributor = event.contributor notification_tool = portal.getNotificationTool() notification_tool.notify_administrative(ob, contributor, ob_edited=True) notification_tool.notify_maintainer(ob, ob.aq_parent, contributor=contributor, ob_edited=True) if ob.approved: #Create log entry notification_tool.notify_instant(ob, contributor, ob_edited=True) action_logger = portal.getActionLogger() action_logger.create(type=constants.LOG_TYPES['modified'], contributor=contributor, path=path_in_site(ob))