def widget(self):
        uid = current_user.get_id()
        baskets = []  #FIXME add loading baskets

        template = """
{{ _('You have') }}
<div class="btn-group">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
     <strong class="text-info">{{ baskets|length }}</strong>
     {{ _('personal baskets') }}
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
  {%- for b in baskets -%}
    <li>
        <a href="#">
            {{ b.name }}
        </a>
    </li>
  {%- endfor -%}
  </ul>
</div>"""

        return render_template_to_string(template,
                                         _from_string=True,
                                         baskets=baskets)
Example #2
0
    def test_simple_email_header(self):
        """
        Test simple email header.
        """
        from invenio.config import CFG_SITE_ADMIN_EMAIL
        from invenio.jinja2utils import render_template_to_string

        msg_content = """Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Subject
From: [email protected]
To: %s""" % (CFG_SITE_ADMIN_EMAIL, )

        msg = render_template_to_string('mail_text.tpl', content='Content')

        send_email('*****@*****.**', ['*****@*****.**'], subject='Subject',
                   content='Content')
        email = sys.stdout.getvalue()
        self.assertIn(msg_content, email)
        self.assertIn(self.ADMIN_MESSAGE, email)
        self.assertNotIn('Bcc:', email)
        self.assertIn(msg, email)
        self.flush_mailbox()

        send_email('*****@*****.**', '*****@*****.**', subject='Subject',
                   content='Content')
        email = sys.stdout.getvalue()
        self.assertIn(msg_content, email)
        self.assertIn(self.ADMIN_MESSAGE, email)
        self.assertNotIn('Bcc:', email)
        self.assertIn(msg, email)
        self.flush_mailbox()
Example #3
0
    def test_email_html_template(self):
        """
        Test email html template engine.
        """
        from invenio.jinja2utils import render_template_to_string

        contexts = {
            'ctx1': {'html_content': '<b>Content 1</b>'},
            'ctx2': {'html_content': '<b>Content 2</b>',
                     'html_header': '<h1>Header 2</h1>'},
            'ctx3': {'html_content': '<b>Content 3</b>',
                     'html_footer': '<i>Footer 3</i>'},
            'ctx4': {'html_content': '<b>Content 4</b>',
                     'html_header': '<h1>Header 4</h1>',
                     'html_footer': '<i>Footer 4</i>'}
        }

        def strip_html_key(ctx):
            return dict(map(lambda (k, v): (k[5:], v), ctx.iteritems()))

        for name, ctx in contexts.iteritems():
            msg = render_template_to_string('mail_html.tpl',
                                            **strip_html_key(ctx))
            send_email('*****@*****.**', ['*****@*****.**'], subject=name,
                       content='Content Text', **ctx)
            email = sys.stdout.getvalue()
            self.assertIn('Content-Type: multipart/alternative;', email)
            self.assertIn('Content Text', email)
            self.assertIn(msg, email)
            self.flush_mailbox()
Example #4
0
def format_element(bfo, template='bfe_files.html', show_subformat_icons='yes',
        focus_on_main_file='no', **kwargs):
    """
    This is the default format for formatting fulltext links.

    When possible, it returns only the main file(s) (+ link to
    additional files if needed). If no distinction is made at
    submission time between main and additional files, returns
    all the files
    """

    # Retrieve files
    (parsed_urls, old_versions, additionals) = get_files(bfo, \
        distinguish_main_and_additional_files=focus_on_main_file.lower() == 'yes',
        include_subformat_icons=show_subformat_icons == 'yes')

    ctx = {
        'recid': bfo.recID,
        'bfo': bfo,
        'others_urls': parsed_urls['others_urls'],
        'main_urls': parsed_urls['main_urls'],
    }

    kwargs.update(ctx)

    return render_template_to_string(template, **kwargs)
Example #5
0
    def test_email_text_template(self):
        """
        Test email text template engine.
        """
        from invenio.jinja2utils import render_template_to_string

        contexts = {
            'ctx1': {'content': 'Content 1'},
            'ctx2': {'content': 'Content 2', 'header': 'Header 2'},
            'ctx3': {'content': 'Content 3', 'footer': 'Footer 3'},
            'ctx4': {'content': 'Content 4', 'header': 'Header 4', 'footer': 'Footer 4'}
        }

        msg_content = """Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: %s
From: [email protected]
To: [email protected]"""

        for name, ctx in contexts.iteritems():
            msg = render_template_to_string('mail_text.tpl', **ctx)
            send_email('*****@*****.**', ['*****@*****.**'], subject=name,
                       **ctx)
            email = sys.stdout.getvalue()
            self.assertIn(msg_content % name, email)
            self.assertIn(msg, email)
            self.flush_mailbox()
