Skip to content
__init__.py 72 KiB
Newer Older
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from flask import Blueprint
from flask import current_app, request, jsonify, session, url_for, redirect, abort

import base64
import hashlib
from uuid import uuid4

from cStringIO import StringIO
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import pdf2image
from PIL import Image
from pyzbar import pyzbar

import config
from const import pfsp
from functions import do_encrypt_user_session, do_decrypt_user_session
from functions import do_encrypt_dek, dek_generate, dek_check
from functions import mySMTP

import utils
from utils.decorator import login_required, submission_has_access, admin_required
from utils.images import create_thumbnail
from utils.template import my_render_template

from views.images import do_img_info

from NIST.fingerprint import NISTf_auto
from NIST.fingerprint.labels import FINGER_POSITION_CODE, PALM_POSITION_CODE
segments_position_code = dict( FINGER_POSITION_CODE, **PALM_POSITION_CODE )
submission_view = Blueprint( "submission", __name__, template_folder = "templates" )

@submission_view.route( "/upload", methods = [ "POST" ] )
@login_required
def upload_file():
    """
        Main function dealing with the upload of files (tenprint, mark and consent forms).
        This function accept traditionals images and NIST files for the fingerprint data,
        and PDFs for the consent forms.
    """
    current_app.logger.info( "Processing of the uploaded file" )
    
    upload_type = request.form.get( "upload_type", None )
    current_app.logger.debug( "Upload type: {}".format( upload_type ) )
    
    file_extension = request.form.get( "extension", None )
    if isinstance( file_extension, str ):
        file_extension = file_extension.lower()
    
    current_app.logger.debug( "File extension: {}".format( file_extension ) )
    
    if upload_type == None:
        return jsonify( {
            "error": True,
            "message": "Must specify a file type to upload a file"
        } )
    
    if "file" not in request.files:
        current_app.logger.error( "No file in the upload request" )
        return jsonify( {
            "error": True,
            "message": "No file in the POST request"
        } )
    
    elif "submission_id" not in request.form:
        current_app.logger.error( "No submission identification number" )
        return jsonify( {
            "error": True,
            "message": "No submission_id"
        } )
    
    else:
        try:
            submission_uuid = request.form.get( "submission_id" )
            sql = "SELECT id FROM submissions WHERE uuid = %s"
            submission_id = config.db.query_fetchone( sql, ( submission_uuid, ) )[ "id" ]
            
            current_app.logger.debug( "Submission UUID: {}".format( submission_uuid ) )
            
        except:
            return jsonify( {
                "error": True,
                "message": "upload not related to a submission form"
            } )
        
        uploaded_file = request.files[ "file" ]
        file_name = do_encrypt_user_session( uploaded_file.filename )
        file_uuid = str( uuid4() )
        
        current_app.logger.debug( "File uuid: {}".format( file_uuid ) )
        
        fp = StringIO()
        
        uploaded_file.save( fp )
        file_size = fp.tell()
        
        current_app.logger.debug( "File size: {}".format( file_size ) )
        
        fp.seek( 0 )
        
        if file_extension in config.NIST_file_extensions:
            file_data = fp.getvalue()
            file_data = base64.b64encode( file_data )
            file_data = do_encrypt_dek( file_data, submission_uuid )
            
            try:
                n = NISTf_auto( fp )
                
                if not n.is_initialized():
                    raise
                
                current_app.logger.info( "NIST file loaded correctly" )
                current_app.logger.debug( "Records: " + ", ".join( [ "Type-%02d" % x for x in n.get_ntype() ] ) )
            
            except:
                current_app.logger.error( "Error while loading the NIST file" )
                return jsonify( {
                    "error": True,
                    "message": "Error while loading the NIST file"
                } )
            
            # Save the NIST file in the DB
            current_app.logger.info( "Saving the NIST file to the database" )
            sql = utils.sql.sql_insert_generate( "files", [ "folder", "creator", "filename", "type", "format", "size", "uuid", "data" ] )
            data = ( submission_id, session[ "user_id" ], file_name, 5, "NIST", file_size, file_uuid, file_data, )
            config.db.query( sql, data )
            
            # Segmentation of the NIST file
            current_app.logger.info( "Segmenting the NIST file" )
            fpc_in_file = []
            for fpc in config.all_fpc:
                current_app.logger.debug( "FPC {}".format( fpc ) )
                
                try:
                    try:
                        img = n.get_print( fpc = fpc )
                    except:
                        img = n.get_palmar( fpc = fpc )
                    
                    buff = StringIO()
                    img.save( buff, format = "TIFF" )
                    
                    current_app.logger.debug( str( img ) )
                    
                    buff.seek( 0 )
                    img_data = buff.getvalue()
                    img_data = base64.b64encode( img_data )
                    img_data = do_encrypt_dek( img_data, submission_uuid )
                    
                    sql = utils.sql.sql_insert_generate( "files_segments", [ "tenprint", "uuid", "pc", "data" ] )
                    data = ( file_uuid, str( uuid4() ), fpc, img_data, )
                    config.db.query( sql, data )
                    
                    current_app.logger.info( "Image saved to the database" )
                    
                    fpc_in_file.append( fpc )
                
                except:
                    current_app.logger.debug( "    No data" )
                    pass
            
            current_app.logger.info( "FPC processed ({}): {}".format( len( fpc_in_file ), fpc_in_file ) )
            
            config.db.commit()
            
            return jsonify( {
                "error": False,
                "fpc": fpc_in_file
            } )
                
        else:
            if upload_type in [ "mark_target", "mark_incidental", "tenprint_card_front", "tenprint_card_back" ]:
                current_app.logger.info( "Image file type: {}".format( upload_type ) )
                
                img = Image.open( fp )
                img_format = img.format
                width, height = img.size
                
                current_app.logger.debug( str( img ) )
                
                try:
                    res = int( img.info[ "dpi" ][ 0 ] )
                    current_app.logger.debug( "Resolution: {}".format( res ) )
                except:
                    current_app.logger.error( "No resolution found in the image" )
                    return jsonify( {
                        "error": True,
                        "message": "No resolution found in the image. Upload not possible at the moment."
                    } )
                
                try:
                    img = utils.images.rotate_image_upon_exif( img )
                    current_app.logger.debug( "Rotation of the image" )
                except:
                    pass
                
                buff = StringIO()
                
                if img_format.upper() in [ "TIFF", "TIF" ]:
                    img.save( buff, format = img_format, compression = "raw" )
                else:
                    img.save( buff, format = img_format )
                
                buff.seek( 0 )
                file_data = buff.getvalue()
                
                if upload_type in [ "tenprint_card_front", "tenprint_card_back" ]:
                    current_app.logger.debug( "Creation of the thumbnail" )
                    create_thumbnail( file_uuid, img, submission_uuid )
            
            else:
                file_data = fp.getvalue()
            
            file_data_r = file_data
            file_data = base64.b64encode( file_data )
            
            sql = "SELECT id FROM files_type WHERE name = %s"
            upload_type_id = config.db.query_fetchone( sql, ( upload_type, ) )[ "id" ]
            
            ####################################################################
            
            if upload_type == "consent_form":
                current_app.logger.info( "Processing of the consent form" )
                
                sql = "SELECT email_aes FROM submissions WHERE uuid = %s"
                email = config.db.query_fetchone( sql, ( submission_uuid, ) )[ "email_aes" ]
                email = do_decrypt_user_session( email )
                
                sql = """
                    SELECT users.username, users.email
                    FROM users
                    LEFT JOIN account_type ON users.type = account_type.id
                    WHERE account_type.name = 'Donor'
                    ORDER BY users.id DESC
                """
                for username_db, email_db in config.db.query_fetchall( sql ):
                    if utils.hash.pbkdf2( email, email_db ).verify():
                        username = username_db
                        url_hash = hashlib.sha512( email_db ).hexdigest()
                        current_app.logger.info( "Donor: {}".format( username ) )
                        break
                
                else:
                    current_app.logger.error( "User not found" )
                    return jsonify( {
                        "error": True,
                        "message": "user not found"
                    } )
                
                # Check that the PDF contains the QRCODE
                qrcode_checked = False
                
                try:
                    pages = pdf2image.convert_from_bytes( 
                        file_data_r,
                        poppler_path = config.POPPLER_PATH
                    )
                    
                    for page in pages:
                        decoded = pyzbar.decode( page )
                        for d in decoded:
                            if d.data == "ICNML CONSENT FORM":
                                qrcode_checked = True
                
                except:
                    qrcode_checked = False
                
                # Email for the donor
                current_app.logger.info( "Sending the email to the donor" )
                email_content = utils.template.render_jinja_html( 
                    "templates/email", "donor.html",
                    username = username,
                    url = "https://icnml.unil.ch" + url_for( "newuser.config_new_user_donor", h = url_hash )
                )
                
                msg = MIMEMultipart()
                
                msg[ "Subject" ] = "ICNML - You have been added as donor"
                msg[ "From" ] = config.sender
                msg[ "To" ] = email
                
                msg.attach( MIMEText( email_content, "html" ) )
                
                part = MIMEApplication( file_data_r, Name = "consent_form.pdf" )
                part[ "Content-Disposition" ] = "attachment; filename=consent_form.pdf"
                msg.attach( part )
                 
                try:
                    with mySMTP() as s:
                        s.sendmail( config.sender, [ email ], msg.as_string() )
                    
                    current_app.logger.info( "Email sended" )
                
                except:
                    current_app.logger.error( "Can not send the email to the donor" )
                    return jsonify( {
                        "error": True,
                        "message": "Can not send the email to the user"
                    } )
                
                else:
                    # Consent form save
                    current_app.logger.info( "Saving the consent form to the database" )
                    file_data = base64.b64encode( file_data )
                    file_data = config.gpg.encrypt( file_data, *config.gpg_key )
                    file_data = str( file_data )
                    file_data = base64.b64encode( file_data )
                    
                    email_hash = utils.hash.pbkdf2( email, iterations = config.CF_NB_ITERATIONS ).hash()
                    
                    sql = utils.sql.sql_insert_generate( "cf", [ "uuid", "data", "email", "has_qrcode" ] )
                    data = ( file_uuid, file_data, email_hash, qrcode_checked, )
                    config.db.query( sql , data )
                    
                    sql = "UPDATE submissions SET consent_form = true WHERE uuid = %s"
                    config.db.query( sql, ( submission_uuid, ) )
                    
                    config.db.commit()
                
            else:
                # Save the file to the database
                current_app.logger.info( "Save the file to the databse" )
                
                file_data = do_encrypt_dek( file_data, submission_uuid )
                
                sql = utils.sql.sql_insert_generate( "files", [
                    "folder", "creator",
                    "filename", "type",
                    "format", "size", "width", "height", "resolution",
                    "uuid", "data"
                ] )
                data = ( 
                    submission_id, session[ "user_id" ],
                    file_name, upload_type_id,
                    img_format, file_size, width, height, res,
                    file_uuid, file_data,
                )
                config.db.query( sql, data )
                # Set the finger if available
                finger_name = request.form.get( "finger_name", None )
                if finger_name != None:
                    sql = utils.sql.sql_insert_generate( "mark_info", [ "uuid", "pfsp" ] )
                    config.db.query( sql, ( file_uuid, finger_name, ) )
                config.db.commit()
            
            return jsonify( {
                "error": False,
                "uuid": file_uuid
            } )

