Exemplo n.º 1
0
 def do_login_first(error=401):
     """Displays login page when user is not authorised."""
     if request.is_xhr:
         return g._("Authorization failure"), 401
     if current_user.is_guest:
         flash(g._("Please sign in to continue."), 'info')
     else:
         flash(g._("Authorization failure."), 'danger')
     from invenio.modules.accounts.views.accounts import login
     return login(referer=request.url), 401
Exemplo n.º 2
0
 def do_login_first(error=401):
     """Display login page when user is not authorised."""
     if request.is_xhr:
         return g._("Authorization failure"), 401
     secure_url = url_for(request.endpoint, _external=True, _scheme='https',
                          **request.view_args)
     if not urllib.unquote(secure_url).startswith(request.base_url):
         return redirect(secure_url)
     if current_user.is_guest:
         if not session.get('_flashes'):
             flash(g._("Please sign in to continue."), 'info')
         from invenio_accounts.views.accounts import login
         return login(referer=request.url)
     else:
         from flask import render_template
         return render_template("401.html"), 401
Exemplo n.º 3
0
 def do_login_first(error=401):
     """Display login page when user is not authorised."""
     if request.is_xhr:
         return g._("Authorization failure"), 401
     secure_url = url_for(request.endpoint, _external=True, _scheme='https',
                          **request.view_args)
     if not urllib.unquote(secure_url).startswith(request.base_url):
         return redirect(secure_url)
     if current_user.is_guest:
         if not session.get('_flashes'):
             flash(g._("Please sign in to continue."), 'info')
         from invenio.modules.accounts.views.accounts import login
         return login(referer=request.url)
     else:
         from flask import render_template
         return render_template("401.html"), 401
Exemplo n.º 4
0
 def formatoptions(self):
     if len(self._formatoptions):
         return [dict(f) for f in self._formatoptions]
     else:
         return [{
             'code': 'hb',
             'name': "HTML %s" % g._("brief"),
             'content_type': 'text/html'
         }]
Exemplo n.º 5
0
 def search_within(self):
     """Collect search within options."""
     default = [('', g._('any field'))]
     found = [(o.field.code, o.field.name_ln) for o in self._search_within]
     if not found:
         found = [(f.name.replace(' ', ''), f.name_ln)
                  for f in Field.query.filter(Field.name.in_(
                      cfg['CFG_WEBSEARCH_SEARCH_WITHIN'])).all()]
     return default + sorted(found, key=itemgetter(1))
Exemplo n.º 6
0
 def search_within(self):
     """
     Collect search within options.
     """
     from invenio.search_engine_config import CFG_WEBSEARCH_SEARCH_WITHIN
     default = [('', g._('any field'))]
     found = [(o.field.code, o.field.name_ln) for o in self._search_within]
     if not found:
         found = [(f.name.replace(' ', ''), f.name_ln)
                  for f in Field.query.filter(
                      Field.name.in_(CFG_WEBSEARCH_SEARCH_WITHIN)).all()]
     return default + sorted(found, key=itemgetter(1))
Exemplo n.º 7
0
        def decorated_function(*args, **kwargs):
            if not model or not columns:
                return f(*args, **kwargs)
            where = []
            for column, op in iteritems(columns):
                try:
                    values = request.values.getlist(column)
                    if not values:
                        continue
                    column_keys = column.split('.')
                    if hasattr(model, column_keys[0]):
                        cond = reduce(
                            lambda x, y: getattr(x.property.table.columns, y),
                            column_keys[1:], getattr(model, column_keys[0]))
                        current_app.logger.debug("Filtering by: %s = %s" %
                                                 (cond, values))

                        # Multi-values support
                        if len(values) > 0:
                            # Ignore empty values when using start with,
                            # contains or similar.
                            # FIXME: add per field configuration
                            values = [
                                value for value in values
                                if len(value) > 0 or filter_empty
                            ]
                            if op == operators.eq:
                                where.append(sae.in_(values))
                            else:
                                or_list = []
                                for value in values:
                                    or_list.append(op(cond, value))
                                where.append(sae.or_(*or_list))
                        else:
                            where.append(op(cond, value))
                except:
                    flash(
                        g._("Invalid filtering key '%(x_key)s'.",
                            x_key=column))
            if form is not None:
                filter_form = form(request.values)

                # FIXME replace by signal when Flask 1.0 is out
                from invenio_ext.template.context_processor import \
                    register_template_context_processor

                @register_template_context_processor
                def inject_filter_form():
                    return dict(filter_form=filter_form)

            # Generate ClauseElement for filtered columns.
            kwargs['filter'] = sae.and_(*where)
            return f(*args, **kwargs)