Example #6
0
def openaire_upload_notification(recid):
    """
    Send a notification to all user collections.
    """
    ctx = {
        'record': get_record(recid),
    }

    ucolls = UserCollection.from_recid(recid, provisional=True)
    for c in ucolls:
        try:
            if c.owner.email:
                ctx.update({
                    'usercollection': c,
                })
                content = render_template_to_string(
                    "usercollection_new_upload_email.html", **ctx)
                send_email(CFG_SITE_SUPPORT_EMAIL,
                           c.owner.email.encode('utf8'),
                           "[%s] New upload to %s" %
                           (CFG_SITE_NAME, c.title.encode('utf8')),
                           content=content.encode('utf8'))
                logger.info("Sent email for new record %s to %s." %
                            (recid, c.owner.email.encode('utf8')))
        except AttributeError:
            pass
Example #7
0
    def tmpl_pagefooter(self, req, **kwargs):
        """Creates a page footer

           Parameters:

          - 'ln' *string* - The language to display

          - 'lastupdated' *string* - when the page was last updated

          - 'pagefooteradd' *string* - additional page footer HTML code

           Output:

          - HTML code of the page headers
        """
        ctx = dict(ln=CFG_SITE_LANG, lastupdated=None, pagefooteradd=None)
        ctx.update(kwargs)
        lastupdated = ctx.get('lastupdated')
        if lastupdated and lastupdated != '$Date$':
            if lastupdated.startswith("$Date: ") or lastupdated.startswith(
                    "$Id: "):
                ctx['lastupdated'] = convert_datecvs_to_datestruct(lastupdated)

        return render_template_to_string("legacy_page.html",
                                         no_pagebody=True,
                                         no_pageheader=True,
                                         **ctx).encode('utf8')
Example #8
0
    def widget(self):
        uid = current_user.get_id()
        query_baskets = UserQueryBasket.query.filter(
            UserQueryBasket.id_user == uid
            ).all()

        template = """
{{ _('You own the following') }}
<div class="btn-group">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
     <strong class="text-info">{{ query_baskets|length }}</strong>
     {{ _('alerts') }}
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
  {%- for a in query_baskets -%}
    <li>
        <a href="#">
            {{ a.alert_name }}
        </a>
    </li>
  {%- endfor -%}
  </ul>
</div>"""

        return render_template_to_string(template, _from_string=True,
                                         query_baskets=query_baskets)
Example #9
0
def format_element(bfo,
                   template='bfe_files.html',
                   show_subformat_icons='yes',
                   focus_on_main_file='no',
                   **kwargs):
    """
    This is the default format for formatting fulltext links.

    When possible, it returns only the main file(s) (+ link to
    additional files if needed). If no distinction is made at
    submission time between main and additional files, returns
    all the files
    """

    # Retrieve files
    (parsed_urls, old_versions, additionals) = get_files(bfo, \
        distinguish_main_and_additional_files=focus_on_main_file.lower() == 'yes',
        include_subformat_icons=show_subformat_icons == 'yes')

    ctx = {
        'recid': bfo.recID,
        'bfo': bfo,
        'others_urls': parsed_urls['others_urls'],
        'main_urls': parsed_urls['main_urls'],
    }

    kwargs.update(ctx)

    return render_template_to_string(template, **kwargs)
def template_context_function(recID):
    """
    Displays next-hit/previous-hit/back-to-search links
    on the detailed record pages in order to be able to quickly
    flip between detailed record pages
    @param recID: detailed record ID
    @type recID: string
    @return: html output
    """

    # this variable is set to zero so nothing is displayed
    if not CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT:
        return ""

    # search for a specific record having not done
    # any search before
    try:
        last_query = session['websearch-last-query']
        recids = session["websearch-last-query-hits"]
    except:
        return ""

    if recids and (int(recID) in recids):
        return render_template_to_string('record_back_to_search_links.html',
                                         recID=int(recID),
                                         last_query=CFG_SITE_URL + last_query,
                                         recids=recids)
    else:
        # did not rich the limit CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT,
        # so nothing is displayed
        return ""