################################################################################
#    Submission of a new donor

@submission_view.route( "/submission/new" )
@submission_has_access
def submission_new():
    """
        Serve the page to start a new submission (new donor).
    """
    current_app.logger.info( "Serve the new donor form" )
    return my_render_template( "submission/new.html" )

@submission_view.route( "/submission/do_new", methods = [ "POST" ] )
@submission_has_access
def submission_do_new():
    """
        Check the new donor data, and store the new submission process in the database.
    """
    current_app.logger.info( "Process the new donor form" )
    
    email = request.form.get( "email", False )
    email = email.lower()
    
    if email:
        # Check for duplicate base upon the email data
        sql = "SELECT id, email_hash FROM submissions WHERE submitter_id = %s"
        for case in config.db.query_fetchall( sql, ( session[ "user_id" ], ) ):
            if utils.hash.pbkdf2( email, case[ "email_hash" ] ).verify():
                current_app.logger.error( "Email already used for an other submission ({}) by this submitter".format( case[ "id" ] ) )
                return jsonify( {
                    "error": True,
                    "message": "Email already used for an other submission. Check the list of submissions to update the corresponding one."
                } )
                
                break
        
        else:
            current_app.logger.info( "Insertion of the donor to the databse" )
            # Insert the new donor
            donor_uuid = str( uuid4() )
            current_app.logger.debug( "Donor uuid: {}".format( donor_uuid ) )
            
            email_aes = do_encrypt_user_session( email )
            email_hash = utils.hash.pbkdf2( email, iterations = config.EMAIL_NB_ITERATIONS ).hash()
            
            upload_nickname = request.form.get( "upload_nickname", None )
            upload_nickname = do_encrypt_user_session( upload_nickname )
            submitter_id = session[ "user_id" ]
            
            status = "pending"
            
            userid = config.db.query_fetchone( "SELECT nextval( 'username_donor_seq' ) as id" )[ "id" ]
            username = "donor_{}".format( userid )
            sql = utils.sql.sql_insert_generate( "users", [ "username", "email", "type" ], "id" )
            data = ( username, email_hash, 2 )
            donor_user_id = config.db.query_fetchone( sql, data )[ "id" ]
            
            current_app.logger.debug( "Username: {}".format( username ) )
            
            dek_salt, dek, dek_check = dek_generate( email = email, username = username )
            
            current_app.logger.debug( "DEK salt: {}...".format( dek_salt[ 0:10 ] ) )
            current_app.logger.debug( "DEK:      {}...".format( dek[ 0:10 ] ) )
            
            sql = utils.sql.sql_insert_generate( "donor_dek", [ "donor_name", "salt", "dek", "dek_check", "iterations", "algo", "hash" ], "id" )
            data = ( username, dek_salt, dek, dek_check, config.DEK_NB_ITERATIONS, "pbkdf2", "sha512", )
            config.db.query_fetchone( sql, data )
            
            sql = utils.sql.sql_insert_generate( "submissions", [ "uuid", "email_aes", "email_hash", "nickname", "donor_id", "status", "submitter_id" ] )
            data = ( donor_uuid, email_aes, email_hash, upload_nickname, donor_user_id, status, submitter_id, )
            config.db.query( sql, data )
            
            config.db.commit()
            
            return jsonify( {
                "error": False,
                "id": donor_uuid
            } )
        
    else:
        current_app.logger.error( "No email provided for the submission folder" )
        return jsonify( {
            "error": True,
            "message": "Email not provided"
        } )

