Esempio n. 1
0
File: terms.py Progetto: julen/tzos
def edit(id):

    if g.user.is_corrector:
        user_restriction = "true()"
    else:
        user_restriction = "term:is_public($tig)"

    qs = """
    import module namespace term = "http://tzos.net/term" at "term.xqm";

    let $tig := collection($collection)/martif/text/body/termEntry/langSet/tig[@id="{0}"]
    let $unreviewed :=
        if (term:owner($tig) = "{1}") then
            true()
        else
            false()
    where term:owner($tig) = "{1}" or {2}
    return term:values($tig, $unreviewed)
    """.format(unicode(id).encode('utf-8'),
               getattr(g.user, 'username', u'').encode('utf-8'),
               user_restriction)

    term = dbxml.session.raw_query(qs).as_callback(Term.parse).first_or_404()

    try:
        term.lock()
    except Term.TermLocked:
        return render_template('terms/locked.html')

    # Be aware these checks have to be done from highest to lowest permissions
    if g.user.is_moderator:
        form_cls = EditTermFormMod
    elif g.user.is_corrector:
        form_cls = EditTermFormCor
    else:
        form_cls = EditTermForm

    form = _gen_term_form(form_cls, obj=term)

    #
    # Adapt working_status for reviewing cases
    #
    review = request.args.get('mode', u'') == u'review'

    if g.user.is_moderator and review:
        form.working_status.data = u"workingElement"
    elif g.user.is_corrector and review:
        form.working_status.data = True
    elif not g.user.is_moderator and g.user.is_corrector:
        form.working_status.data = term.is_public

    if form.validate_on_submit():

        new_term = Term()
        form.populate_obj(new_term)
        new_term._id = id

        objects = new_term.check_collision(term_id=id)

        if objects:
            flash(_(u'Collision detected! The renamed term you entered '
                    'already exists in the database.'), 'warning')

            return render_template('terms/edit.html', form=form, term=term)

        if new_term.update():
            _register_transaction(id)

            term.unlock()

            flash(_(u"Term ‘%(term)s’ has been edited.", term=new_term.term),
                    "success")

            return redirect(url_for("terms.detail", id=id))
        else:
            flash(_(u"Failed to edit term."), "error")

    elif request.method == 'POST' and not form.validate():
        flash(_(u"Failed to edit term. Please review the data you "
                 "entered is correct."), "error")

    return render_template('terms/edit.html', form=form, term=term)