def email_alert(mapper, connection, target):
    """ Sends email alerts to message recipients. """
    from invenio.jinja2utils import render_template_to_string
    from invenio.mailutils import send_email, scheduled_send_email
    m = target
    is_reminder =  m.received_date is not None \
                   and m.received_date > datetime.now()

    alert = send_email
    if is_reminder:
        alert = lambda *args, **kwargs: scheduled_send_email(
            *args,
            other_bibtasklet_arguments=
            [m.received_date.strftime(datetext_format)],
            **kwargs)

    for u in m.recipients:
        if isinstance(u.settings, dict) and \
            u.settings.get('webmessage_email_alert', True):
            try:
                alert(CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL,
                      u.email,
                      subject=m.subject,
                      content=render_template_to_string(
                          'webmessage_email_alert.html', message=m, user=u))
            except:
                # FIXME tests are not in request context
                pass
    def widget(self):
        user = User.query.get(current_user.get_id())
        email = user.email
        email_field = "8560_"
        deposit_count = len(perform_request_search(f=email_field, p=email, of="id"))

        return render_template_to_string('deposits_user_settings.html',
            email=email, email_field=email_field, deposit_count=deposit_count)
Example #13
0
    def render_portalbox_bodies(self, templates):
        """
        Get a list of rendered portal boxes for this user collection
        """
        ctx = {
            'usercollection': self,
        }

        return map(lambda t: render_template_to_string(t, **ctx), templates)
Example #14
0
def format_element(bfo, template='record_hb.html', **kwargs):
    #bfo.field('0247_a')

    ctx = {
        'recid': bfo.recID,
        'bfo': bfo,
    }
    kwargs.update(ctx)

    return render_template_to_string(template, **kwargs)
Example #15
0
def plupload_widget(field, **kwargs):
    field_id = kwargs.pop('id', field.id)
    kwargs['class'] = u'plupload'

    return HTMLString(
        render_template_to_string(
            "webdeposit_widget_plupload.html",
            field=field,
            field_id=field_id,
        ))
    def widget(self):
        user = User.query.get(current_user.get_id())
        tag_count = user.tags_query.count()

        record_count = Bibrec.query.join(WtgTAGRecord).join(WtgTAG)\
                       .filter(WtgTAG.user == user).count()

        return render_template_to_string('webtag_user_settings.html',
            tag_count=tag_count,
            record_count=record_count)
Example #17
0
    def render_portalbox_bodies(self, templates):
        """
        Get a list of rendered portal boxes for this user collection
        """
        ctx = {
            'usercollection': self,
        }

        return map(
            lambda t: render_template_to_string(t, **ctx),
            templates
        )
Example #18
0
    def widget(self):
        uid = current_user.get_id()
        queries = db.session.query(db.func.count(
            UserQuery.id_query)).filter(UserQuery.id_user == uid).scalar()

        template = """
{{ _('You have made %d queries. A detailed list is available with a possibility to
(a) view search results and (b) subscribe to an automatic email alerting service
for these queries.') | format(queries) }}
"""

        return render_template_to_string(template,
                                         _from_string=True,
                                         queries=queries)
Example #19
0
    def tmpl_navtrailbox_body(self, ln, title, previous_links, separator,
                              prolog, epilog):
        """Bootstrap friendly-Create navigation trail box body

           Parameters:

          - 'ln' *string* - The language to display

          - 'title' *string* - page title;

          - 'previous_links' *string* - the trail content from site title until current page (both ends exclusive)

          - 'prolog' *string* - HTML code to prefix the navtrail item with

          - 'epilog' *string* - HTML code to suffix the navtrail item with

          - 'separator' *string* - HTML code that separates two navtrail items

           Output:

          - text containing the navtrail

           Note: returns empty string for Home page. (guessed by title).
        """

        # load the right message language
        _ = gettext_set_language(ln)

        if title == CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME):
            return ""

        # First element
        breadcrumbs = [
            (_("Home"), CFG_SITE_URL),
        ]

        # Decode previous elements
        if previous_links:
            soup = BeautifulSoup(previous_links)
            for link in soup.find_all('a'):
                breadcrumbs.append(
                    (unicode(" ".join(link.contents)), link.get('href')))

        # Add head
        if title:
            breadcrumbs.append((title, ''))

        return render_template_to_string(
            "breadcrumbs.html", breadcrumbs=breadcrumbs).encode('utf8')
Example #20
0
    def open_tag(self, subfield, **kwargs):
        if self.html_tag:
            if subfield.name.endswith('__input__'):
                return '<%s>' % self.html_tag
            else:
                ctx = {}
                if (isinstance(subfield.data, basestring)):
                    ctx['value'] = subfield.data
                elif subfield.data:
                    ctx.update(subfield.data)

                return '<%s %s><button type="button" class="close remove-element" data-dismiss="alert">&times;</button><span class="tag-title">%s</span>' % (
                    self.html_tag,
                    html_params(class_=self.class_ + ' ' +
                                kwargs.get('class_', '')),
                    render_template_to_string(
                        self.template, _from_string=True, **ctx))
        return ''
