Exemple #1
0
def _delete_torrent(torrent, form, banform):
    editor = flask.g.user
    uploader = torrent.user

    # Only allow admins edit deleted torrents
    if torrent.deleted and not (editor and editor.is_moderator):
        flask.abort(404)

    action = None
    url = flask.url_for('main.home')

    ban_torrent = form.ban.data
    if banform:
        ban_torrent = ban_torrent or banform.ban_user.data or banform.ban_userip.data

    if form.delete.data and not torrent.deleted:
        action = 'deleted'
        torrent.deleted = True
        db.session.add(torrent)

    elif ban_torrent and not torrent.banned and editor.is_moderator:
        action = 'banned'
        torrent.banned = True
        if not torrent.deleted:
            torrent.deleted = True
            action = 'deleted and banned'
        backend.tracker_api([torrent.info_hash], 'ban')
        db.session.add(torrent)

    elif form.undelete.data and torrent.deleted:
        action = 'undeleted'
        torrent.deleted = False
        if torrent.banned:
            action = 'undeleted and unbanned'
            torrent.banned = False
            backend.tracker_api([torrent.info_hash], 'unban')
        db.session.add(torrent)

    elif form.unban.data and torrent.banned:
        action = 'unbanned'
        torrent.banned = False
        backend.tracker_api([torrent.info_hash], 'unban')
        db.session.add(torrent)

    if not action and not ban_torrent:
        flask.flash(flask.Markup('What the f**k are you doing?'), 'danger')
        return flask.redirect(
            flask.url_for('torrents.edit', torrent_id=torrent.id))

    if action and editor.is_moderator:
        url = flask.url_for('torrents.view', torrent_id=torrent.id)
        if editor is not uploader:
            log = "Torrent [#{0}]({1}) has been {2}".format(
                torrent.id, url, action)
            adminlog = models.AdminLog(log=log, admin_id=editor.id)
            db.session.add(adminlog)

    if action:
        db.session.commit()
        flask.flash(
            flask.Markup('Torrent has been successfully {0}.'.format(action)),
            'success')

    if not banform or not (banform.ban_user.data or banform.ban_userip.data):
        return flask.redirect(url)

    if banform.ban_userip.data:
        tbanned = models.Ban.banned(None, torrent.uploader_ip).first()
        ubanned = True
        if uploader:
            ubanned = models.Ban.banned(None, uploader.last_login_ip).first()
        ipbanned = (tbanned and ubanned)

    if (banform.ban_user.data and (not uploader or uploader.is_banned)) or \
            (banform.ban_userip.data and ipbanned):
        flask.flash(flask.Markup('What the f**k are you doing?'), 'danger')
        return flask.redirect(
            flask.url_for('torrents.edit', torrent_id=torrent.id))

    flavor = "Nyaa" if app.config['SITE_FLAVOR'] == 'nyaa' else "Sukebei"
    eurl = flask.url_for('torrents.view',
                         torrent_id=torrent.id,
                         _external=True)
    reason = "[{0}#{1}]({2}) {3}".format(flavor, torrent.id, eurl,
                                         banform.reason.data)
    ban1 = models.Ban(admin_id=editor.id, reason=reason)
    ban2 = models.Ban(admin_id=editor.id, reason=reason)
    db.session.add(ban1)

    if uploader:
        uploader.status = models.UserStatusType.BANNED
        db.session.add(uploader)
        ban1.user_id = uploader.id
        ban2.user_id = uploader.id

    if banform.ban_userip.data:
        if not ubanned:
            ban1.user_ip = ip_address(uploader.last_login_ip)
            if not tbanned:
                uploader_ip = ip_address(torrent.uploader_ip)
                if ban1.user_ip != uploader_ip:
                    ban2.user_ip = uploader_ip
                    db.session.add(ban2)
        else:
            ban1.user_ip = ip_address(torrent.uploader_ip)

    uploader_str = "Anonymous"
    if uploader:
        uploader_url = flask.url_for('users.view_user',
                                     user_name=uploader.username)
        uploader_str = "[{0}]({1})".format(uploader.username, uploader_url)
    if ban1.user_ip:
        uploader_str += " IP({0})".format(ban1.user_ip)
        ban1.user_ip = ban1.user_ip.packed
    if ban2.user_ip:
        uploader_str += " IP({0})".format(ban2.user_ip)
        ban2.user_ip = ban2.user_ip.packed

    log = "Uploader {0} of torrent [#{1}]({2}) has been banned.".format(
        uploader_str, torrent.id,
        flask.url_for('torrents.view', torrent_id=torrent.id), action)
    adminlog = models.AdminLog(log=log, admin_id=editor.id)
    db.session.add(adminlog)

    db.session.commit()

    flask.flash(flask.Markup('Uploader has been successfully banned.'),
                'success')

    return flask.redirect(url)
Exemple #2
0
 def index():
     return flask.render_template('escaping_template.html',
                                  text=text,
                                  html=flask.Markup(text))
Exemple #3
0
 def index():
     flask.flash(u'Hello World')
     flask.flash(u'Hello World', 'error')
     flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')
     return ''
Exemple #4
0
def number_field_data(label):
    return flask.Markup(nf_knowl_guts(label, db()))
Exemple #5
0
 def modify_session(response):
     flask.session['m'] = flask.Markup('Hello!')
     flask.session['u'] = the_uuid
     flask.session['dt'] = now
     flask.session['t'] = (1, 2, 3)
     return response