@submission_view.route( "/submission/<submission_id>/add_files" )
@submission_has_access
def submission_upload_tenprintmark( submission_id ):
    """
        Serve the page to upload tenprint and mark images files.
        This page is not accessible if a consent form is not available in the
        database for this particular donor.
    """
    current_app.logger.info( "Upload a new file in the submission {}".format( submission_id ) )
    
    try:
        dek_check( submission_id )
        
        sql = """
            SELECT email_aes as email, nickname, created_time, consent_form
            FROM submissions
            WHERE submitter_id = %s AND uuid = %s
        """
        user = config.db.query_fetchone( sql, ( session[ "user_id" ], submission_id ) )
        
        if user[ "consent_form" ]:
            current_app.logger.debug( "The donor has a consent form" )
            current_app.logger.info( "Serving the add new file page" )
            
            for key in [ "email", "nickname" ]:
                user[ key ] = do_decrypt_user_session( user[ key ] )
            
            return my_render_template( 
                "submission/add_files.html",
                submission_id = submission_id,
                **user
            )
        else:
            current_app.logger.debug( "The donor dont have a consent form in the database" )
            current_app.logger.info( "Serving the consent form upload page" )
            
            return redirect( url_for( "submission.submission_consent_form", submission_id = submission_id ) )
        
