示例#1
0
def request_password_reset(user, profile, request):
    profile.password_reset_key = sha1(
        str(random.random())).hexdigest()
    profile.password_reset_time = datetime.datetime.now()
    context = find_site(profile)
    reset_url = model_url(
        context, request, "reset_confirm.html",
        query=dict(key=profile.password_reset_key))

    # send email
    mail = Message()
    system_name = get_setting(context, 'system_name', 'OpenCore')
    admin_email = get_setting(context, 'admin_email')
    mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
    mail["To"] = "%s <%s>" % (profile.title, profile.email)
    mail["Subject"] = "%s Password Reset Request" % system_name
    body = render_template(
        "templates/email_reset_password.pt",
        login=user['login'],
        reset_url=reset_url,
        system_name=system_name,
    )

    if isinstance(body, unicode):
        body = body.encode("UTF-8")

    mail.set_payload(body, "UTF-8")
    mail.set_type("text/html")

    recipients = [profile.email]
    mailer = getUtility(IMailDelivery)
    mailer.send(admin_email, recipients, mail)
示例#2
0
def _send_signup_ai_email(request, username, profile):
    """Send email to user who has signed up to site.
    """
    info = {}
    info['system_name'] = get_setting(profile, 'system_name', 'OpenCore')
    info['system_email_domain'] = get_setting(profile, 'system_email_domain')
    info['from_name'] = '%s invitation' % info['system_name']
    info['from_email'] = 'invitation@%s' % info['system_email_domain']
    info['c_title'] = info['system_name']
    info['c_description'] = ""
    info['c_href'] = request.api.app_url
    info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email'])
    info['subject'] = 'Thank you for joining the %s community' % info['system_name']
  
    body_template = get_template('templates/email_accept_signup_invitation.pt')

    mailer = getUtility(IMailDelivery)
    msg = Message()
    msg['From'] = info['mfrom']
    msg['To'] = profile.email
    msg['Subject'] = info['subject'] 
    body = body_template(
        system_name=info['system_name'],
        system_href=info['c_href'],                 
        username=username,
        )

    if isinstance(body, unicode):
        body = body.encode("UTF-8")

    msg.set_payload(body, "UTF-8")
    msg.set_type('text/html')
    mailer.send(info['mfrom'], [profile.email,], msg)    
示例#3
0
def _send_signup_email(request, invitation):
    site = find_site(request.context)
    mailer = getUtility(IMailDelivery)
    
    info = {}
    info['system_name'] = get_setting(site, 'system_name', 'OpenCore')
    info['system_email_domain'] = get_setting(site, 'system_email_domain')
    info['from_name'] = '%s invitation' % info['system_name']
    info['from_email'] = 'invitation@%s' % info['system_email_domain']
    info['c_title'] = info['system_name']
    info['c_description'] = ""
    info['c_href'] = model_url(site, request)
    info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email'])
    info['subject'] = 'Please join the %s community' % info['system_name']
    
    body_template = get_template('templates/email_signup.pt')

    msg = Message()
    msg['From'] = info['mfrom']
    msg['To'] = invitation.email
    msg['Subject'] = info['subject']
    body = body_template(
        system_name=info['system_name'],
        personal_message=invitation.message,
        invitation_url=model_url(site, request, 'signup', invitation.__name__)
        )

    if isinstance(body, unicode):
        body = body.encode("UTF-8")

    msg.set_payload(body, "UTF-8")
    msg.set_type('text/html')
    mailer.send(info['mfrom'], [invitation.email,], msg)    
示例#4
0
def _format_date(context, date):
    date = ''.join(date.split('.')[0])

    date_format_from = get_setting(context, 'messaging_date_format_from')
    date_format_to = get_setting(context, 'messaging_date_format_to')

    return strftime(date_format_to, strptime(date, date_format_from))
示例#5
0
def _get_common_email_info(community, community_href):
    info = {}
    info['system_name'] = get_setting(community, 'system_name', 'OpenCore')
    info['system_email_domain'] = get_setting(community,
                                              'system_email_domain')
    info['from_name'] = '%s invitation' % info['system_name']
    info['from_email'] = 'invitation@%s' % info['system_email_domain']
    info['c_title'] = community.title
    info['c_description'] = community.description
    info['c_href'] = community_href
    info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email'])

    return info