Exemplo n.º 8
0
        def decorated_function(*args, **kwargs):
            if not model or not columns:
                return f(*args, **kwargs)
            where = []
            for column, op in iteritems(columns):
                try:
                    values = request.values.getlist(column)
                    if not values:
                        continue
                    column_keys = column.split(".")
                    if hasattr(model, column_keys[0]):
                        cond = reduce(
                            lambda x, y: getattr(x.property.table.columns, y),
                            column_keys[1:],
                            getattr(model, column_keys[0]),
                        )
                        current_app.logger.debug("Filtering by: %s = %s" % (cond, values))

                        # Multi-values support
                        if len(values) > 0:
                            # Ignore empty values when using start with,
                            # contains or similar.
                            # FIXME: add per field configuration
                            values = [value for value in values if len(value) > 0 or filter_empty]
                            if op == operators.eq:
                                where.append(sae.in_(values))
                            else:
                                or_list = []
                                for value in values:
                                    or_list.append(op(cond, value))
                                where.append(sae.or_(*or_list))
                        else:
                            where.append(op(cond, value))
                except:
                    flash(g._("Invalid filtering key '%(x_key)s'.", x_key=column))
            if form is not None:
                filter_form = form(request.values)

                # FIXME replace by signal when Flask 1.0 is out
                from invenio_ext.template.context_processor import register_template_context_processor

                @register_template_context_processor
                def inject_filter_form():
                    return dict(filter_form=filter_form)

            # Generate ClauseElement for filtered columns.
            kwargs["filter"] = sae.and_(*where)
            return f(*args, **kwargs)
Exemplo n.º 9
0
 def decorated_function(*args, **kwargs):
     sort_by = request.args.get('sort_by', None)
     order_fn = {'asc': db.asc,
                 'desc': db.desc}.get(request.args.get('order', 'asc'),
                                      db.asc)
     sort = False
     if model is not None and sort_by is not None and (
             cols is None or sort_by in cols):
         try:
             sort_keys = sort_by.split('.')
             if hasattr(model, sort_keys[0]):
                 sort = order_fn(reduce(lambda x, y: getattr(
                     x.property.table.columns, y), sort_keys[1:],
                     getattr(model, sort_keys[0])))
         except:
             flash(g._("Invalid sorting key '%(x_key)s'.", x_key=sort_by))
     kwargs['sort'] = sort
     return f(*args, **kwargs)
Exemplo n.º 10
0
 def decorated_function(*args, **kwargs):
     sort_by = request.args.get("sort_by", None)
     order_fn = {"asc": sae.asc, "desc": sae.desc}.get(request.args.get("order", "asc"), sae.asc)
     sort = False
     if model is not None and sort_by is not None and (cols is None or sort_by in cols):
         try:
             sort_keys = sort_by.split(".")
             if hasattr(model, sort_keys[0]):
                 sort = order_fn(
                     reduce(
                         lambda x, y: getattr(x.property.table.columns, y),
                         sort_keys[1:],
                         getattr(model, sort_keys[0]),
                     )
                 )
         except:
             flash(g._("Invalid sorting key '%(x_key)s'.", x_key=sort_by))
     kwargs["sort"] = sort
     return f(*args, **kwargs)
Exemplo n.º 11
0
 def decorated_function(*args, **kwargs):
     sort_by = request.args.get('sort_by', None)
     order_fn = {
         'asc': db.asc,
         'desc': db.desc
     }.get(request.args.get('order', 'asc'), db.asc)
     sort = False
     if model is not None and sort_by is not None and (cols is None or
                                                       sort_by in cols):
         try:
             sort_keys = sort_by.split('.')
             if hasattr(model, sort_keys[0]):
                 sort = order_fn(
                     reduce(
                         lambda x, y: getattr(x.property.table.columns,
                                              y), sort_keys[1:],
                         getattr(model, sort_keys[0])))
         except:
             flash(
                 g._("Invalid sorting key '%(x_key)s'.", x_key=sort_by))
     kwargs['sort'] = sort
     return f(*args, **kwargs)
 def get_title(self, **kwargs):
     """Return facet title."""
     return g._('Any ' + self.name.capitalize())