Example #21
0
def print_records(recIDs,
                  of='hb',
                  ln=CFG_SITE_LANG,
                  verbose=0,
                  search_pattern='',
                  on_the_fly=False,
                  **ctx):
    """
    Returns records using Jinja template.
    """
    import time
    from math import ceil
    from flask import request
    from invenio.bibformat_engine import format_record
    from invenio.websearch_model import Format
    from invenio.paginationutils import Pagination
    from invenio.bibformat_engine import TEMPLATE_CONTEXT_FUNCTIONS_CACHE

    of = of.lower()
    jrec = request.values.get('jrec', ctx.get('jrec', 1), type=int)
    rg = request.values.get('rg', ctx.get('rg', 10), type=int)
    ln = wash_language(request.values.get('ln', ln))
    pages = int(ceil(jrec / float(rg))) if rg > 0 else 1

    context = dict(
        of=of,
        jrec=jrec,
        rg=rg,
        ln=ln,
        facets={},
        time=time,
        recids=recIDs,
        pagination=Pagination(pages, rg, ctx.get('records', len(recIDs))),
        verbose=verbose,
        export_formats=Format.get_export_formats(),
        format_record=format_record,
        **TEMPLATE_CONTEXT_FUNCTIONS_CACHE.template_context_functions)
    context.update(ctx)
    return render_template_to_string([
        'format_records_%s.tpl' % of,
        'format_records_%s.tpl' % of[0],
        'format_records_%s.tpl' %
        get_output_format_content_type(of).replace('/', '_')
    ], **context)
Example #22
0
def template_context_function(id_bibrec, id_user):
    """
    @param id_bibrec ID of record
    @param id_user user viewing the record (and owning the displayed tags)
    @return HTML containing tag list
    """

    if id_user and id_bibrec:
        tags = WtgTAG.query\
           .join(WtgTAGRecord)\
           .filter(WtgTAG.id_user==id_user,
                   WtgTAGRecord.id_bibrec == id_bibrec)\
           .order_by(WtgTAG.name)\
           .all()
        return render_template_to_string('webtag_record.html',
                                         id_bibrec=id_bibrec,
                                         record_tags=tags)
    else:
        return None
Example #23
0
def print_records(recIDs,
                  of='hb',
                  ln=CFG_SITE_LANG,
                  verbose=0,
                  search_pattern='',
                  on_the_fly=False,
                  **ctx):
    """
    Returns records using Jinja template.
    """
    import time
    from math import ceil
    from flask import request
    from invenio.search_engine import print_record
    from invenio.websearch_model import Format
    from invenio.paginationutils import Pagination

    of = request.values.get('of', str(of)).lower()
    rg = request.values.get('rg', ctx.get('rg', 10), type=int)
    ln = request.values.get('ln', ln)
    page = request.values.get('jrec', 1, type=int)
    pages = int(ceil(page / float(rg))) if rg > 0 else 1

    context = dict(of=of,
                   rg=rg,
                   ln=ln,
                   facets={},
                   time=time,
                   recids=recIDs,
                   pagination=Pagination(pages, rg,
                                         ctx.get('records', len(recIDs))),
                   verbose=verbose,
                   export_formats=Format.get_export_formats(),
                   format_record=print_record)
    context.update(ctx)

    return render_template_to_string([
        'format_records_%s.tpl' % of,
        'format_records_%s.tpl' % of[0],
        'format_records_%s.tpl' %
        get_output_format_content_type(of).replace('/', '_')
    ], **context)
 def large_file_notification(sender, deposition=None, deposition_file=None,
                             **kwargs):
     if deposition_file and deposition_file.size > 10485760:
         from invenio.mailutils import send_email
         from invenio.config import CFG_SITE_ADMIN_EMAIL, CFG_SITE_NAME
         from invenio.textutils import nice_size
         from invenio.jinja2utils import render_template_to_string
         current_app.logger.info(deposition_file.__getstate__())
         send_email(
             CFG_SITE_ADMIN_EMAIL,
             CFG_SITE_ADMIN_EMAIL,
             subject="%s: %s file uploaded" % (
                 CFG_SITE_NAME, nice_size(deposition_file.size)
             ),
             content=render_template_to_string(
                 "email_large_file.html",
                 deposition=deposition,
                 deposition_file=deposition_file,
             )
         )
    def widget(self):
        uid = current_user.get_id()
        unread = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
            filter(db.and_(
                UserMsgMESSAGE.id_user_to == uid,
                UserMsgMESSAGE.status == CFG_WEBMESSAGE_STATUS_CODE['NEW']
            )).scalar()

        total = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
            filter(
                UserMsgMESSAGE.id_user_to == uid
            ).scalar()

        template = """
{{  _("You have %d new messages out of %d messages.") | format(unread, total) }}
"""
        return render_template_to_string(template,
                                         _from_string=True,
                                         unread=unread,
                                         total=total)