Marco De Donno's avatar
Marco De Donno committed
    except:
        return jsonify( {
            "error": True,
            "message": "Case not found"
        } )

@submission_view.route( "/submission/<submission_id>/add_marks" )
@submission_has_access
def submission_upload_mark_per_finger( submission_id ):
    """
        Serve the page to upload mark images files per finger.
    """
    current_app.logger.info( "Upload a new mark file in the submission {}".format( submission_id ) )
    
    try:
        dek_check( submission_id )
        
        sql = """
            SELECT email_aes as email, nickname, created_time, consent_form
            FROM submissions
            WHERE submitter_id = %s AND uuid = %s
        """
        user = config.db.query_fetchone( sql, ( session[ "user_id" ], submission_id ) )
        
        if user[ "consent_form" ]:
            current_app.logger.debug( "The donor has a consent form" )
            current_app.logger.info( "Serving the add new file page" )
            
            for key in [ "email", "nickname" ]:
                user[ key ] = do_decrypt_user_session( user[ key ] )
            
            finger_names = []
            for laterality in [ "Right", "Left" ]:
                for finger in [ "thumb", "index", "middle", "ring", "little" ]:
                    finger_names.append( "{} {}".format( laterality, finger ) )
            
            return my_render_template( 
                "submission/add_marks_by_finger.html",
                submission_id = submission_id,
                finger_names = finger_names,
                user = user
            )
        else:
            current_app.logger.debug( "The donor dont have a consent form in the database" )
            current_app.logger.info( "Serving the consent form upload page" )
            
            return redirect( url_for( "submission.submission_consent_form", submission_id = submission_id ) )
        
    except:
        return jsonify( {
            "error": True,
            "message": "Case not found"
        } )