Exemplo n.º 13
0
def send_email(
    fromaddr,
    toaddr,
    subject="",
    content="",
    html_content='',
    html_images=None,
    header=None,
    footer=None,
    html_header=None,
    html_footer=None,
    copy_to_admin=0,
    attempt_times=1,
    attempt_sleeptime=10,
    debug_level=0,
    ln=None,
    charset=None,
    replytoaddr="",
    attachments=None,
    bccaddr="",
    forward_failures_to_admin=True,
):
    """Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly
    header and footer.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ','). BEWARE: If more than once receiptiant is given,
                   the receivers are put in BCC and To will be "Undisclosed.Recipients:".
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] header to add, None for the Default
    @param footer: [string] footer to add, None for the Default
    @param html_header: [string] header to add to the html part, None for the Default
    @param html_footer: [string] footer to add to the html part, None for the Default
    @param copy_to_admin: [int] if 1 add CFG_SITE_ADMIN_EMAIL in receivers
    @param attempt_times: [int] number of tries
    @param attempt_sleeptime: [int] seconds in between tries
    @param debug_level: [int] debug level
    @param ln: [string] invenio language
    @param charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)
    @param bccaddr: [string or list-of-strings] to be used for BCC header of the email
                    (if string, then receivers are separated by ',')
    @param forward_failures_to_admin: [bool] prevents infinite recursion
                                             in case of admin reporting,
                                             when the problem is not in
                                             the e-mail address format,
                                             but rather in the network

    If sending fails, try to send it ATTEMPT_TIMES, and wait for
    ATTEMPT_SLEEPTIME seconds in between tries.

    e.g.:
    send_email('*****@*****.**', '*****@*****.**', 'Let\'s try!'', 'check 1234', '<strong>check</strong> <em>1234</em><img src="cid:image1">', {'image1': '/tmp/quantum.jpg'})

    @return: [bool]: True if email was sent okay, False if it was not.
    """
    from invenio.ext.logging import register_exception
    ln = default_ln(ln)

    if html_images is None:
        html_images = {}

    if type(toaddr) is not list:
        toaddr = toaddr.strip().split(',')
    toaddr = remove_temporary_emails(toaddr)

    usebcc = len(
        toaddr) > 1  # More than one address, let's use Bcc in place of To

    if copy_to_admin:
        if cfg['CFG_SITE_ADMIN_EMAIL'] not in toaddr:
            toaddr.append(cfg['CFG_SITE_ADMIN_EMAIL'])

    if type(bccaddr) is not list:
        bccaddr = bccaddr.strip().split(',')

    msg = forge_email(fromaddr, toaddr, subject, content, html_content,
                      html_images, usebcc, header, footer, html_header,
                      html_footer, ln, charset, replytoaddr, attachments,
                      bccaddr)

    if attempt_times < 1 or not toaddr:
        try:
            raise EmailError(
                g._(
                    'The system is not attempting to send an email from %(x_from)s'
                    ', to %(x_to)s, with body %(x_body)s.',
                    x_from=fromaddr,
                    x_to=toaddr,
                    x_body=content))
        except EmailError:
            register_exception()
        return False
    sent = False
    failure_reason = ''
    while not sent and attempt_times > 0:
        try:
            sent = msg.send()
        except Exception as e:
            failure_reason = str(e)
            register_exception()
            if debug_level > 1:
                try:
                    raise EmailError(g._('Error in sending message. \
                        Waiting %(sec)s seconds. Exception is %(exc)s, \
                        while sending email from %(sender)s to %(receipient)s \
                        with body %(email_body)s.'                                                  , \
                        sec = attempt_sleeptime, \
                        exc = sys.exc_info()[0], \
                        sender = fromaddr, \
                        receipient = toaddr, \
                        email_body = content))
                except EmailError:
                    register_exception()
        if not sent:
            attempt_times -= 1
            if attempt_times > 0:  # sleep only if we shall retry again
                sleep(attempt_sleeptime)
    if not sent:
        # report failure to the admin with the intended message, its
        # sender and recipients
        if forward_failures_to_admin:
            # prepend '> ' to every line of the original message
            quoted_body = '> ' + '> '.join(content.splitlines(True))

            # define and fill in the report template
            admin_report_subject = g._(
                'Error while sending an email: %(x_subject)s',
                x_subject=subject)
            admin_report_body = g._(
                "\nError while sending an email.\n"
                "Reason: %(x_reason)s\n"
                "Sender: \"%(x_sender)s\"\n"
                "Recipient(s): \"%(x_recipient)s\"\n\n"
                "The content of the mail was as follows:\n"
                "%(x_body)s",
                x_reason=failure_reason,
                x_sender=fromaddr,
                x_recipient=', '.join(toaddr),
                x_body=quoted_body)

            send_email(cfg['CFG_SITE_ADMIN_EMAIL'],
                       cfg['CFG_SITE_ADMIN_EMAIL'],
                       admin_report_subject,
                       admin_report_body,
                       forward_failures_to_admin=False)

        try:
            raise EmailError(
                g._(
                    'Error in sending email from %(x_from)s to %(x_to)s with body'
                    '%(x_body)s.',
                    x_from=fromaddr,
                    x_to=toaddr,
                    x_body=content))
        except EmailError:
            register_exception()
    return sent