Example #26
0
def openaire_upload_notification(recid):
    """
    Send a notification to all user collections.
    """
    ctx = {
        'record': get_record(recid),
    }

    ucolls = UserCollection.from_recid(recid, provisional=True)
    for c in ucolls:
        try:
            if c.owner.email:
                ctx.update({
                    'usercollection': c,
                })
                content = render_template_to_string("usercollection_new_upload_email.html", **ctx)
                send_email(CFG_SITE_SUPPORT_EMAIL, c.owner.email.encode('utf8'), "[%s] New upload to %s" % (CFG_SITE_NAME, c.title.encode('utf8')), content=content.encode('utf8'))
                logger.info("Sent email for new record %s to %s." % (recid, c.owner.email.encode('utf8')))
        except AttributeError:
            pass
    def widget(self):
        uid = current_user.get_id()

        baskets = []

        if(uid is not None and uid != 0):
            # list of tuples: (bskid, bsk_name, topic)
            bsk_from_db = get_all_personal_baskets_names(uid)

            baskets = [{'name': name, 'bskid': bskid}
                       for (bskid, name, dummy_topic) in bsk_from_db]

        template = """
{{ _('You have') }}
<div class="btn-group">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
     <strong class="text-info">{{ baskets|length }}</strong>
     {{ _('personal baskets') }}
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
  {%- for b in baskets -%}
    <li>
        <a href="/yourbaskets/display?bskid={{ b.bskid }}">
            {{ b.name }}
        </a>
    </li>
  {%- endfor -%}
  </ul>
</div>"""

        # If the list is too long ( >= 2 items! ),
        # it will not be properlt displayed
        # (it appears that the list cannot be displayed outside the
        #  box, so the rest is cut off)

        return render_template_to_string(template, _from_string=True,
                                         baskets=baskets)
Example #28
0
    def widget(self):
        uid = current_user.get_id()
        usergroups = UserUsergroup.query.filter(
            UserUsergroup.id_user == uid).all()

        template = """
{%- if usergroups -%}
{{ _('You are involved in following groups:') }}
<div>
  {%- for ug in usergroups -%}
  <span class="label">
    {{ ug.usergroup.name }}
  </span>
  {%- endfor -%}
</div>
{%- else -%}
{{ _('You are not involved in any group.') }}
{%- endif -%}
"""

        rv = render_template_to_string(template,
                                       _from_string=True,
                                       usergroups=usergroups)
        return rv
    def widget(self):
        template = """
{{  _("You are logged in as %s") | format(current_user.nickname) }}
"""
        return render_template_to_string(template, _from_string=True)