Esempio n. 2
0
File: terms.py Progetto: julen/tzos
def add():

    form_args = None

    if request.args and 'term' in request.args and \
       'lang' in request.args and 'sf' in request.args:
        form_args = request.args.copy()

        form_args['add-subject_field'] = request.args.getlist('sf')
        form_args['add-syntrans_term'] = request.args['term']
        form_args['add-syntrans_lang'] = request.args['lang']
        form_args['add-syntrans'] = True
        form_args['add-transac_type'] = u'input'
        form_args['collision-subject_field'] = request.args.getlist('sf')
        form_args['collision-syntrans_term'] = request.args['term']
        form_args['collision-syntrans_lang'] = request.args['lang']
        form_args['collision-syntrans'] = True
        form_args['collision-transac_type'] = u'input'

        del form_args['sf']
        del form_args['term']
        del form_args['lang']

    if g.user.is_corrector:
        add_form_cls = AddTermFormCor
        upload_form_cls = UploadFormCor
        collision_form_cls = CollisionFormCor
    else:
        add_form_cls = AddTermForm
        upload_form_cls = UploadForm
        collision_form_cls = CollisionForm

    add_form = _gen_term_form(add_form_cls, formdata=form_args,
                                  prefix='add')
    collision_form = _gen_term_form(collision_form_cls, formdata=form_args,
                                  prefix='collision', csrf_enabled=False)
    upload_form = _gen_term_form(upload_form_cls, formdata=form_args,
                                     prefix='upload', csrf_enabled=False)

    if (add_form.submit.data and add_form.validate_on_submit()) or \
        ((collision_form.discard.data or collision_form.force.data) and \
        collision_form.validate_on_submit()):

        # Get desired extra action (only used in collision pages)
        force = False
        discard = False
        if collision_form.discard.data:
            discard = True
        elif collision_form.force.data:
            force = True

        if discard:
            flash(_(u"Term addition discarded."), 'success')
            return redirect(url_for('frontend.index'))

        term = Term()
        if collision_form.force.data:
            collision_form.populate_obj(term)
        else:
            add_form.populate_obj(term)

        _populate_equivalents(add_form, term)

        st, results, objects = term.insert_all(force=force)

        if st == u"success":
            msg = _(u'Term added successfully. '
                    '<a href="%(url)s">Go to the term</a>.',
                    url=url_for('terms.detail', id=term.id))
            flash(msg, 'success')

            return redirect(url_for("terms.add"))
        elif st == u"collision":
            msg = _(u'Collision detected!')
            flash(msg, 'warning')

            #
            # Fill in collision form
            #
            for fname in add_form._fields:

                if fname != 'csrf':
                    val = getattr(add_form, fname).data
                    f = getattr(collision_form, fname, None)

                    # FieldLists are tricky
                    if isinstance(f, FieldList):
                        f.pop_entry()
                        for entry in val:
                            f.append_entry(entry)
                    else:
                        f.data = val

            return render_template('terms/collision.html',
                    add_form=add_form,
                    collision_form=collision_form,
                    terms=objects)
        else:
            flash(_(u'Error while trying to add some terms.'), 'error')

    elif (upload_form.submit.data or upload_form.confirm.data or \
          upload_form.cancel.data) and upload_form.validate_on_submit():

        if upload_form.cancel.data:
            flash(_(u"Import action cancelled."), 'success')
            return redirect(url_for('frontend.index'))

        emulate = True
        if upload_form.confirm.data:
            emulate = False

        # Save for later reuse
        disk_fn = None
        if emulate:
            import os
            import random
            import string
            import tempfile

            f = request.files['upload-file']
            fn = ''.join(random.choice(string.lowercase) for x in range(6))
            disk_fn = os.path.join(tempfile.gettempdir(), fn)
            f.save(disk_fn)
            upload_form.fpath.data = disk_fn

        try:
            file = open(upload_form.fpath.data)
        except IOError:
            file = None

        fields = upload_form.columns.data.split(u";")
        fields.insert(0, upload_form.term_field.data)

        if file:
            import csv

            reader = csv.DictReader(file, fieldnames=fields, skipinitialspace=True)

            results = {}

            if not emulate:
                term_upload = TermUpload(author=g.user)

            for (count, row) in enumerate(reader):

                # Break on the max num. of allowed term uploads
                if count == current_app.config.get('TZOS_MAX_UPLOADS', 100):
                    break

                # Store current term for using as a reference for
                # synonyms and translations
                try:
                    # TODO: clean the input before blindly insert it
                    current_term = unicode(row[fields[0]], 'utf-8').strip()
                    current_language = fields[0][5:7]
                except IndexError:
                    current_term = None
                    current_language = None

                term = Term()
                upload_form.populate_obj(term)

                if term.working_status == u'starterElement':
                    term.working_status = u'importedElement'

                for field in fields:

                    if not row[field]:
                        continue

                    value = unicode(row[field], 'utf-8').strip()

                    if not value:
                        # No value passed, skip this field
                        continue

                    if field.startswith('term-'):

                        # Fill in fields
                        term.term = value
                        term.language = field[5:7]

                    elif field.startswith('trans-'):

                        lang = field[6:8]

                        if term.language == lang:
                            term.append_raw_synonym(value)
                        else:
                            term.append_raw_translation(lang, value)

                st, res, objects = term.insert_all(emulate=emulate)
                results.setdefault(st, []).append(res)

                # Add resulting terms to the upload tracking structure
                if not emulate:
                    for (term, status) in res:
                        if status == u'success':
                            term_upload.add(term)

            # Once all is processed, save the upload tracking structure
            if not emulate:
                db.session.add(term_upload)
                db.session.commit()

            # We need to set this again due to the postprocessing
            upload_form.fpath.data = disk_fn

            return render_template('terms/upload_results.html',
                    results=results,
                    upload_form=upload_form,
                    emulate=emulate)
        else:
            flash(_(u'Not a valid file.'), 'error')

    return render_template('terms/add.html', add_form=add_form,
                                             upload_form=upload_form)