Exemplo n.º 14
0
 def __init__(self):
     super(WebAccountSettings, self).__init__()
     self.icon = 'user'
     self.title = g._('Account')
     self.edit = url_for('accounts_settings.profile')
Exemplo n.º 15
0
def send_email(fromaddr,
               toaddr,
               subject="",
               content="",
               html_content='',
               html_images=None,
               header=None,
               footer=None,
               html_header=None,
               html_footer=None,
               copy_to_admin=0,
               attempt_times=1,
               attempt_sleeptime=10,
               debug_level=0,
               ln=CFG_SITE_LANG,
               charset=None,
               replytoaddr="",
               attachments=None):
    """Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly
    header and footer.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] header to add, None for the Default
    @param footer: [string] footer to add, None for the Default
    @param html_header: [string] header to add to the html part, None for the Default
    @param html_footer: [string] footer to add to the html part, None for the Default
    @param copy_to_admin: [int] if 1 add CFG_SITE_ADMIN_EMAIL in receivers
    @param attempt_times: [int] number of tries
    @param attempt_sleeptime: [int] seconds in between tries
    @param debug_level: [int] debug level
    @param ln: [string] invenio language
    @param charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)

    If sending fails, try to send it ATTEMPT_TIMES, and wait for
    ATTEMPT_SLEEPTIME seconds in between tries.

    e.g.:
    send_email('*****@*****.**', '*****@*****.**', 'Let\'s try!'', 'check 1234', '<strong>check</strong> <em>1234</em><img src="cid:image1">', {'image1': '/tmp/quantum.jpg'})

    @return: [bool]: True if email was sent okay, False if it was not.
    """

    if html_images is None:
        html_images = {}

    if type(toaddr) is str:
        toaddr = toaddr.strip().split(',')

    toaddr = remove_temporary_emails(toaddr)

    usebcc = len(toaddr.split(
        ',')) > 1  # More than one address, let's use Bcc in place of To

    if copy_to_admin:
        if CFG_SITE_ADMIN_EMAIL not in toaddr:
            toaddr.append(CFG_SITE_ADMIN_EMAIL)

    body = forge_email(fromaddr, toaddr, subject, content, html_content,
                       html_images, usebcc, header, footer, html_header,
                       html_footer, ln, charset, replytoaddr, attachments)

    if attempt_times < 1 or not toaddr:
        try:
            raise InvenioMiscUtilError(
                g.
                _('The system is not attempting to send an email from %s, to %s, with body %s.'
                  ) % (fromaddr, toaddr, body))
        except InvenioMiscUtilError:
            register_exception()
        return False
    sent = False
    while not sent and attempt_times > 0:
        sent = body.send()
        try:
            sent = body.send()
        except Exception:
            register_exception()
            if debug_level > 1:
                try:
                    raise InvenioMiscUtilError(
                        g.
                        _('Error in sending message. Waiting %s seconds. Exception is %s, while sending email from %s to %s with body %s.'
                          ) % (attempt_sleeptime, sys.exc_info()[0], fromaddr,
                               toaddr, body))
                except InvenioMiscUtilError:
                    register_exception()
        if not sent:
            attempt_times -= 1
            if attempt_times > 0:  # sleep only if we shall retry again
                sleep(attempt_sleeptime)
    if not sent:
        try:
            raise InvenioMiscUtilError(
                g._('Error in sending email from %s to %s with body %s.') %
                (fromaddr, toaddr, body))
        except InvenioMiscUtilError:
            register_exception()
    return sent