Example #30
0
def forge_email(fromaddr,
                toaddr,
                subject,
                content,
                html_content='',
                html_images=None,
                usebcc=False,
                header=None,
                footer=None,
                html_header=None,
                html_footer=None,
                ln=CFG_SITE_LANG,
                charset=None,
                replytoaddr="",
                attachments=None):
    """Prepare email. Add header and footer if needed.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param usebcc: [bool] True for using Bcc in place of To
    @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] None for the default header
    @param footer: [string] None for the default footer
    @param ln: language
    @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)
    @return: forged email as a string"""
    if html_images is None:
        html_images = {}

    content = render_template_to_string('mail_text.tpl',
                                        content=content,
                                        header=header,
                                        footer=footer)

    if type(toaddr) is not str:
        toaddr = ','.join(toaddr)

    if type(replytoaddr) is not str:
        replytoaddr = ','.join(replytoaddr)

    toaddr = remove_temporary_emails(toaddr)

    headers = {}
    kwargs = {'to': [], 'cc': [], 'bcc': []}

    if replytoaddr:
        headers['Reply-To'] = replytoaddr
    if usebcc:
        headers['Bcc'] = toaddr
        kwargs['bcc'] = toaddr.split(',')
        kwargs['to'] = ['Undisclosed.Recipients:']
    else:
        kwargs['to'] = toaddr.split(',')
    headers['From'] = fromaddr
    headers['Date'] = formatdate(localtime=True)
    headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL)

    if html_content:
        html_content = render_template_to_string('mail_html.tpl',
                                                 content=html_content,
                                                 header=html_header,
                                                 footer=html_footer)

        msg_root = EmailMultiAlternatives(subject=subject,
                                          body=content,
                                          from_email=fromaddr,
                                          headers=headers,
                                          **kwargs)
        msg_root.attach_alternative(html_content, "text/html")

        #if not html_images:
        #    # No image? Attach the HTML to the root
        #    msg_root.attach(msg_text)
        #else:
        if html_images:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            #msg_related.attach(msg_text)
            for image_id, image_path in html_images.iteritems():
                attach_embed_image(msg_related, image_id, image_path)
            msg_root.attach(msg_related)
    else:
        msg_root = EmailMessage(subject=subject,
                                body=content,
                                from_email=fromaddr,
                                headers=headers,
                                **kwargs)

    if attachments:
        from invenio.bibdocfile import _mimes, guess_format_from_url
        #old_msg_root = msg_root
        #msg_root = MIMEMultipart()
        #msg_root.attach(old_msg_root)
        for attachment in attachments:
            try:
                mime = None
                if type(attachment) in (list, tuple):
                    attachment, mime = attachment
                if mime is None:
                    ## Automatic guessing of mimetype
                    mime = _mimes.guess_type(attachment)[0]
                if mime is None:
                    ext = guess_format_from_url(attachment)
                    mime = _mimes.guess_type("foo" + ext)[0]
                if not mime:
                    mime = 'application/octet-stream'
                part = MIMEBase(*mime.split('/', 1))
                part.set_payload(open(attachment, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attachment))
                msg_root.attach(part)
            except:
                register_exception(alert_admin=True,
                                   prefix="Can't attach %s" % attachment)

    return msg_root