@submission_view.route( "/submission/<submission_id>/consent_form" )
@submission_has_access
def submission_consent_form( submission_id ):
    """
        Serve the page to upload the consent form for the user.
    """
    current_app.logger.info( "Serve the consent form upload page" )
    
    sql = """
        SELECT email_aes as email, nickname, created_time
        FROM submissions
        WHERE submitter_id = %s AND uuid = %s
    """
    user = config.db.query_fetchone( sql, ( session[ "user_id" ], submission_id ) )
    
    if user != None:
        for key in [ "email", "nickname" ]:
            user[ key ] = do_decrypt_user_session( user[ key ] )
        
        return my_render_template( 
            "submission/consent_form.html",
            submission_id = submission_id,
            **user
        )
    
    else:
        current_app.logger.error( "Submission not found" )
        return abort( 404 )

@submission_view.route( "/submission/<submission_id>/gp" )
@submission_has_access
def submission_gp( submission_id ):
    """
        Serve the page to upload the general pattern for a donor.
    """
    current_app.logger.info( "Serve the page to set the GP for {}".format( submission_id ) )
    
    finger_names = []
    for laterality in [ "Right", "Left" ]:
        for finger in [ "thumb", "index", "middel", "ring", "little" ]:
            finger_names.append( "{} {}".format( laterality, finger ) )
    
            "div_name": "ll",
            "name": "left loop"
        },
        {
            "div_name": "rl",
            "name": "right loop"
        },
        {
            "div_name": "whorl",
            "name": "whorl"
        },
        {
            "div_name": "arch",
            "name": "arch"
        },
        {
            "div_name": "cpl",
            "name": "central pocket loop"
        },
        {
            "div_name": "dl",
            "name": "double loop"
        },
        {
            "div_name": "ma",
            "name": "missing/amputated"
        },
        {
            "div_name": "sm",
            "name": "scarred/mutilated"
        },
        {
            "div_name": "unknown",
            "name": "unknown"
        }
    ]
        sql = """
            SELECT donor_fingers_gp.fpc, gp.div_name, gp.name
            FROM donor_fingers_gp
            LEFT JOIN submissions ON donor_fingers_gp.donor_id = submissions.donor_id
            LEFT JOIN gp ON donor_fingers_gp.gp = gp.id
            WHERE submissions.uuid = %s AND donor_fingers_gp.fpc <= 10
        """
        current_gp = config.db.query_fetchall( sql, ( submission_id, ) )
        
        dek_check( submission_id )
        
        sql = """
            SELECT email_aes as email, nickname, created_time, consent_form
            FROM submissions
            WHERE submitter_id = %s AND uuid = %s
        """
        user = config.db.query_fetchone( sql, ( session[ "user_id" ], submission_id ) )
        
        for key in [ "email", "nickname" ]:
            user[ key ] = do_decrypt_user_session( user[ key ] )
        
        return my_render_template( 
            "submission/set_gp.html",
            submission_id = submission_id,
            finger_names = finger_names,
            gp_list = gp_list,
        )
    
    except:
        return jsonify( {
            "error": True,
            "message": "Case not found"
        } )