Exemplo n.º 16
0
def inject_utils():
    """
    This will add some more variables and functions to the Jinja2 to execution
    context. In particular it will add:

    - `url_for`: an Invenio specific wrapper of Flask url_for, that will let you
                 obtain URLs for non Flask-native handlers (i.e. not yet ported
                 Invenio URLs)
    - `breadcrumbs`: this will be a list of three-elements tuples, containing
                 the hierarchy of Label -> URLs of navtrails/breadcrumbs.
    - `_`: this can be used to automatically translate a given string.
    - `is_language_rtl`: is True if the chosen language should be read right to left
    """
    from werkzeug.routing import BuildError

    from invenio.messages import is_language_rtl
    from invenio.webinterface_handler_flask_utils import _, guess_language
    from invenio.webuser_flask import current_user
    from invenio.urlutils import create_url, get_canonical_and_alternates_urls

    def invenio_url_for(endpoint, **values):
        try:
            return url_for(endpoint, **values)
        except BuildError:
            if endpoint.startswith('http://') or endpoint.startswith(
                    'https://'):
                return endpoint
            if endpoint.startswith('.'):
                endpoint = request.blueprint + endpoint
            return create_url('/' + '/'.join(endpoint.split('.')), values,
                              False).decode('utf-8')

    if request.endpoint in current_app.config['breadcrumbs_map']:
        breadcrumbs = current_app.config['breadcrumbs_map'][request.endpoint]
    elif request.endpoint:
        breadcrumbs = [(_('Home'), '')
                       ] + current_app.config['breadcrumbs_map'].get(
                           request.endpoint.split('.')[0], [])
    else:
        breadcrumbs = [(_('Home'), '')]

    user = current_user._get_current_object()
    canonical_url, alternate_urls = get_canonical_and_alternates_urls(
        request.environ['PATH_INFO'])
    alternate_urls = dict((ln.replace('_', '-'), alternate_url)
                          for ln, alternate_url in alternate_urls.iteritems())

    guess_language()

    from invenio.bibfield import get_record  # should not be global due to bibfield_config
    return dict(_=lambda *args, **kwargs: g._(*args, **kwargs),
                current_user=user,
                get_css_bundle=current_app.jinja_env.get_css_bundle,
                get_js_bundle=current_app.jinja_env.get_js_bundle,
                is_language_rtl=is_language_rtl,
                canonical_url=canonical_url,
                alternate_urls=alternate_urls,
                get_record=get_record,
                url_for=invenio_url_for,
                breadcrumbs=breadcrumbs,
                **TEMPLATE_CONTEXT_FILTERS)
Exemplo n.º 17
0
 def get_title(self, **kwargs):
     return g._('Any Format')