Example #31
0
def create_config(force=False, no_ssl=True):
    """
    Create Apache configuration files for this site, keeping previous
    files in a backup copy.
    """
    import os
    import pwd
    import sys
    import shutil
    from flask import current_app
    from jinja2 import TemplateNotFound
    from invenio.jinja2utils import render_template_to_string
    from invenio.textutils import wrap_text_in_a_box
    from invenio.access_control_config import CFG_EXTERNAL_AUTH_USING_SSO

    CFG_PREFIX = current_app.config.get('CFG_PREFIX', '')

    def get_context():
        from invenio.inveniocfg import _detect_ip_address

        conf = current_app.config

        ## Apache vhost conf file is distro specific, so analyze needs:
        # Gentoo (and generic defaults):
        listen_directive_needed = True
        ssl_pem_directive_needed = False
        ssl_pem_path = CFG_PREFIX + '/etc/apache/ssl/apache.pem'
        ssl_crt_path = CFG_PREFIX + '/etc/apache/ssl/server.crt'
        ssl_key_path = CFG_PREFIX + '/etc/apache/ssl/server.key'
        vhost_ip_address_needed = False
        wsgi_socket_directive_needed = False
        # Debian:
        if os.path.exists(os.path.sep + 'etc' + os.path.sep +
                          'debian_version'):
            listen_directive_needed = False
            ssl_pem_directive_needed = True
            ssl_pem_path = '/etc/apache2/ssl/apache.pem'
            ssl_crt_path = '/etc/apache2/ssl/server.crt'
            ssl_key_path = '/etc/apache2/ssl/server.key'
        # RHEL/SLC:
        if os.path.exists(os.path.sep + 'etc' + os.path.sep +
                          'redhat-release'):
            listen_directive_needed = False
            ssl_crt_path = '/etc/pki/tls/certs/localhost.crt'
            ssl_key_path = '/etc/pki/tls/private/localhost.key'
            vhost_ip_address_needed = True
            wsgi_socket_directive_needed = True
        # maybe we are using non-standard ports?
        vhost_site_url = conf.get('CFG_SITE_URL').replace("http://", "")
        if vhost_site_url.startswith("https://"):
            ## The installation is configured to require HTTPS for any connection
            vhost_site_url = vhost_site_url.replace("https://", "")
        vhost_site_url_port = '80'
        vhost_site_secure_url = conf.get('CFG_SITE_SECURE_URL').replace(
            "https://", "").replace("http://", "")
        vhost_site_secure_url_port = '443'
        if ':' in vhost_site_url:
            vhost_site_url, vhost_site_url_port = vhost_site_url.split(':', 1)
        if ':' in vhost_site_secure_url:
            vhost_site_secure_url, vhost_site_secure_url_port = vhost_site_secure_url.split(
                ':', 1)
        if vhost_site_url_port != '80' or vhost_site_secure_url_port != '443':
            listen_directive_needed = True

        apc1 = {
            'vhost_site_url_port':
            vhost_site_url_port,
            'servername':
            vhost_site_url,
            'serveralias':
            vhost_site_url.split('.')[0],
            'vhost_ip_address':
            vhost_ip_address_needed and _detect_ip_address() or '*',
            'wsgi_socket_directive_needed':
            wsgi_socket_directive_needed,
            'listen_directive_needed':
            listen_directive_needed,
        }

        apc2 = {
            'vhost_site_url_port':
            vhost_site_secure_url_port,
            'servername':
            vhost_site_secure_url,
            'serveralias':
            vhost_site_secure_url.split('.')[0],
            'vhost_ip_address':
            vhost_ip_address_needed and _detect_ip_address() or '*',
            'wsgi_socket_directive_needed':
            wsgi_socket_directive_needed,
            'ssl_pem_directive':
            ssl_pem_directive_needed and 'SSLCertificateFile %s' % ssl_pem_path
            or '#SSLCertificateFile %s' % ssl_pem_path,
            'ssl_crt_directive':
            ssl_pem_directive_needed
            and '#SSLCertificateFile %s' % ssl_crt_path
            or 'SSLCertificateFile %s' % ssl_crt_path,
            'ssl_key_directive':
            ssl_pem_directive_needed
            and '#SSLCertificateKeyFile %s' % ssl_key_path
            or 'SSLCertificateKeyFile %s' % ssl_key_path,
            'listen_directive_needed':
            listen_directive_needed,
        }

        return [apc1, apc2]

    current_app.config.update(
        CFG_RUNNING_AS_USER=pwd.getpwuid(os.getuid())[0],
        CFG_EXTERNAL_AUTH_USING_SSO=CFG_EXTERNAL_AUTH_USING_SSO,
        CFG_WSGIDIR=os.path.join(CFG_PREFIX, 'var', 'www-wsgi'))

    apache_conf_dir = current_app.config.get('CFG_ETCDIR') + os.sep + 'apache'

    print ">>> Going to create Apache conf files..."
    conf_files = ['invenio-apache-vhost.conf', 'invenio-apache-vhost-ssl.conf']
    conf_files = conf_files[:1 if no_ssl else 2]

    if not os.path.exists(apache_conf_dir):
        os.mkdir(apache_conf_dir)

    for local_file, context in zip(conf_files,
                                   get_context()[:1 if no_ssl else 2]):
        print ">>> Writing %s ..." % local_file

        try:
            apache_vhost_file = apache_conf_dir + os.sep + local_file
            if os.path.exists(apache_vhost_file):
                shutil.copy(apache_vhost_file, apache_vhost_file + '.OLD')

            with open(apache_vhost_file, 'w') as f:
                out = render_template_to_string(local_file + '.tpl',
                                                os=os,
                                                **context)
                print >> f, out

        except TemplateNotFound:
            print >> sys.stderr, "Could not find template %s" % local_file

    print wrap_text_in_a_box("""\
Apache virtual host configuration file(s) for your Invenio site
was(were) created.  Please check created file(s) and activate virtual
host(s).  For example, you can put the following include statements in
your httpd.conf:\n

%s

%s


Please see the INSTALL file for more details.
    """ % tuple(
        map(
            lambda x: "Include " + apache_conf_dir.encode('utf-8') + os.sep +
            x, list(conf_files))))
    print ">>> Apache conf files created."
Example #32
0
 def tplEqualToString(self, tpl, text, **ctx):
     self.assertEqual(
         render_template_to_string(tpl, _from_string=True, **ctx),
         text)
