'Form validation for both, documents and images'

@staticmethod
def document_onvalidation(form, document=True):

    form_vars = form.vars
    doc = form_vars.file
    if (doc is None):
        return
    if (not document):
        encoded_file = form_vars.get('imagecrop-data', None)
        if encoded_file:
            import base64
            import uuid
            (metadata, encoded_file) = encoded_file.split(',')
            (filename, datatype, enctype) = metadata.split(';')
            f = Storage()
            f.filename = (uuid.uuid4().hex + filename)
            import cStringIO
            f.file = cStringIO.StringIO(base64.decodestring(encoded_file))
            doc = form_vars.file = f
            if (not form_vars.name):
                form_vars.name = filename
    if ((not hasattr(doc, 'file')) and (not doc) and (not form_vars.url)):
        if document:
            msg = current.T('Either    file    upload    or    document    URL    required.')
        else:
            msg = current.T('Either    file    upload    or    image    URL    required.')
        form.errors.file = msg
        form.errors.url = msg
    if hasattr(doc, 'file'):
        name = form_vars.name
        if (not name):
            form_vars.name = doc.filename
    else:
        id = current.request.post_vars.id
        if id:
            if document:
                tablename = 'doc_document'
            else:
                tablename = 'doc_image'
            db = current.db
            table = db[tablename]
            record = db((table.id == id)).select(table.file, limitby=(0, 1)).first()
            if record:
                name = form_vars.name
                if (not name):
                    form_vars.name = table.file.retrieve(record.file)[0]