@submission_view.route( "/submission/<submission_id>/set/nickname", methods = [ "POST" ] )
@submission_has_access
def submission_update_nickname( submission_id ):
    """
        Change the nickname of the donor in the database.

        THIS INFORMATION SHALL BE ENCRYPTED ON THE CLIENT SIDE FIRST WITH A UNIQUE
        ENCRYPTION KEY NOT TRANSMETTED TO THE SERVER!
    """
    current_app.logger.info( "Save the donor nickname to the database" )
    
    nickname = request.form.get( "nickname", None )
    
    if nickname != None and len( nickname ) != 0:
        try:
            nickname = do_encrypt_user_session( nickname )
            
            sql = "UPDATE submissions SET nickname = %s WHERE uuid = %s"
            config.db.query( sql, ( nickname, submission_id, ) )
            config.db.commit()
            
            return jsonify( {
                "error": False
            } )
        
        except:
            current_app.logger.error( "Database error" )
            return jsonify( {
                "error": True,
                "message": "DB error"
            } )
    
    else:
        current_app.logger.error( "No nickname in the post request" )
        return jsonify( {
            "error": True,
            "message": "No new nickname in the POST request"
        } )

@submission_view.route( "/submission/list" )
@submission_has_access
def submission_list():
    """
        Get the list of all submissions folder for the currently logged submitter.
    """
    current_app.logger.info( "Get all submissions for '{}'".format( session[ "username" ] ) )
    
    sql = "SELECT * FROM submissions WHERE submitter_id = %s ORDER BY created_time DESC"
    q = config.db.query_fetchall( sql, ( session[ "user_id" ], ) )
    
    donors = []
    for donor in q:
        donors.append( {
            "nickname": do_decrypt_user_session( donor.get( "nickname", None ) ),
            "uuid": donor.get( "uuid", None )
        } )
        current_app.logger.debug( "uuid: {}".format( donor[ "uuid" ] ) )
    
    current_app.logger.info( "{} submissions found".format( len( donors ) ) )
    
    return my_render_template( 
        "submission/list.html",
        donors = donors
    )

@submission_view.route( "/submission/<submission_id>/mark/list" )
@submission_view.route( "/submission/<submission_id>/mark/list/<mark_type>" )
@submission_has_access
def submission_mark_list( submission_id, mark_type = "all" ):
    """
        Get the list of mark for a particular submission folder.
    """
    current_app.logger.info( "Get the list of mark for the submission '{}'".format( submission_id ) )
    current_app.logger.debug( "mark_type: {}".format( mark_type ) )
    
    if mark_type in [ "target", "incidental", "all" ]:
        sql = "SELECT id, nickname FROM submissions WHERE uuid = %s"
        case_id, nickname = config.db.query_fetchone( sql, ( submission_id, ) )
        nickname = do_decrypt_user_session( nickname )
        
        sql = """
            SELECT files.id, files.uuid, files.filename, files.size, files.creation_time
            FROM files
            LEFT JOIN files_type ON files.type = files_type.id
            WHERE folder = %s AND
        """
        if mark_type == "target":
            sql += " files_type.name = 'mark_target'"
        elif mark_type == "incidental":
            sql += " files_type.name = 'mark_incidental'"
        elif mark_type == "all":
            sql += " ( files_type.name = 'mark_target' OR files_type.name = 'mark_incidental' )"
        
        sql += " ORDER BY files.id DESC"
        files = config.db.query_fetchall( sql, ( case_id, ) )
        
        for _, v in enumerate( files ):
            v[ "filename" ] = do_decrypt_user_session( v[ "filename" ] )
            v[ "size" ] = round( ( float( v[ "size" ] ) / ( 1024 * 1024 ) ) * 100 ) / 100
        
        current_app.logger.debug( "{} marks for '{}'".format( len( files ), submission_id ) )
        
        return my_render_template( 
            submission_id = submission_id,
            mark_type = mark_type,
            files = files,
        )
    
    else:
        return abort( 403 )