示例#6
0
 def __init__(self, profile, eventinfo):
     self.eventinfo = eventinfo
     self.profile = profile
     log.debug('Alert: %s, profile=%s, event=%s' % \
               (self.__class__.__name__, profile, str(eventinfo)))
           
     self.system_name = get_setting(None, "system_name", "OpenCore")
     self.admin_email = get_setting(None, 'admin_email', '*****@*****.**')
     self.notifications_reply_to = get_setting(None, 'notifications_reply_to', 'noreply')
     self.system_email_domain = get_setting(None, "system_email_domain")
     self.site_url = get_setting(None, 'public_domain_root',
                                             'http://localhost:6543')
     self.sent_from = self.admin_email 
     self.is_profile_alert = False
示例#7
0
 def __init__(self, context, request, page_title=None):
     super(AdminTemplateAPI, self).__init__(context, request, page_title)
     syslog_view = get_setting(context, 'syslog_view', None)
     self.syslog_view_enabled = syslog_view != None
     self.has_logs = not not get_setting(context, 'logs_view', None)
     self.error_monitoring = not not get_setting(
         context, 'error_monitor_subsystems', None
     )
     statistics_folder = get_setting(context, 'statistics_folder', None)
     if statistics_folder is not None:
         csv_files = [fn for fn in os.listdir(statistics_folder)
                      if fn.endswith('.csv')]
         self.statistics_view_enabled = not not csv_files
     else:
         self.statistics_view_enabled = False
示例#8
0
 def emit_to_user(self, profile, event):
     alerts_on = get_setting(profile, 'alert_notifications_on', 'true')
     if not asbool(alerts_on):
         log.debug('alert notifications are disabled, alert not sent.')
         return
     
     alert = event
     
     # flag alerts are treated differently. Just send straight to admin 
     # not the flagged user.
     if isinstance(alert, FlagAlert):
         log.info('flag alert received. sending directly to admin only.')
         self._send_immediately(alert)
         return
     
     def action_pref(pref, alert):
         if pref == IProfile.ALERT_DIGEST:
             self._queue_digest(alert, profile)
         elif pref == IProfile.ALERT_IMMEDIATELY:
             self._send_immediately(alert)
             
     alerts_inbox_on = get_setting(profile, 'alert_notifications_inbox_on',
                                   'false')
     if not asbool(alerts_inbox_on):
         log.debug('alert inbox notifications are disabled, alert not sent '
                   'to inbox.')
     else:
         # preferences not used for inbox, alert always sent    
         self._send_to_inbox(alert, profile)        
       
     # profile alerts are for content that does not belong to a community 
     # such as profile comments
     if alert.is_profile_alert:
         log.debug('profile alert')
         action_pref(profile.get_alerts_preference('profile'), alert)
         return
     
     community = find_community(event['content'])          
     if community:   
         community_pref = profile.get_alerts_preference(community.__name__)
         log.debug('alert received for user: %s, alert: %s, in community: '
           '%s with pref:%s' % (profile.__name__, str(alert),
                                community.__name__, community_pref)) 
         action_pref(community_pref, alert)  
         return 
     
     # site preference e.g. for hcd stories                             
     action_pref(profile.get_alerts_preference('site'), alert)
示例#9
0
    def handle_submit(self, validated):
        
        user = _get_user_by_email(self.context, validated['email'])
        
        # No such user, we're not letting anyone know about it though to protect
        # users from crooks trying to explore the users DB in hope of finding
        # out who has an account here.
        if not user:
            return self._redirect()
        
        request_id = uuid4().hex
        request = PasswordRequestRequest(request_id, user.email)
        
        site = find_site(self.context)
        if user.email in site['reset_password']:
            del site['reset_password'][user.email]
            
        site['reset_password'][user.email] = request

        reset_url = model_url(self.context, self.request, 
                              "reset.html", query=dict(key=request_id))
        
        # send email
        mail = Message()
        system_name = get_setting(self.context, 'system_name', 'OpenCore')
        admin_email = get_setting(self.context, 'admin_email')
        mail["From"] = "%s Administrator <%s>" % (system_name, admin_email)
        mail["To"] = "%s <%s>" % (user.title, user.email)
        mail["Subject"] = "%s Password Reset Request" % system_name
        body = render_template(
            "templates/email_reset_password.pt",
            login=user.__name__,
            reset_url=reset_url,
            system_name=system_name,
            valid_hours=REQUEST_VALIDITY_HOURS,
        )
    
        if isinstance(body, unicode):
            body = body.encode("UTF-8")
    
        mail.set_payload(body, "UTF-8")
        mail.set_type("text/html")
    
        recipients = [user.email]
        mailer = getUtility(IMailDelivery)
        mailer.send(admin_email, recipients, mail)
        
        return self._redirect()