Exemplo n.º 18
0
def send_email(fromaddr,
               toaddr,
               subject="",
               content="",
               html_content='',
               html_images=None,
               header=None,
               footer=None,
               html_header=None,
               html_footer=None,
               copy_to_admin=0,
               attempt_times=1,
               attempt_sleeptime=10,
               debug_level=0,
               ln=None,
               charset=None,
               replytoaddr="",
               attachments=None
               ):
    """Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly
    header and footer.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] header to add, None for the Default
    @param footer: [string] footer to add, None for the Default
    @param html_header: [string] header to add to the html part, None for the Default
    @param html_footer: [string] footer to add to the html part, None for the Default
    @param copy_to_admin: [int] if 1 add CFG_SITE_ADMIN_EMAIL in receivers
    @param attempt_times: [int] number of tries
    @param attempt_sleeptime: [int] seconds in between tries
    @param debug_level: [int] debug level
    @param ln: [string] invenio language
    @param charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)

    If sending fails, try to send it ATTEMPT_TIMES, and wait for
    ATTEMPT_SLEEPTIME seconds in between tries.

    e.g.:
    send_email('*****@*****.**', '*****@*****.**', 'Let\'s try!'', 'check 1234', '<strong>check</strong> <em>1234</em><img src="cid:image1">', {'image1': '/tmp/quantum.jpg'})

    @return: [bool]: True if email was sent okay, False if it was not.
    """
    from invenio.ext.logging import register_exception
    ln = default_ln(ln)

    if html_images is None:
        html_images = {}

    if type(toaddr) is not list:
        toaddr = toaddr.strip().split(',')

    toaddr = remove_temporary_emails(toaddr)

    usebcc = len(toaddr.split(',')) > 1  # More than one address, let's use Bcc in place of To

    if copy_to_admin:
        if cfg['CFG_SITE_ADMIN_EMAIL'] not in toaddr:
            toaddr.append(cfg['CFG_SITE_ADMIN_EMAIL'])

    body = forge_email(fromaddr, toaddr, subject, content, html_content,
                       html_images, usebcc, header, footer, html_header,
                       html_footer, ln, charset, replytoaddr, attachments)

    if attempt_times < 1 or not toaddr:
        try:
            raise EmailError(g._('The system is not attempting to send an email from %s, to %s, with body %s.') % (fromaddr, toaddr, body))
        except EmailError:
            register_exception()
        return False
    sent = False
    while not sent and attempt_times > 0:
        try:
            sent = body.send()
        except Exception:
            register_exception()
            if debug_level > 1:
                try:
                    raise EmailError(g._('Error in sending message. \
                        Waiting %(sec)s seconds. Exception is %(exc)s, \
                        while sending email from %(sender)s to %(receipient)s \
                        with body %(email_body)s.', \
                        sec = attempt_sleeptime, \
                        exc = sys.exc_info()[0], \
                        sender = fromaddr, \
                        receipient = toaddr, \
                        email_body = body))
                except EmailError:
                    register_exception()
        if not sent:
            attempt_times -= 1
            if attempt_times > 0:  # sleep only if we shall retry again
                sleep(attempt_sleeptime)
    if not sent:
        try:
            raise EmailError(g._('Error in sending email from %s to %s with body %s.') % (fromaddr, toaddr, body))
        except EmailError:
            register_exception()
    return sent