@submission_view.route( "/submission/<submission_id>/mark/<mark_id>" )
@submission_has_access
def submission_mark( submission_id, mark_id ):
    """
        Serve the page to edit a particular mark image.
    """
    current_app.logger.info( "Serve the mark page edit" )
    current_app.logger.debug( "submission {}".format( submission_id ) )
    current_app.logger.debug( "mark {}".format( mark_id ) )
    
    sql = "SELECT id, nickname FROM submissions WHERE uuid = %s"
    submission_folder_id, nickname = config.db.query_fetchone( sql, ( submission_id, ) )
    nickname = do_decrypt_user_session( nickname )
    
    sql = """
        SELECT
            files.uuid, files.filename, files.note,
            files.format, files.resolution, files.width, files.height, files.size,
            files.creation_time, files.type,
            files_type.name as file_type
        
        FROM files
        LEFT JOIN files_type ON files.type = files_type.id
        WHERE
            folder = %s AND
            files.uuid = %s
    """
    
    mark = config.db.query_fetchone( sql, ( submission_folder_id, mark_id, ) )
    mark[ "size" ] = round( 100 * float( mark[ "size" ] ) / ( 1024 * 1024 ) ) / 100
    mark[ "filename" ] = do_decrypt_user_session( mark[ "filename" ] )
    mark[ "file_type" ] = mark[ "file_type" ].replace( "mark_", "" )
    
    sql = "SELECT * FROM detection_technics ORDER BY name ASC"
    all_detection_tetchnics = config.db.query_fetchall( sql )
    sql = "SELECT * FROM surfaces ORDER BY name ASC"
    all_surfaces = config.db.query_fetchall( sql )
    sql = "SELECT * FROM activities ORDER BY name ASC"
    all_activities = config.db.query_fetchall( sql )

    sql = "SELECT * FROM distortion ORDER BY name ASC"
    all_distortions = config.db.query_fetchall( sql )

    try:
        sql = "SELECT detection_technic FROM mark_info WHERE uuid = %s"
        detection_technics = config.db.query_fetchone( sql, ( mark_id, ) )[ "detection_technic" ]
        
        for old in "{}'":
            detection_technics = detection_technics.replace( old, "" )
        detection_technics = detection_technics.split( "," )
    except:
        detection_technics = []
    
    try:
        sql = "SELECT surface FROM mark_info WHERE uuid = %s"
        surface = config.db.query_fetchone( sql, ( mark_id, ) )[ "surface" ]
        
        for old in "{}'":
            surface = surface.replace( old, "" )
        surface = surface.split( "," )
    except:
        surface = []
    
    try:
        sql = "SELECT activity FROM mark_info WHERE uuid = %s"
        activity = config.db.query_fetchone( sql, ( mark_id, ) )[ "activity" ]
        
        for old in "{}'":
            activity = activity.replace( old, "" )
        activity = activity.split( "," )
    except:
        activity = []
    
    try:
        sql = "SELECT distortion FROM mark_info WHERE uuid = %s"
        distortion = config.db.query_fetchone( sql, ( mark_id, ) )[ "distortion" ]
        
        for old in "{}'":
            distortion = distortion.replace( old, "" )
        distortion = distortion.split( "," )
    except:
        distortion = []
    
    return my_render_template(
        "submission/mark.html",
        submission_id = submission_id,
        nickname = nickname,
        all_detection_technics = all_detection_tetchnics,
        all_surfaces = all_surfaces,
        all_activities = all_activities,
        all_distortions = all_distortions,
        detection_technics = detection_technics,
        surface = surface,
        activity = activity,
        distortion = distortion
    )