Exemple #6
0
		for algorithm improvements on get_data()
	Rodrigo Serrão [https://github.com/RojerGS]:
		for exec(templates)
"""

import flask
import os
import time
from random import choice
from math import ceil

pineblog = flask.Flask(__name__)
pineblog.jinja_env.trim_blocks = True
pineblog.jinja_env.lstrip_blocks = True
# http://stackoverflow.com/questions/9767585/insert-static-files-literally-into-jinja-templates-without-parsing-them
pineblog.jinja_env.globals['include_raw'] = lambda filename: flask.Markup(
    pineblog.jinja_loader.get_source(pineblog.jinja_env, filename)[0])

# Constants
posts_per_page = 3

# Globals
data = []
number_of_pages = None


def log(message):
    with open('log', 'a') as logfile:
        epoch = str(time.time())
        microseconds = epoch.split('.')[-1]  # extra resolution for seconds
        logtime = time.strftime('[%d/%m/%Y %H:%M:%S.{0}]'.format(microseconds))
        logfile.write('{0} {1}\n'.format(logtime, message))
Exemple #7
0
def group_cclasses_data(n, t):
    return flask.Markup(group_cclasses_knowl_guts(n, t, db()))
Exemple #8
0
def _preprocess_variables(config, strings):
    in_page_link = flask.Markup('<a target="_blank" href=%s>%s</a>')
    strings['in_page'] = \
        flask.Markup(strings['in_page']) % in_page_link

    if config.lead_section_policy_link:
        lead_section_policy_link = flask.Markup(
            '<a target="_blank" href=%s>%s</a>') % (
                config.lead_section_policy_link,
                config.lead_section_policy_link_title)
        strings['lead_section_hint'] = \
            flask.Markup(strings['lead_section_hint']) % \
            lead_section_policy_link
    else:
        strings['lead_section_hint'] = ''

    beginners_hint_link = flask.Markup('<a target="_blank" href=%s>%s</a>') % (
        config.beginners_link, config.beginners_link_title)
    strings['beginners_hint'] = \
        flask.Markup(strings['beginners_hint']) % beginners_hint_link

    if '404' not in config.flagged_off:
        page_not_found_link = flask.Markup('<a href=%s>Citation Hunt</a>') % (
            config.lang_code)
        strings['page_not_found_text'] = \
            flask.Markup(strings['page_not_found_text']) % page_not_found_link

    strings.setdefault('instructions_goal', '')
    strings.setdefault('instructions_details', '')
    if strings['instructions_details']:
        strings['instructions_details'] = flask.Markup(
            strings['instructions_details']) % (
                flask.Markup('<b>' + strings['button_wikilink'] + '</b>'),
                flask.Markup('<b>' + strings['button_next'] + '</b>'),
                beginners_hint_link)
    return strings
Exemple #9
0
 def _get_charts_markup(self):
     return {n: flask.Markup(c.html()) for n, c in self.charts.items()}
Exemple #10
0
def test():
    ts = TAINTED_STRING

    # class `Markup` can be used for things that are already safe.
    # if used with any text in a string operation, that other text will be escaped.
    #
    # see https://markupsafe.palletsprojects.com/en/2.0.x/
    m_unsafe = Markup(TAINTED_STRING)
    m_safe = Markup(SAFE)

    # this 3 tests might look strange, but the purpose is to check we still treat `ts`
    # as tainted even after it has been escaped in some place. This _might_ not be the
    # case since data-flow library has taint-steps from adjacent uses...
    ensure_tainted(ts)  # $ tainted
    ensure_not_tainted(
        escape(ts))  # $ escapeInput=ts escapeKind=html escapeOutput=escape(..)
    ensure_tainted(ts)  # $ tainted

    ensure_tainted(
        ts,  # $ tainted
        m_unsafe,  # $ tainted
        m_unsafe +
        SAFE,  # $ escapeInput=SAFE escapeKind=html escapeOutput=BinaryExpr MISSING: tainted
        SAFE +
        m_unsafe,  # $ escapeInput=SAFE escapeKind=html escapeOutput=BinaryExpr MISSING: tainted
        m_unsafe.format(
            SAFE
        ),  # $ escapeInput=SAFE escapeKind=html escapeOutput=m_unsafe.format(..) MISSING: tainted
        m_unsafe %
        SAFE,  # $ escapeInput=SAFE escapeKind=html escapeOutput=BinaryExpr MISSING: tainted
        m_unsafe +
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr MISSING: tainted
        m_safe.format(m_unsafe),  # $ tainted
        m_safe % m_unsafe,  # $ tainted
        escape(ts).unescape(
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=escape(..) MISSING: tainted
        escape_silent(ts).unescape(
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=escape_silent(..) MISSING: tainted
    )

    ensure_not_tainted(
        escape(ts),  # $ escapeInput=ts escapeKind=html escapeOutput=escape(..)
        escape_silent(
            ts
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=escape_silent(..)
        Markup.escape(
            ts
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=Markup.escape(..)
        m_safe,
        m_safe +
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr
        ts +
        m_safe,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr
        m_safe.format(
            ts
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=m_safe.format(..)
        m_safe %
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr
        escape(ts) +
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr escapeOutput=escape(..)
        escape_silent(ts) +
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr escapeOutput=escape_silent(..)
        Markup.escape(ts) +
        ts,  # $ escapeInput=ts escapeKind=html escapeOutput=BinaryExpr escapeOutput=Markup.escape(..)
    )

    # flask re-exports these, as:
    # flask.escape = markupsafe.escape
    # flask.Markup = markupsafe.Markup
    import flask

    ensure_tainted(
        flask.Markup(ts),  # $ tainted
    )

    ensure_not_tainted(
        flask.escape(
            ts
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=flask.escape(..)
        flask.Markup.escape(
            ts
        ),  # $ escapeInput=ts escapeKind=html escapeOutput=flask.Markup.escape(..)
    )
Exemple #11
0
 def test_filters2():
     messages = flask.get_flashed_messages(category_filter=['message', 'warning'])
     self.assert_equal(len(messages), 2)
     self.assert_equal(messages[0], u'Hello World')
     self.assert_equal(messages[1], flask.Markup(u'<em>Testing</em>'))
     return ''
Exemple #12
0
def lemmas_spans(lemmas: LexemeLemmas) -> flask.Markup:
    return flask.Markup(r'/').join(term_span(lemma)
                                   for lemma in lemmas.values())
Exemple #13
0
def form2input(context, form, first=False, readonly=False, template_language_code=None, representation_language_code=None):
    (prefix, placeholder, suffix) = split_example(form)
    if 'lexeme_forms' in form and template_language_code != representation_language_code:
        placeholder = '/'.join(lexeme_form['representations'][template_language_code]['value']
                               for lexeme_form in form['lexeme_forms']
                               if template_language_code in lexeme_form['representations'])
    optional = context['advanced'] or form.get('optional', False)
    return (flask.Markup.escape(prefix) +
            flask.Markup(r'<input type="text" name="form_representation" placeholder="') +
            flask.Markup.escape(placeholder) +
            flask.Markup(r'"') +
            flask.Markup(r' pattern="[^/]+(?:/[^/]+)*"') +
            (flask.Markup(r' required') if not optional else flask.Markup('')) +
            (flask.Markup(r' disabled') if readonly else flask.Markup('')) +
            (flask.Markup(r' autofocus') if first else flask.Markup('')) +
            (flask.Markup(r' value="') + flask.Markup.escape(form['value']) + flask.Markup(r'"') if 'value' in form else flask.Markup('')) +
            flask.Markup(r' spellcheck="true"') +
            (flask.Markup(r' lang="') + flask.Markup.escape(representation_language_code) + flask.Markup(r'"') if representation_language_code != template_language_code else flask.Markup('')) +
            flask.Markup(r'>') +
            flask.Markup.escape(suffix))
Exemple #14
0
def edit_torrent(torrent_id):
    torrent = models.Torrent.by_id(torrent_id)
    form = forms.EditForm(flask.request.form)
    form.category.choices = _create_upload_category_choices()
    delete_form = forms.DeleteForm()
    ban_form = None

    editor = flask.g.user

    if not torrent:
        flask.abort(404)

    # Only allow admins edit deleted torrents
    if torrent.deleted and not (editor and editor.is_moderator):
        flask.abort(404)

    # Only allow torrent owners or admins edit torrents
    if not editor or not (editor is torrent.user or editor.is_moderator):
        flask.abort(403)

    torrent_user_level = torrent.user and torrent.user.level
    if editor and editor.is_moderator and \
            (torrent_user_level is None or editor.level > torrent_user_level):
        ban_form = forms.BanForm()

    if flask.request.method == 'POST' and form.submit.data and form.validate():
        # Form has been sent, edit torrent with data.
        torrent.main_category_id, torrent.sub_category_id = \
            form.category.parsed_data.get_category_ids()
        torrent.display_name = (form.display_name.data or '').strip()
        torrent.information = (form.information.data or '').strip()
        torrent.description = (form.description.data or '').strip()

        torrent.hidden = form.is_hidden.data
        torrent.remake = form.is_remake.data
        torrent.complete = form.is_complete.data
        torrent.anonymous = form.is_anonymous.data

        if editor.is_trusted:
            torrent.trusted = form.is_trusted.data

        deleted_changed = torrent.deleted != form.is_deleted.data
        if editor.is_moderator:
            torrent.deleted = form.is_deleted.data

        url = flask.url_for('torrents.view', torrent_id=torrent.id)
        if deleted_changed and editor.is_moderator:
            log = "Torrent [#{0}]({1}) marked as {2}".format(
                torrent.id, url, "deleted" if torrent.deleted else "undeleted")
            adminlog = models.AdminLog(log=log, admin_id=editor.id)
            db.session.add(adminlog)

        db.session.commit()

        flask.flash(
            flask.Markup(
                'Torrent has been successfully edited! Changes might take a few minutes to show up.'
            ), 'success')

        return flask.redirect(url)
    elif flask.request.method == 'POST' and delete_form.validate() and \
            (not ban_form or ban_form.validate()):
        return _delete_torrent(torrent, delete_form, ban_form)
    else:
        if flask.request.method != 'POST':
            # Fill form data only if the POST didn't fail
            form.category.data = torrent.sub_category.id_as_string
            form.display_name.data = torrent.display_name
            form.information.data = torrent.information
            form.description.data = torrent.description

            form.is_hidden.data = torrent.hidden
            form.is_remake.data = torrent.remake
            form.is_complete.data = torrent.complete
            form.is_anonymous.data = torrent.anonymous

            form.is_trusted.data = torrent.trusted
            form.is_deleted.data = torrent.deleted

        ipbanned = None
        if editor.is_moderator:
            torrent_ip_banned = True
            user_ip_banned = True

            # Archived torrents do not have a null uploader_ip
            if torrent.uploader_ip:
                torrent_ip_banned = models.Ban.banned(
                    None, torrent.uploader_ip).first()

            if torrent.user:
                user_ip_banned = models.Ban.banned(
                    None, torrent.user.last_login_ip).first()
            ipbanned = (torrent_ip_banned and user_ip_banned)

        return flask.render_template('edit.html',
                                     form=form,
                                     delete_form=delete_form,
                                     ban_form=ban_form,
                                     torrent=torrent,
                                     ipbanned=ipbanned)
Exemple #15
0
def _check_rpmfusion(repos):
    if "rpmfusion" in repos:
        message = flask.Markup(
            'Using rpmfusion as dependency is nearly always wrong. Please see <a href="https://docs.pagure.org/copr.copr/user_documentation.html#what-i-can-build-in-copr">What I can build in Copr</a>.'
        )
        flask.flash(message, "error")
Exemple #16
0
 def _get_script_markup(self):
     return flask.Markup(self.templates['init'].render(
         charts=self.charts,
         config=self.config,
         packages=self.packages(),
         include_tags=True))
Exemple #17
0
    index_php = 'https://{{ cookiecutter.wiki_domain }}/w/index.php'


@app.template_global()
def csrf_token(){% if cookiecutter.set_up_mypy == "True" %} -> str{% endif %}:
    if 'csrf_token' not in flask.session:
        characters = string.ascii_letters + string.digits
        random_string = ''.join(random.choice(characters) for _ in range(64))
        flask.session['csrf_token'] = random_string
    return flask.session['csrf_token']


@app.template_global()
def form_value(name{% if cookiecutter.set_up_mypy == "True" %}: str{% endif %}){% if cookiecutter.set_up_mypy == "True" %} -> flask.Markup{% endif %}:
    if 'repeat_form' in flask.g and name in flask.request.form:
        return (flask.Markup(r' value="') +
                flask.Markup.escape(flask.request.form[name]) +
                flask.Markup(r'" '))
    else:
        return flask.Markup()


@app.template_global()
def form_attributes(name{% if cookiecutter.set_up_mypy == "True" %}: str{% endif %}){% if cookiecutter.set_up_mypy == "True" %} -> flask.Markup{% endif %}:
    return (flask.Markup(r' id="') +
            flask.Markup.escape(name) +
            flask.Markup(r'" name="') +
            flask.Markup.escape(name) +
            flask.Markup(r'" ') +
            form_value(name))
Exemple #18
0
def _preprocess_variables(config, strings):
    strings['in_page'] = \
        flask.Markup(strings['in_page']) % _link('%s', '%s')

    strings.setdefault('tooltitle', 'Citation Hunt')

    if config.lead_section_policy_link:
        strings['lead_section_hint'] = \
            flask.Markup(strings['lead_section_hint']) % _link(
                config.lead_section_policy_link,
                config.lead_section_policy_link_title)
    else:
        strings['lead_section_hint'] = ''

    strings['page_not_found_text'] = \
        flask.Markup(strings['page_not_found_text']) % _link(
            'https://tools.wmflabs.org/citationhunt/' + config.lang_code,
            'Citation Hunt', "_self")

    strings.setdefault('instructions_goal', '')
    if strings['instructions_goal']:
        if hasattr(config, 'reliable_sources_link'):
            link_start, link_end = (
                _link_start(config.reliable_sources_link), '</a>')
        else:
            link_start = link_end = ''

        # Note that format() doesn't raise an exception if the string doesn't
        # have any formatters, so this is fine even if instructions_goal is
        # outdated and doesn't contain the {link_start}/{link_end} markers.
        strings['instructions_goal'] = flask.Markup(
            strings['instructions_goal'].format(
                link_start = link_start, link_end = link_end))

    strings.setdefault('instructions_details', '')
    if strings['instructions_details'].count('%s') == 3:
        beginners_hint_link = _link(
            config.beginners_link,
            config.beginners_link_title)
        # Support the extra link pre-#129.
        strings['instructions_details'] = flask.Markup(
                strings['instructions_details']) % (
                    flask.Markup('<b>' + strings['button_wikilink'] + '</b>'),
                    flask.Markup('<b>' + strings['button_next'] + '</b>'),
                    beginners_hint_link)
    else:
        # Support beginner's link, optionally.
        if hasattr(config, 'beginners_link'):
            link_start, link_end = (_link_start(config.beginners_link), '</a>')
        else:
            link_start = link_end = ''
        strings['instructions_details'] = flask.Markup(
                (strings['instructions_details'] % (
                    flask.Markup('<b>' + strings['button_wikilink'] + '</b>'),
                    flask.Markup('<b>' + strings['button_next'] + '</b>'))).format(
                        link_start = link_start, link_end = link_end))

    strings.setdefault('footer', '')
    if strings['footer']:
        # We replace the URLs in the template itself
        strings['footer'] = flask.Markup(strings['footer']) % (
            strings['tooltitle'],
            _link('%s', 'Tools Labs'),
            _link('%s', 'translatewiki.net'))

    strings.setdefault('leaderboard_title', '')
    strings.setdefault('leaderboard_description', '')
    if strings['leaderboard_title'] and strings['leaderboard_description']:
        strings['leaderboard_title'] = strings['leaderboard_title'] % (
            strings['tooltitle'])
        strings['leaderboard_description'] = (
            strings['leaderboard_description'].format(
                tooltitle = strings['tooltitle'],
                days = '%s'))  # The template swaps in the actual number.

    strings.setdefault('custom_intro', '')
    if strings['custom_intro']:
        strings['custom_intro'] = strings['custom_intro'].format(
            tooltitle = strings['tooltitle'])

    strings.setdefault('import_articles_prompt', '')
    if strings['import_articles_prompt']:
        strings['import_articles_prompt'] = flask.Markup(
            strings['import_articles_prompt'].format(
                em_start = '<b>',
                em_end = '</b>'))

    strings.setdefault('import_petscan_intro', '')
    if strings['import_petscan_intro']:
        strings['import_petscan_intro'] = flask.Markup(
            strings['import_petscan_intro'].format(
                em_start = '<b>',
                em_end = '</b>'))

    strings.setdefault('import_petscan_prompt', '')
    if strings['import_petscan_prompt']:
        strings['import_petscan_prompt'] = flask.Markup(
            strings['import_petscan_prompt'].format(
                link_start = _link_start(make_petscan_url(config)),
                link_end = '</a>'))

    strings.setdefault('import_petscan_category_tip', '')
    if strings['import_petscan_category_tip']:
        strings['import_petscan_category_tip'] = flask.Markup(
            strings['import_petscan_category_tip'].format(
                tooltitle = strings['tooltitle'],
                category = '<i>' + config.citation_needed_category + '</i>'))

    strings.setdefault('back_to_cancel', '')
    if strings['back_to_cancel'] and strings['back']:
        strings['back_to_cancel'] = flask.Markup(
            strings['back_to_cancel'].format(
                em_start = '<b>', back = strings['back'],
                em_end = '</b>'))

    strings['custom_please_wait'] = flask.Markup(
        strings.get('custom_please_wait', '').format(
            tooltitle = strings['tooltitle']))

    strings['custom_failed'] = flask.Markup(
        strings.get('custom_failed', '').format(
            tooltitle = strings['tooltitle']))

    strings.setdefault('custom_notice', '')
    if strings['custom_notice']:
        strings['custom_notice'] = flask.Markup(
            strings['custom_notice'].format(
                tooltitle = strings['tooltitle'],
                link_start = _link_start('/' + config.lang_code, ''),
                link_end = '</a>'))

    strings['custom_created'] = strings.get(
        'custom_created', '').format(
            tooltitle = strings['tooltitle'])

    strings.setdefault('js-leaving-custom', '')
    if strings['js-leaving-custom']:
        strings['js-leaving-custom'] = (
            strings['js-leaving-custom'].format(
                tooltitle = strings['tooltitle']))

    strings.setdefault('custom_end_copy_link', '')
    if strings['custom_end_copy_link']:
        strings['custom_end_copy_link'] = flask.Markup(
            strings['custom_end_copy_link'].format(
                link_start = _link_start('', ''),
                link_end = '</a>'))

    strings.setdefault('select_articles', '')
    if strings['select_articles']:
        strings['select_articles'] = strings['select_articles'].format(
                tooltitle = strings['tooltitle'])

    strings.setdefault('select_articles_prompt', '')
    if strings['select_articles_prompt']:
        strings['select_articles_prompt'] = flask.Markup(
            strings['select_articles_prompt'].format(
                em_start = '<b>', em_end = '</b>',
                tooltitle = strings['tooltitle']))

    strings.setdefault('custom_import_prompt', '')
    if strings['custom_import_prompt']:
        strings['custom_import_prompt'] = (
            strings['custom_import_prompt'].format(
                tooltitle = strings['tooltitle']))

    return strings
Exemple #19
0
def galois_group_data(n, t):
    return flask.Markup(group_knowl_guts(n, t, db()))
Exemple #20
0
def _link_start(url, target = '_blank'):
    return flask.Markup('<a target="%s" href="%s">' % (target, url))
Exemple #21
0
def group_character_table_data(n, t):
    return flask.Markup(group_character_table_knowl_guts(n, t, db()))
Exemple #22
0
def _link(url, title, target = "_blank"):
    return flask.Markup('%s%s</a>' % (_link_start(url, target), title))
Exemple #23
0
def edit_torrent(torrent_id):
    torrent = models.Torrent.by_id(torrent_id)
    form = forms.EditForm(flask.request.form)
    form.category.choices = _create_upload_category_choices()

    editor = flask.g.user

    if not torrent:
        flask.abort(404)

    # Only allow admins edit deleted torrents
    if torrent.deleted and not (editor and editor.is_admin):
        flask.abort(404)

    # Only allow torrent owners or admins edit torrents
    if not editor or not (editor is torrent.user or editor.is_admin):
        flask.abort(403)

    if flask.request.method == 'POST' and form.validate():
        # Form has been sent, edit torrent with data.
        torrent.main_category_id, torrent.sub_category_id = \
            form.category.parsed_data.get_category_ids()
        torrent.display_name = (form.display_name.data or '').strip()
        torrent.information = (form.information.data or '').strip()
        torrent.description = (form.description.data or '').strip()

        torrent.hidden = form.is_hidden.data
        torrent.remake = form.is_remake.data
        torrent.complete = form.is_complete.data
        torrent.anonymous = form.is_anonymous.data

        if editor.is_trusted:
            torrent.trusted = form.is_trusted.data
        if editor.is_admin:
            torrent.deleted = form.is_deleted.data

        db.session.commit()

        flask.flash(
            flask.Markup(
                'Torrent has been successfully edited! Changes might take a few minutes to show up.'
            ), 'info')

        return flask.redirect(
            flask.url_for('view_torrent', torrent_id=torrent.id))
    else:
        if flask.request.method != 'POST':
            # Fill form data only if the POST didn't fail
            form.category.data = torrent.sub_category.id_as_string
            form.display_name.data = torrent.display_name
            form.information.data = torrent.information
            form.description.data = torrent.description

            form.is_hidden.data = torrent.hidden
            form.is_remake.data = torrent.remake
            form.is_complete.data = torrent.complete
            form.is_anonymous.data = torrent.anonymous

            form.is_trusted.data = torrent.trusted
            form.is_deleted.data = torrent.deleted

        return flask.render_template('edit.html',
                                     form=form,
                                     torrent=torrent,
                                     editor=editor)
Exemple #24
0
def view_user(user_name):
    user = models.User.by_username(user_name)

    if not user:
        flask.abort(404)

    admin_form = None
    ban_form = None
    bans = None
    ipbanned = None
    nuke_form = None
    if flask.g.user and flask.g.user.is_moderator and flask.g.user.level > user.level:
        admin_form = forms.UserForm()
        default, admin_form.user_class.choices = _create_user_class_choices(
            user)
        if flask.request.method == 'GET':
            admin_form.user_class.data = default

        ban_form = forms.BanForm()
        nuke_form = forms.NukeForm()
        if flask.request.method == 'POST':
            doban = (ban_form.ban_user.data or ban_form.unban.data
                     or ban_form.ban_userip.data)
        bans = models.Ban.banned(user.id, user.last_login_ip).all()
        ipbanned = list(filter(lambda b: b.user_ip == user.last_login_ip,
                               bans))

    url = flask.url_for('users.view_user', user_name=user.username)
    if flask.request.method == 'POST' and admin_form and not doban and admin_form.validate(
    ):
        selection = admin_form.user_class.data
        mapping = {
            'regular': models.UserLevelType.REGULAR,
            'trusted': models.UserLevelType.TRUSTED,
            'moderator': models.UserLevelType.MODERATOR
        }

        if mapping[selection] != user.level:
            user.level = mapping[selection]
            log = "[{}]({}) changed to {} user".format(user_name, url,
                                                       selection)
            adminlog = models.AdminLog(log=log, admin_id=flask.g.user.id)
            db.session.add(adminlog)

        if admin_form.activate_user.data and not user.is_banned:
            if user.status != models.UserStatusType.ACTIVE:
                user.status = models.UserStatusType.ACTIVE
                adminlog = models.AdminLog(
                    "[{}]({}) was manually activated".format(user_name, url),
                    admin_id=flask.g.user.id)
                db.session.add(adminlog)
                flask.flash('{} was manually activated'.format(user_name),
                            'success')

        db.session.add(user)
        db.session.commit()

        return flask.redirect(url)

    if flask.request.method == 'POST' and ban_form and doban and ban_form.validate(
    ):
        if (ban_form.ban_user.data and user.is_banned) or \
                (ban_form.ban_userip.data and ipbanned) or \
                (ban_form.unban.data and not user.is_banned and not bans):
            flask.flash(flask.Markup('What the f**k are you doing?'), 'danger')
            return flask.redirect(url)

        user_str = "[{0}]({1})".format(user.username, url)

        if ban_form.unban.data:
            action = "unbanned"
            user.status = models.UserStatusType.ACTIVE
            db.session.add(user)

            for ban in bans:
                if ban.user_ip:
                    user_str += " IP({0})".format(ip_address(ban.user_ip))
                db.session.delete(ban)
        else:
            action = "banned"
            user.status = models.UserStatusType.BANNED
            db.session.add(user)

            ban = models.Ban(admin_id=flask.g.user.id,
                             user_id=user.id,
                             reason=ban_form.reason.data)
            db.session.add(ban)

            if ban_form.ban_userip.data:
                ban.user_ip = ip_address(user.last_login_ip)
                user_str += " IP({0})".format(ban.user_ip)
                ban.user_ip = ban.user_ip.packed

        log = "User {0} has been {1}.".format(user_str, action)
        adminlog = models.AdminLog(log=log, admin_id=flask.g.user.id)
        db.session.add(adminlog)

        db.session.commit()

        flask.flash(
            flask.Markup('User has been successfully {0}.'.format(action)),
            'success')
        return flask.redirect(url)

    req_args = flask.request.args

    search_term = chain_get(req_args, 'q', 'term')

    sort_key = req_args.get('s')
    sort_order = req_args.get('o')

    category = chain_get(req_args, 'c', 'cats')
    quality_filter = chain_get(req_args, 'f', 'filter')

    page_number = chain_get(req_args, 'p', 'page', 'offset')
    try:
        page_number = max(1, int(page_number))
    except (ValueError, TypeError):
        page_number = 1

    results_per_page = app.config.get('RESULTS_PER_PAGE', DEFAULT_PER_PAGE)

    query_args = {
        'term': search_term or '',
        'user': user.id,
        'sort': sort_key or 'id',
        'order': sort_order or 'desc',
        'category': category or '0_0',
        'quality_filter': quality_filter or '0',
        'page': page_number,
        'rss': False,
        'per_page': results_per_page
    }

    if flask.g.user:
        query_args['logged_in_user'] = flask.g.user
        if flask.g.user.is_moderator:  # God mode
            query_args['admin'] = True

    # Use elastic search for term searching
    rss_query_string = _generate_query_string(search_term, category,
                                              quality_filter, user_name)
    use_elastic = app.config.get('USE_ELASTIC_SEARCH')
    if use_elastic and search_term:
        query_args['term'] = search_term

        max_search_results = app.config.get('ES_MAX_SEARCH_RESULT',
                                            DEFAULT_MAX_SEARCH_RESULT)

        # Only allow up to (max_search_results / page) pages
        max_page = min(query_args['page'],
                       int(math.ceil(max_search_results / results_per_page)))

        query_args['page'] = max_page
        query_args['max_search_results'] = max_search_results

        query_results = search_elastic(**query_args)

        max_results = min(max_search_results, query_results['hits']['total'])
        # change p= argument to whatever you change page_parameter to or pagination breaks
        pagination = Pagination(p=query_args['page'],
                                per_page=results_per_page,
                                total=max_results,
                                bs_version=3,
                                page_parameter='p',
                                display_msg=SERACH_PAGINATE_DISPLAY_MSG)
        return flask.render_template('user.html',
                                     use_elastic=True,
                                     pagination=pagination,
                                     torrent_query=query_results,
                                     search=query_args,
                                     user=user,
                                     user_page=True,
                                     rss_filter=rss_query_string,
                                     admin_form=admin_form,
                                     ban_form=ban_form,
                                     nuke_form=nuke_form,
                                     bans=bans,
                                     ipbanned=ipbanned)
    # Similar logic as home page
    else:
        if use_elastic:
            query_args['term'] = ''
        else:
            query_args['term'] = search_term or ''
        query = search_db(**query_args)
        return flask.render_template('user.html',
                                     use_elastic=False,
                                     torrent_query=query,
                                     search=query_args,
                                     user=user,
                                     user_page=True,
                                     rss_filter=rss_query_string,
                                     admin_form=admin_form,
                                     ban_form=ban_form,
                                     nuke_form=nuke_form,
                                     bans=bans,
                                     ipbanned=ipbanned)
Exemple #25
0
def view_docs(repo, username=None, namespace=None, filename=None):
    """ Display the documentation
    """
    if "." in repo:
        namespace, repo = repo.split(".", 1)

    repo = pagure.lib.query.get_authorized_project(SESSION,
                                                   repo,
                                                   user=username,
                                                   namespace=namespace)

    if not repo:
        flask.abort(404, description="Project not found")

    if not repo.settings.get("project_documentation", True):
        flask.abort(404, description="This project has documentation disabled")

    reponame = repo.repopath("docs")
    if not os.path.exists(reponame):
        flask.abort(404, description="Documentation not found")

    repo_obj = pygit2.Repository(reponame)

    if not repo_obj.is_empty:
        commit = repo_obj[repo_obj.head.target]
    else:
        flask.abort(
            404,
            flask.Markup(
                "No content found in the repository, you may want to read "
                'the <a href="'
                'https://docs.pagure.org/pagure/usage/using_doc.html">'
                "Using the doc repository of your project</a> documentation."),
        )

    content = None
    tree = None
    if not filename:
        path = [""]
    else:
        path = [it for it in filename.split("/") if it]

    if commit:
        try:
            (tree, content,
             filename) = __get_tree_and_content(repo_obj, commit, path)
        except pagure.exceptions.FileNotFoundException as err:
            flask.flash("%s" % err, "error")
        except Exception as err:
            _log.exception(err)
            flask.abort(500,
                        description="Unkown error encountered and reported")

    if not content:
        if not tree or not len(tree):
            flask.abort(404, description="No content found in the repository")
        html = "<li>"
        for el in tree:
            name = el.name
            # Append a trailing '/' to the folders
            if el.filemode == 16384:
                name += "/"
            html += '<ul><a href="{0}">{1}</a></ul>'.format(name, name)
        html += "</li>"
        content = TMPL_HTML.format(content=html)
        mimetype = "text/html"
    else:
        mimetype, _ = pagure.lib.mimetype.guess_type(filename, content)

    return flask.Response(content, mimetype=mimetype)
Exemple #26
0
def nl2br(text):
    return flask.Markup('<br>').join(text.splitlines())
Exemple #27
0
def _shorten(addr, n=5):
    return flask.Markup(
        '<span class="not-ellipsed">%s</span><span class="ellipsed">%s'
        '</span>' % (addr, "%s&nbsp;&hellip;&nbsp;%s" % (addr[:n], addr[-n:])))
Exemple #28
0
 def index():
     return flask.render_template("non_escaping_template.txt",
                                  text=text,
                                  html=flask.Markup(text))
Exemple #29
0
def view_docs(repo, username=None, namespace=None, filename=None):
    """ Display the documentation
    """
    if '.' in repo:
        namespace, repo = repo.split('.', 1)

    repo = pagure.get_authorized_project(SESSION,
                                         repo,
                                         user=username,
                                         namespace=namespace)

    if not repo:
        flask.abort(404, 'Project not found')

    if not repo.settings.get('project_documentation', True):
        flask.abort(404, 'This project has documentation disabled')

    reponame = os.path.join(APP.config['DOCS_FOLDER'], repo.path)
    if not os.path.exists(reponame):
        flask.abort(404, 'Documentation not found')

    repo_obj = pygit2.Repository(reponame)

    if not repo_obj.is_empty:
        commit = repo_obj[repo_obj.head.target]
    else:
        flask.abort(
            404,
            flask.Markup(
                'No content found in the repository, you may want to read '
                'the <a href="'
                'https://docs.pagure.org/pagure/usage/using_doc.html">'
                'Using the doc repository of your project</a> documentation.'))

    content = None
    tree = None
    if not filename:
        path = ['']
    else:
        path = [it for it in filename.split('/') if it]

    if commit:
        try:
            (tree, content,
             filename) = __get_tree_and_content(repo_obj, commit, path)
        except pagure.exceptions.FileNotFoundException as err:
            flask.flash(err.message, 'error')
        except Exception as err:
            _log.exception(err)
            flask.abort(500, 'Unkown error encountered and reported')

    if not content:
        if not tree or not len(tree):
            flask.abort(404, 'No content found in the repository')
        html = '<li>'
        for el in tree:
            name = el.name
            # Append a trailing '/' to the folders
            if el.filemode == 16384:
                name += '/'
            html += '<ul><a href="{0}">{1}</a></ul>'.format(name, name)
        html += '</li>'
        content = TMPL_HTML.format(content=html)
        mimetype = 'text/html'
    else:
        mimetype, _ = pagure.lib.mimetype.guess_type(filename, content)

    return flask.Response(content, mimetype=mimetype)
Exemple #30
0
    def dispatch_request(self):
        """
        Mandatory interface required by the :py:func:`flask.views.View.dispatch_request`.
        Will be called by the *Flask* framework to service the request.
        """

        form = RegistrationForm(
            choices_locales = list(flask.current_app.config['MYDOJO_LOCALES'].items())
        )

        if form.validate_on_submit():
            form_data = form.data

            if form_data[mydojo.const.FORM_ACTION_CANCEL]:
                self.flash(
                    gettext('Account registration canceled.'),
                    mydojo.const.FLASH_INFO
                )
                return self.redirect(
                    default_url = flask.url_for(
                        flask.current_app.config['MYDOJO_ENDPOINT_HOME']
                    )
                )

            if form_data[mydojo.const.FORM_ACTION_SUBMIT]:
                try:
                    # Populate the user object from form data and make sure the
                    # account has default 'user' role and is disabled by default.
                    item = UserModel()
                    form.populate_obj(item)
                    item.roles = [mydojo.const.ROLE_USER]
                    item.enabled = False

                    self.dbsession.add(item)
                    self.dbsession.commit()

                    # Send information about new account registration to system
                    # admins. Use default locale for email content translations.
                    mail_locale = flask.current_app.config['BABEL_DEFAULT_LOCALE']
                    with force_locale(mail_locale):
                        msg = flask_mail.Message(
                            gettext(
                                "%(prefix)s Account registration - %(item_id)s",
                                prefix  = flask.current_app.config['MAIL_SUBJECT_PREFIX'],
                                item_id = item.login
                            ),
                            recipients = flask.current_app.config['MYDOJO_ADMINS']
                        )
                        msg.body = flask.render_template(
                            'auth_pwd/email_registration_admins.txt',
                            account = item,
                            justification = form_data['justification']
                        )
                        MAILER.send(msg)

                    # Send information about new account registration to the user.
                    # Use user`s preferred locale for email content translations.
                    mail_locale = item.locale
                    if not mail_locale:
                        mail_locale = flask.current_app.config['BABEL_DEFAULT_LOCALE']
                    with force_locale(mail_locale):
                        msg = flask_mail.Message(
                            gettext(
                                "%(prefix)s Account registration - %(item_id)s",
                                prefix  = flask.current_app.config['MAIL_SUBJECT_PREFIX'],
                                item_id = item.login
                            ),
                            recipients = [item.email]
                        )
                        msg.body = flask.render_template(
                            'auth_pwd/email_registration_user.txt',
                            account = item,
                            justification = form_data['justification']
                        )
                        MAILER.send(msg)

                    self.flash(
                        flask.Markup(gettext(
                            'User account <strong>%(login)s (%(name)s)</strong> was successfully registered.',
                            login = item.login,
                            name = item.fullname
                        )),
                        mydojo.const.FLASH_SUCCESS
                    )
                    self.logger.info(
                        "New user account '{}' was successfully registered with 'auth_pwd'.".format(
                            item.login
                        )
                    )
                    return self.redirect(
                        default_url = flask.url_for(
                            flask.current_app.config['MYDOJO_ENDPOINT_HOME']
                        )
                    )

                except Exception:  # pylint: disable=locally-disabled,broad-except
                    self.flash(
                        gettext('Unable to register new user account.'),
                        mydojo.const.FLASH_FAILURE
                    )
                    flask.current_app.log_exception_with_label(
                        traceback.TracebackException(*sys.exc_info()),
                        'Unable to register new user account.',
                    )

        self.response_context.update(
            form_url = flask.url_for('{}.{}'.format(
                self.module_name,
                self.get_view_name()
            )),
            form = form
        )
        return self.generate_response()