示例#10
0
def logs_view(context, request):
    log_paths = get_setting(context, 'logs_view')
    log_paths = map(os.path.abspath, log_paths.split())
    if len(log_paths) == 1:
        # Only one log file, just view that
        log = log_paths[0]

    else:
        # Make user pick a log file
        log = request.params.get('log', None)

        # Don't let users view arbitrary files on the filesystem
        if log not in log_paths:
            log = None

    if log is not None and os.path.exists(log):
        lines = codecs.open(log, encoding='utf-8',
                            errors='replace').readlines()
    else:
        lines = []

    return dict(
        api=AdminTemplateAPI(context, request),
        menu=_menu_macro(),
        logs=log_paths,
        log=log,
        lines=lines,
    )
示例#11
0
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]
示例#12
0
 def __init__(self, *args):
     super(MembersBaseController,self).__init__(*args)
     self.community = find_interface(self.context, ICommunity)
     self.actions = _get_manage_actions(self.community, self.request)
     self.profiles = find_profiles(self.context)
     self.system_name = get_setting(
         self.context, 'system_name', 'OpenCore'
         )
     self.data['actions']=self.actions
示例#13
0
def get_group_options(context):
    group_options = []
    for group in get_setting(context, "selectable_groups").split():
        if group.startswith('group.'):
            title = group[6:]
        else:
            title = group
        group_options.append((group, title))
    return group_options
示例#14
0
def statistics_view(context, request):
    statistics_folder = get_setting(context, 'statistics_folder')
    csv_files = [fn for fn in os.listdir(statistics_folder)
                 if fn.endswith('.csv')]
    return dict(
        api=AdminTemplateAPI(context, request),
        menu=_menu_macro(),
        csv_files=csv_files
    )
示例#15
0
def fetch_twitter(context, feed_format):
    twitter_search_id = get_setting(context, 'twitter_search_id')
    if not twitter_search_id:
        raise ValueError('no value found for twitter_search_id in config (ini). Unable to search twitter.')
    
    search_url = 'http://search.twitter.com/search.%s?q=%s' % (feed_format, twitter_search_id)
    log.info('twitter_site_atom_view: GET %s' % search_url)
    feed_xml, headers = fetch_url(search_url)
    
    return feed_xml, headers
示例#16
0
def statistics_csv_view(request):
    statistics_folder = get_setting(request.context, 'statistics_folder')
    csv_file = request.matchdict.get('csv_file')
    if not csv_file.endswith('.csv'):
        raise NotFound()

    path = os.path.join(statistics_folder, csv_file)
    if not os.path.exists(path):
        raise NotFound()

    return request.get_response(FileApp(path).get)
示例#17
0
def get_topic_options(context):
    topic_options = []
    topic_line = get_setting(context, "topics")

    if not topic_line:
        return topic_options

    for topic in topic_line.split('\n'):
        if topic != '':
            topic_options.append(topic)
    return topic_options
示例#18
0
    def update_details(self, context, request, api, photo_thumb_size):

        # Create display values from model object

        for name in [name for name in context.__dict__.keys() if not name.startswith("_")]:
            profile_value = getattr(context, name)
            if profile_value is not None:
                # Don't produce u'None'
                self[name] = unicode(profile_value)
            else:
                self[name] = None

        # 'websites' is a tuple, so unicode(websites) is not what we want
        self["websites"] = context.websites

        # 'title' is a property, so need to access it directly
        self["title"] = context.title

        # 'created' is also a property and needs formatting too
        self['created'] = context.created.strftime('%B %d, %Y')

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

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

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

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

        # Display portrait
        photo = context.get('photo')
        display_photo = {}
        if photo is not None:
            display_photo["url"] = thumb_url(photo, request, photo_thumb_size)
        else:
            display_photo["url"] = api.static_url + "/img/default_user.png"
        self["photo"] = display_photo

        if get_setting(context, 'twitter_search_id'):
            # assume it's a social app
            social = social_category(context, None)
            if social:
                self.update(social.ids())
示例#19
0
def community_tag_listing_view(context, request):
    page_title = 'Tag Listing'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)

    if tags is None:
        entries = ()
    else:
        entries = [{'name': x[0], 'count': x[1]}
                        for x in tags.getFrequency(community=context.__name__)]
        entries.sort(key=lambda x: x['name'])

    system_name = get_setting(context, 'system_name', 'KARL')
    return dict(
        api=api,
        entries=entries,
        crumbs='%s / Communities / %s' % (system_name, context.__name__),
        )