@submission_view.route( "/submission/<submission_id>/mark/<mark_id>/pfsp" )
@submission_has_access
def submission_mark_pfsp( submission_id, mark_id ):
    """
        Serve the page to set the PFSP information (location on the finger
        or the palm print) for the mark.
    """
    current_app.logger.info( "Serve the PFSP edit page" )
    current_app.logger.debug( "submission {}".format( submission_id ) )
    current_app.logger.debug( "mark {}".format( mark_id ) )
    
    sql = "SELECT id, nickname FROM submissions WHERE uuid = %s"
    submission_folder_id, nickname = config.db.query_fetchone( sql, ( submission_id, ) )
    nickname = do_decrypt_user_session( nickname )
    
    sql = """
        SELECT
            files.uuid, files.filename, files.note,
            files.format, files.resolution, files.width, files.height, files.size,
            files.creation_time, files.type,
            files_type.name as file_type
        
        FROM files
        LEFT JOIN files_type ON files.type = files_type.id
        WHERE
            folder = %s AND
            files.uuid = %s
    """
    
    mark = config.db.query_fetchone( sql, ( submission_folder_id, mark_id, ) )
    mark[ "size" ] = round( 100 * float( mark[ "size" ] ) / ( 1024 * 1024 ) ) / 100
    mark[ "filename" ] = do_decrypt_user_session( mark[ "filename" ] )
    mark[ "note" ] = do_decrypt_user_session( mark[ "note" ] )
    mark[ "file_type" ] = mark[ "file_type" ].replace( "mark_", "" )
    
    current_app.logger.debug( "file size: {}Mo".format( mark[ "size" ] ) )
    
    sql = "SELECT pfsp FROM mark_info WHERE uuid = %s"
    try:
        current_pfsp = config.db.query_fetchone( sql, ( mark_id, ) )[ "pfsp" ]
    except:
        current_pfsp = None
    
    current_app.logger.debug( "Current PFSP: {}".format( current_pfsp ) )
    
    for z in pfsp.zones:
        if z[ "desc" ] == current_pfsp:
            current_pfsp = ",".join( z[ "sel" ] )
    
    return my_render_template( 
        "submission/mark_pfsp.html",
        submission_id = submission_id,
        nickname = nickname,
        file = mark,
        pfsp_zones = pfsp.zones,
        current_pfsp = current_pfsp
    )

@submission_view.route( "/submission/<submission_id>/mark/<mark_id>/set/pfsp", methods = [ "POST" ] )
@submission_has_access
def submission_mark_pfsp_set( submission_id, mark_id ):
    """
        Save the PFSP information relative to a mark.
    """
    current_app.logger.info( "Save the PFSP for submission '{}' mark '{}'".format( submission_id, mark_id ) )
    
    try:
        pfsp = request.form.get( "pfsp" )
        pfsp = ",".join( [ p for p in pfsp.split( "," ) if p != "None" ] )
        
        sql = "SELECT id FROM mark_info WHERE uuid = %s"
        q = config.db.query_fetchone( sql, ( mark_id, ) )
        
        if q == None:
            sql = utils.sql.sql_insert_generate( "mark_info", [ "uuid", "pfsp" ] )
            config.db.query( sql, ( mark_id, pfsp, ) )
        
        else:
            sql = "UPDATE mark_info SET pfsp = %s WHERE uuid = %s"
            config.db.query( sql, ( pfsp, mark_id, ) )
        
        config.db.commit()
        
        return jsonify( {
            "error": False
        } )
    
    except:
        return jsonify( {
            "error": True
        } )

@submission_view.route( "/submission/<submission_id>/mark/<mark_id>/set/<field>", methods = [ "POST" ] )
@submission_has_access
def submission_mark_set_field( submission_id, mark_id, field ):
        Set the data related to the <field> (detection technic, surface, ...) for a fingermark.
        "detection": "detection_technic",
        "activity": "activity",
        "distortion": "distortion"
    }
    field = corr.get( field, False )
    
    if field != False:
        current_app.logger.info( "Save the {} for submission '{}' mark '{}'".format( field, submission_id, mark_id ) )
        
        dt = json.loads( request.form.get( "value" ) )
        
        sql = "SELECT id FROM mark_info WHERE uuid = %s"
        q = config.db.query_fetchone( sql, ( mark_id, ) )
        
        if q == None:
            sql = utils.sql.sql_insert_generate( "mark_info", [ "uuid", field ] )
            config.db.query( sql, ( mark_id, dt, ) )
        
        else:
            sql = "UPDATE mark_info SET {} = %s WHERE uuid = %s".format( field )
            config.db.query( sql, ( dt, mark_id, ) )
        
        config.db.commit()
        
        return jsonify( {
            "error": False
        } )
        return jsonify( {