Exemplo n.º 19
0
def send_email(fromaddr,
               toaddr,
               subject="",
               content="",
               html_content='',
               html_images=None,
               header=None,
               footer=None,
               html_header=None,
               html_footer=None,
               copy_to_admin=0,
               attempt_times=1,
               attempt_sleeptime=10,
               debug_level=0,
               ln=None,
               charset=None,
               replytoaddr="",
               attachments=None,
               bccaddr="",
               forward_failures_to_admin=True,
               ):
    """Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly
    header and footer.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ','). BEWARE: If more than once receiptiant is given,
                   the receivers are put in BCC and To will be "Undisclosed.Recipients:".
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] header to add, None for the Default
    @param footer: [string] footer to add, None for the Default
    @param html_header: [string] header to add to the html part, None for the Default
    @param html_footer: [string] footer to add to the html part, None for the Default
    @param copy_to_admin: [int] if 1 add CFG_SITE_ADMIN_EMAIL in receivers
    @param attempt_times: [int] number of tries
    @param attempt_sleeptime: [int] seconds in between tries
    @param debug_level: [int] debug level
    @param ln: [string] invenio language
    @param charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)
    @param bccaddr: [string or list-of-strings] to be used for BCC header of the email
                    (if string, then receivers are separated by ',')
    @param forward_failures_to_admin: [bool] prevents infinite recursion
                                             in case of admin reporting,
                                             when the problem is not in
                                             the e-mail address format,
                                             but rather in the network

    If sending fails, try to send it ATTEMPT_TIMES, and wait for
    ATTEMPT_SLEEPTIME seconds in between tries.

    e.g.:
    send_email('*****@*****.**', '*****@*****.**', 'Let\'s try!'', 'check 1234', '<strong>check</strong> <em>1234</em><img src="cid:image1">', {'image1': '/tmp/quantum.jpg'})

    @return: [bool]: True if email was sent okay, False if it was not.
    """
    from invenio.ext.logging import register_exception
    ln = default_ln(ln)

    if html_images is None:
        html_images = {}

    if type(toaddr) is not list:
        toaddr = toaddr.strip().split(',')
    toaddr = remove_temporary_emails(toaddr)

    usebcc = len(toaddr) > 1  # More than one address, let's use Bcc in place of To

    if copy_to_admin:
        if cfg['CFG_SITE_ADMIN_EMAIL'] not in toaddr:
            toaddr.append(cfg['CFG_SITE_ADMIN_EMAIL'])

    if type(bccaddr) is not list:
        bccaddr = bccaddr.strip().split(',')

    body = forge_email(fromaddr, toaddr, subject, content, html_content,
                       html_images, usebcc, header, footer, html_header,
                       html_footer, ln, charset, replytoaddr, attachments,
                       bccaddr)

    if attempt_times < 1 or not toaddr:
        try:
            raise EmailError(g._(
                'The system is not attempting to send an email from %(x_from)s'
                ', to %(x_to)s, with body %(x_body)s.', x_from=fromaddr,
                x_to=toaddr, x_body=body))
        except EmailError:
            register_exception()
        return False
    sent = False
    failure_reason = ''
    while not sent and attempt_times > 0:
        try:
            sent = body.send()
        except Exception as e:
            failure_reason = str(e)
            register_exception()
            if debug_level > 1:
                try:
                    raise EmailError(g._('Error in sending message. \
                        Waiting %(sec)s seconds. Exception is %(exc)s, \
                        while sending email from %(sender)s to %(receipient)s \
                        with body %(email_body)s.', \
                        sec = attempt_sleeptime, \
                        exc = sys.exc_info()[0], \
                        sender = fromaddr, \
                        receipient = toaddr, \
                        email_body = body))
                except EmailError:
                    register_exception()
        if not sent:
            attempt_times -= 1
            if attempt_times > 0:  # sleep only if we shall retry again
                sleep(attempt_sleeptime)
    if not sent:
        # report failure to the admin with the intended message, its
        # sender and recipients
        if forward_failures_to_admin:
            # prepend '> ' to every line of the original message
            quoted_body = '> ' + '> '.join(body.splitlines(True))

            # define and fill in the report template
            admin_report_subject = g._('Error while sending an email: %(x_subject)s',
                                       x_subject=subject)
            admin_report_body = g._(
                "\nError while sending an email.\n"
                "Reason: %(x_reason)s\n"
                "Sender: \"%(x_sender)s\"\n"
                "Recipient(s): \"%(x_recipient)s\"\n\n"
                "The content of the mail was as follows:\n"
                "%(x_body)s",
                x_reason=failure_reason,
                x_sender=fromaddr,
                x_recipient=', '.join(toaddr),
                x_body=quoted_body)

            send_email(CFG_SITE_ADMIN_EMAIL, CFG_SITE_ADMIN_EMAIL,
                       admin_report_subject, admin_report_body,
                       forward_failures_to_admin=False)

        try:
            raise EmailError(g._(
                'Error in sending email from %(x_from)s to %(x_to)s with body'
                '%(x_body)s.', x_from=fromaddr, x_to=toaddr, x_body=body))
        except EmailError:
            register_exception()
    return sent
Exemplo n.º 20
0
 def get_title(self, **kwargs):
     """Return facet title."""
     return g._('Any ' + self.name.capitalize())
 def get_title(self, **kwargs):
     return g._('Any ' + self.name.capitalize())
Exemplo n.º 22
0
 def __init__(self):
     super(WebAccountSettings, self).__init__()
     self.icon = 'user'
     self.title = g._('Account')
     self.edit = url_for('accounts_settings.profile')