示例#20
0
def show_profiles_view(context, request):
    system_name = get_setting(context, 'system_name', 'OpenCore')
    page_title = '%s Profiles' % system_name
    api = request.api
    api.page_title = page_title

    # Grab the data for the two listings, main communities and portlet
    search = ICatalogSearch(context)

    query = dict(sort_index='title', interfaces=[IProfile], limit=5)

    titlestartswith = request.params.get('titlestartswith')
    if titlestartswith:
        query['titlestartswith'] = (titlestartswith, titlestartswith)

    num, docids, resolver = search(**query)

    profiles = []
    for docid in docids:
        model = resolver(docid)
        if model is None:
            continue
        profiles.append(model)


    members = []

    for profile in profiles:
        members.append({
                        'url' : '%s/%s/' % (request.api.people_url, profile.__name__),
                        'title' :  profile.title,
                        'firstname' : profile.firstname,
                        'biography' : profile.biography
                        })

    return render_template_to_response(
        'templates/profiles.pt',
        api=api,
        profiles=profiles,
        members=members,
        )
示例#21
0
def community_tag_cloud_view(context, request):
    page_title = 'Tag Cloud'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)
    if tags is not None:
        cloud = [{'name': x[0], 'count': x[1]}
                    for x in tags.getCloud(community=context.__name__)]
        limited = list(reversed(sorted(cloud, key=lambda x: x['count']))
                      )[:100]
        entries = sorted(_calculateTagWeights(limited),
                         key=lambda x: x['name'])
    else:
        entries = ()

    system_name = get_setting(context, 'system_name', 'KARL')
    return dict(
        api=api,
        entries=entries,
        crumbs='%s / Communities / %s' % (system_name, context.__name__),
        )
示例#22
0
文件: api.py 项目: amarandon/opencore
 def people_url(self):
     # Get a setting for what part is appended the the app_url for
     # this installation's people directory application.
     people_path = get_setting(self.context, 'people_path', 'people')
     return self.app_url + "/" + people_path
示例#23
0
文件: api.py 项目: amarandon/opencore
 def logo_url(self):
     logo_path = get_setting(self.context, 'logo_path', 'images/logo.gif')
     return '%s/%s' % (self.static_url, logo_path)