Example #33
0
    def tmpl_pageheader(self, req, **kwargs):
        """Creates a page header

           Parameters:

          - 'ln' *string* - The language to display

          - 'headertitle' *string* - the title of the HTML page, not yet escaped for HTML

          - 'description' *string* - description goes to the metadata in the header of the HTML page,
                                     not yet escaped for HTML

          - 'keywords' *string* - keywords goes to the metadata in the header of the HTML page,
                                  not yet escaped for HTML

          - 'userinfobox' *string* - the HTML code for the user information box

          - 'useractivities_menu' *string* - the HTML code for the user activities menu

          - 'adminactivities_menu' *string* - the HTML code for the admin activities menu

          - 'navtrailbox' *string* - the HTML code for the navigation trail box

          - 'pageheaderadd' *string* - additional page header HTML code

          - 'uid' *int* - user ID

          - 'secure_page_p' *int* (0 or 1) - are we to use HTTPS friendly page elements or not?

          - 'navmenuid' *string* - the id of the navigation item to highlight for this page

          - 'metaheaderadd' *string* - list of further tags to add to the <HEAD></HEAD> part of the page

          - 'rssurl' *string* - the url of the RSS feed for this page

          - 'body_css_classes' *list* - list of classes to add to the body tag

           Output:

          - HTML code of the page headers
        """

        ctx = dict(ln=CFG_SITE_LANG,
                   headertitle="",
                   description="",
                   keywords="",
                   userinfobox="",
                   useractivities_menu="",
                   adminactivities_menu="",
                   navtrailbox="",
                   pageheaderadd="",
                   uid=0,
                   secure_page_p=0,
                   navmenuid="admin",
                   metaheaderadd="",
                   rssurl=CFG_SITE_URL + "/rss",
                   body_css_classes=None)
        ctx.update(kwargs)
        if ctx['body_css_classes'] is None:
            ctx['body_css_classes'] = [ctx.get('navmenuid', '')]
        else:
            ctx['body_css_classes'].append([ctx.get('navmenuid', '')])

        return render_template_to_string("legacy_page.html",
                                         no_pagebody=True,
                                         no_pagefooter=True,
                                         **ctx).encode('utf8')
Example #34
0
    def tmpl_page(self, req, **kwargs):
        """Creates a complete page

           Parameters:

          - 'ln' *string* - The language to display

          - 'description' *string* - description goes to the metadata in the header of the HTML page,
                                     not yet escaped for HTML

          - 'keywords' *string* - keywords goes to the metadata in the header of the HTML page,
                                  not yet escaped for HTML

          - 'userinfobox' *string* - the HTML code for the user information box

          - 'useractivities_menu' *string* - the HTML code for the user activities menu

          - 'adminactivities_menu' *string* - the HTML code for the admin activities menu

          - 'navtrailbox' *string* - the HTML code for the navigation trail box

          - 'pageheaderadd' *string* - additional page header HTML code

          - 'boxlefttop' *string* - left-top box HTML code

          - 'boxlefttopadd' *string* - additional left-top box HTML code

          - 'boxleftbottom' *string* - left-bottom box HTML code

          - 'boxleftbottomadd' *string* - additional left-bottom box HTML code

          - 'boxrighttop' *string* - right-top box HTML code

          - 'boxrighttopadd' *string* - additional right-top box HTML code

          - 'boxrightbottom' *string* - right-bottom box HTML code

          - 'boxrightbottomadd' *string* - additional right-bottom box HTML code

          - 'title' *string* - the title of the page, not yet escaped for HTML

          - 'titleprologue' *string* - what to print before page title

          - 'titleepilogue' *string* - what to print after page title

          - 'body' *string* - the body of the page

          - 'lastupdated' *string* - when the page was last updated

          - 'uid' *int* - user ID

          - 'pagefooteradd' *string* - additional page footer HTML code

          - 'secure_page_p' *int* (0 or 1) - are we to use HTTPS friendly page elements or not?

          - 'navmenuid' *string* - the id of the navigation item to highlight for this page

          - 'metaheaderadd' *string* - list of further tags to add to the <HEAD></HEAD> part of the page

          - 'rssurl' *string* - the url of the RSS feed for this page

          - 'show_title_p' *int* (0 or 1) - do we display the page title in the body of the page?

          - 'body_css_classes' *list* - list of classes to add to the body tag

          - 'show_header' *boolean* - tells whether page header should be displayed or not

          - 'show_footer' *boolean* - tells whether page footer should be displayed or not

           Output:

          - HTML code of the page
        """

        ctx = dict(ln=CFG_SITE_LANG,
                   description="",
                   keywords="",
                   userinfobox="",
                   useractivities_menu="",
                   adminactivities_menu="",
                   navtrailbox="",
                   pageheaderadd="",
                   boxlefttop="",
                   boxlefttopadd="",
                   boxleftbottom="",
                   boxleftbottomadd="",
                   boxrighttop="",
                   boxrighttopadd="",
                   boxrightbottom="",
                   boxrightbottomadd="",
                   titleprologue="",
                   title="",
                   titleepilogue="",
                   body="",
                   lastupdated=None,
                   pagefooteradd="",
                   uid=0,
                   secure_page_p=0,
                   navmenuid="",
                   metaheaderadd="",
                   rssurl=CFG_SITE_URL + "/rss",
                   show_title_p=True,
                   body_css_classes=None,
                   show_header=True,
                   show_footer=True)
        ctx.update(kwargs)
        return render_template_to_string("legacy_page.html",
                                         **ctx).encode('utf8')