示例#24
0
   
    view_cookie = request.cookies.get(_VIEW_COOKIE)
    classes = []
    for name, title, description, urlname in _VIEWS:
        classes.append({'name': name,
                        'title': title,
                        'description': description,
                        'href': urlname,
                        'selected': name == view_cookie,
                       })

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

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

    my_communities = [] #get_my_communities(context, request)

    preferred_communities = []#get_preferred_communities(context, request)
    api = request.api
    api.page_title = page_title
      
    return {'communities': communities,
            'batch_info': batch_info,
            'letters': {}, #letter_info,
            'community_tabs': classes,
            'actions': actions,
            'my_communities': my_communities, 
            'preferred_communities': preferred_communities,
示例#25
0
def showtag_view(context, request, community=None, user=None, crumb_title=None):
    """Show a page for a particular tag, optionally refined by context."""

    page_title = 'Show Tag'
    api = request.api
    api.page_title = page_title

    # The tag screens (cloud, listing, and this view) each have a
    # "jump box" that allows you to quickly jump to another tag.  All
    # three will point here at /showtag?tag=tag1.  We detect this mode
    # and do a redirect.
    jump_tag = request.params.get('jumptag', False)
    if jump_tag:
        location = model_url(context, request, request.view_name, jump_tag)
        return HTTPFound(location=location)

    # Our strategy is to support tag URLs that are like this:
    #     /showtag/tag1
    # ...instead of:
    #     /tagpage.html?tag=tag1
    # However, our tag data isn't traversable (it is site.tags and not
    # site['tags'].  So we have a view at /showtag that picks apart
    # the next hop in the URL.
    tag = request.subpath
    if not tag:
        # The user didn't provide anything beyond /showtag in the URL
        tag = None
        entries = related = []
    else:
        # Ahh, the good part.  Let's find some tag results and unpack
        # data into what the ZPT needs.
        tag = tag[0]
        page_title = 'Show Tag ' + tag

        catalog = find_catalog(context)
        dm = catalog.document_map
        tags = find_tags(context)
        related = tags.getRelatedTags(tag, user=user, community=community)
        entries = []
        if user:
            users = (user,)
        else:
            users = None
        for docid in tags.getItems(tags=(tag,), users=users,
                                   community=community,
                                   ):
            # XXX Need to wire in batching
            address = dm.address_for_docid(int(docid))
            if address is None:
                raise KeyError(docid)
            resource = find_model(context, address)

            # Skip documents which aren't viewable by authenticated user
            #if not has_permission('view', resource, request):
            #    continue

            # Do a secondary query for each result to find the
            # per-user info
            users = tags.getUsers(tags=(tag,), items=(docid,),
                                  community=community)
            if len(users) == 1:
                tuh = '1 person'
            else:
                tuh = '%s people' % len(users)

            tuhref = model_url(context, request, 'tagusers.html',
                               query={'tag': tag, 'docid': docid})
            entry = {
                'title': resource.title,
                'description': getattr(resource, 'description', ''),
                'href': model_url(resource, request),
                'type': get_content_type_name(resource),
                'tagusers_href': tuhref,
                'tagusers_count': tuh,
                }
            entries.append(entry)

    args = dict(
        api=api,
        tag=tag,
        entries=entries,
        related=related,
    )

    if crumb_title:
        # XXX Would context.title be a bit nicer for displaying to user?
        system_name = get_setting(context, 'system_name', 'KARL')
        args['crumbs'] = '%s / %s / %s' % (
            system_name, crumb_title, context.__name__)

    return dict(**args)
示例#26
0
文件: api.py 项目: amarandon/opencore
 def __getattr__(self, name):
     return get_setting(self._context, name)
示例#27
0
文件: api.py 项目: amarandon/opencore
def get_template_api(context, request):
    name = get_setting(request, 'package')
    factory = queryUtility(ITemplateAPI, name=name, default=TemplateAPI)
    return factory(context, request)
示例#28
0
文件: api.py 项目: amarandon/opencore
    def topics(self, context):
	topics = get_setting(context, 'topics')
	return sorted(elem.strip() for elem in topics.split('\n') if elem)
示例#29
0
def min_pw_length():
    global _MIN_PW_LENGTH
    if _MIN_PW_LENGTH is None:
        _MIN_PW_LENGTH = get_setting(None, 'min_pw_length', 8)
    return _MIN_PW_LENGTH
示例#30
0
    def send_digests(self, context):
                
        mailer = getUtility(IMailDelivery)

        system_name = get_setting(context, "system_name", "OpenCore")
        admin_email = get_setting(None, 'admin_email', '*****@*****.**')
        #system_email_domain = get_setting(context, "system_email_domain")
        sent_from = admin_email #"%s@%s" % (admin_name, system_email_domain)
        from_addr = "%s notification <%s>" % (system_name, sent_from)
        subject = "%s: Today's Challenge Daily Digest" % system_name
        site_url = get_setting(context, 'public_domain_root', 'http://localhost:6543/')

        template = get_template("email_digest.pt")

        for profile in find_profiles(context).values():
            if not profile._pending_alerts:
                continue

            # Perform each in its own transaction, so a problem with one
            # user's email doesn't block all others
            transaction.manager.begin()
            try:
                attachments = []
                for alert in profile._pending_alerts:
                    attachments += alert['attachments']

                msg = MIMEMultipart() if attachments else Message()
                msg["From"] = from_addr
                msg["To"] = "%s <%s>" % (profile.title, profile.email)
                msg["Subject"] = subject
                profile_url='%sprofiles/%s/' % (site_url, profile.__name__)

                body_text = template(
                    system_name=system_name,
                    alerts=profile._pending_alerts,
                    site_url=site_url,
                    manage_preferences_href=profile_url,
                    creator=profile,
                    profile_image_url='%sprofile_thumbnail' % profile_url,
                    profile_image_thumb_url='%sprofile_thumbnail' % profile_url
                )

                if isinstance(body_text, unicode):
                    body_text = body_text.encode("UTF-8")

                if attachments:  # pragma: no cover
                    body = MIMEText(body_text, 'html', 'utf-8')
                    msg.attach(body)
                else:
                    msg.set_payload(body_text, "UTF-8")
                    msg.set_type("text/html")

                for attachment in attachments:  # pragma: no cover
                    msg.attach(attachment)

                mailer.send(sent_from, [profile.email,], msg)
                del profile._pending_alerts[:]
                transaction.manager.commit()

            except Exception, e:
                # Log error and continue
                log.error("Error sending digest to %s <%s>" %
                          (profile.title, profile.email))

                b = StringIO()
                traceback.print_exc(file=b)
                log.error(b.getvalue())
                b.close()

                transaction.manager.abort()