def get_pid_from_uid(uid):
    '''
    Return the PID associated with the uid

    @param uid: the internal ID of a user
    @type uid: int

    @return: the Person ID attached to the user or -1 if none found
    '''
    if not isinstance(uid, tuple):
        uid = ((uid,),)

    return dbapi.get_personid_from_uid(uid)
def get_pid_from_uid(uid):
    '''
    Return the PID associated with the uid

    @param uid: the internal ID of a user
    @type uid: int

    @return: the Person ID attached to the user or -1 if none found
    '''
    if not isinstance(uid, tuple):
        uid = ((uid,),)

    return dbapi.get_personid_from_uid(uid)
def check_transaction_permissions(uid, bibref, pid, action):
    '''
    Check if the user can perform the given action on the given pid,bibrefrec pair.
    return in: granted, denied, warning_granted, warning_denied

    @param uid: The internal ID of a user
    @type uid: int
    @param bibref: the bibref pair to check permissions for
    @type bibref: string
    @param pid: the Person ID to check on
    @type pid: int
    @param action: the action that is to be performed
    @type action: string

    @return: granted, denied, warning_granted xor warning_denied
    @rtype: string
    '''
    c_own = True
    c_override = False
    is_superadmin = isUserSuperAdmin({'uid': uid})

    access_right = _resolve_maximum_acces_rights(uid)
    bibref_status = dbapi.get_bibref_modification_status(bibref)
    old_flag = bibref_status[0]

    if old_flag == 2 or old_flag == -2:
        if action in ['confirm', 'assign']:
            new_flag = 2
        elif action in ['repeal']:
            new_flag = -2
        elif action in ['reset']:
            new_flag = 0
        if old_flag != new_flag:
            c_override = True

    uid_pid = dbapi.get_personid_from_uid([[uid]])
    if not uid_pid[1] or pid != uid_pid[0][0]:
        c_own = False

    #if we cannot override an already touched bibref, no need to go on checking
    if c_override:
        if is_superadmin:
            return 'warning_granted'
        if access_right[1] < bibref_status[1]:
            return "warning_denied"
    else:
        if is_superadmin:
            return 'granted'

    #let's check if invenio is allowing us the action we want to perform
    if c_own:
        action = bconfig.CLAIMPAPER_CLAIM_OWN_PAPERS
    else:
        action = bconfig.CLAIMPAPER_CLAIM_OTHERS_PAPERS
    auth = acc_authorize_action(uid, action)
    if auth[0] != 0:
        return "denied"

    #now we know if claiming for ourselfs, we can ask for external ideas
    if c_own:
        action = 'claim_own_paper'
    else:
        action = 'claim_other_paper'

    ext_permission = external_user_can_perform_action(uid)

    #if we are here invenio is allowing the thing and we are not overwriting a
    #user with higher privileges, if externals are ok we go on!
    if ext_permission:
        if not c_override:
            return "granted"
        else:
            return "warning_granted"

    return "denied"
def arxiv_login(req, picked_profile=None):
    '''
    Log in through arxive. If user already associated to a personid, returns the personid.
    If user has no pid, try to guess which personid to associate based on surname and papers
    from arxiv. If no compatible person is found, creates a new person.
    At the end of the process opens a ticket for the user claiming the papers from arxiv.
    !!! the user will find the open ticket, which will require him to go through the
    final review before getting committed.

    @param req: Apache request object
    @type req: Apache request object

    @return: Returns the pid resulting in the process
    @rtype: int
    '''
    def session_bareinit(req):
        session = get_session(req)
        try:
            pinfo = session["personinfo"]
            if 'ticket' not in pinfo:
                pinfo["ticket"] = []
        except KeyError:
            pinfo = dict()
            session['personinfo'] = pinfo
            pinfo["ticket"] = []
        session.dirty = True




    session_bareinit(req)
    session = get_session(req)

    pinfo = session['personinfo']
    ticket = session['personinfo']['ticket']

    uinfo = collect_user_info(req)
    pinfo['external_first_entry'] = False

    try:
        name = uinfo['external_firstname']
    except KeyError:
        name = ''
    try:
        surname = uinfo['external_familyname']
    except KeyError:
        surname = ''

    if surname:
        session['personinfo']['arxiv_name'] = nameapi.create_normalized_name(
                                          nameapi.split_name_parts(surname + ', ' + name))
    else:
        session['personinfo']['arxiv_name'] = ''

    session.dirty = True

    try:
        arxiv_p_ids = uinfo['external_arxivids'].split(';')
    except KeyError:
        arxiv_p_ids = []

    #'external_arxivids': 'hep-th/0112017;hep-th/0112020',
    #'external_familyname': 'Weiler',
    #'external_firstname': 'Henning',

    try:
        found_bibrecs = set(reduce(add, [perform_request_search(p='037:' + str(arx), of='id', rg=0)for arx in arxiv_p_ids]))
    except (IndexError, TypeError):
        found_bibrecs = set()

    #found_bibrecs = [567700, 567744]

    uid = getUid(req)
    pid, pid_found = dbapi.get_personid_from_uid([[uid]])

    if pid_found:
        pid = pid[0]
    else:
        if picked_profile == None:
            top5_list = dbapi.find_top5_personid_for_new_arXiv_user(found_bibrecs,
                nameapi.create_normalized_name(nameapi.split_name_parts(surname + ', ' + name)))
            return ("top5_list", top5_list)
        else:
            pid = dbapi.check_personids_availability(picked_profile, uid)

    pid_bibrecs = set([i[0] for i in dbapi.get_all_personids_recs(pid, claimed_only=True)])
    missing_bibrecs = found_bibrecs - pid_bibrecs
    #present_bibrecs = found_bibrecs.intersection(pid_bibrecs)

    #assert len(found_bibrecs) == len(missing_bibrecs) + len(present_bibrecs)

    tempticket = []
    #now we have to open the tickets...
    #person_papers contains the papers which are already assigned to the person and came from arxive,
    #they can be claimed regardless

    for bibrec in missing_bibrecs:
        tempticket.append({'pid':pid, 'bibref':str(bibrec), 'action':'confirm'})

    #check if ticket targets (bibref for pid) are already in ticket
    for t in list(tempticket):
        for e in list(ticket):
            if e['pid'] == t['pid'] and e['bibref'] == t['bibref']:
                ticket.remove(e)
        ticket.append(t)

    session.dirty = True

    if picked_profile != None and picked_profile != pid and picked_profile != -1:

        return ("chosen pid not available", pid)
    elif picked_profile != None and picked_profile == pid and picked_profile != -1:
        return ("pid assigned by user", pid)
    else:
        return ("pid", pid)
def arxiv_login(req, picked_profile=None):
    '''
    Log in through arxive. If user already associated to a personid, returns the personid.
    If user has no pid, try to guess which personid to associate based on surname and papers
    from arxiv. If no compatible person is found, creates a new person.
    At the end of the process opens a ticket for the user claiming the papers from arxiv.
    !!! the user will find the open ticket, which will require him to go through the
    final review before getting committed.

    @param req: Apache request object
    @type req: Apache request object

    @return: Returns the pid resulting in the process
    @rtype: int
    '''
    def session_bareinit(req):
        session = get_session(req)
        try:
            pinfo = session["personinfo"]
            if 'ticket' not in pinfo:
                pinfo["ticket"] = []
        except KeyError:
            pinfo = dict()
            session['personinfo'] = pinfo
            pinfo["ticket"] = []
        session.dirty = True




    session_bareinit(req)
    session = get_session(req)

    pinfo = session['personinfo']
    ticket = session['personinfo']['ticket']

    uinfo = collect_user_info(req)
    pinfo['external_first_entry'] = False

    try:
        name = uinfo['external_firstname']
    except KeyError:
        name = ''
    try:
        surname = uinfo['external_familyname']
    except KeyError:
        surname = ''

    if surname:
        session['personinfo']['arxiv_name'] = nameapi.create_normalized_name(
                                          nameapi.split_name_parts(surname + ', ' + name))
    else:
        session['personinfo']['arxiv_name'] = ''

    session.dirty = True

    try:
        arxiv_p_ids = uinfo['external_arxivids'].split(';')
    except KeyError:
        arxiv_p_ids = []

    #'external_arxivids': 'hep-th/0112017;hep-th/0112020',
    #'external_familyname': 'Weiler',
    #'external_firstname': 'Henning',

    try:
        found_bibrecs = set(reduce(add, [perform_request_search(p='037:' + str(arx), of='id', rg=0)for arx in arxiv_p_ids]))
    except (IndexError, TypeError):
        found_bibrecs = set()

    #found_bibrecs = [567700, 567744]

    uid = getUid(req)
    pid, pid_found = dbapi.get_personid_from_uid([[uid]])

    if pid_found:
        pid = pid[0]
    else:
        if picked_profile == None:
            top5_list = dbapi.find_top5_personid_for_new_arXiv_user(found_bibrecs,
                nameapi.create_normalized_name(nameapi.split_name_parts(surname + ', ' + name)))
            return ("top5_list", top5_list)
        else:
            pid = dbapi.check_personids_availability(picked_profile, uid)

    pid_bibrecs = set([i[0] for i in dbapi.get_all_personids_recs(pid, claimed_only=True)])
    missing_bibrecs = found_bibrecs - pid_bibrecs
    #present_bibrecs = found_bibrecs.intersection(pid_bibrecs)

    #assert len(found_bibrecs) == len(missing_bibrecs) + len(present_bibrecs)

    tempticket = []
    #now we have to open the tickets...
    #person_papers contains the papers which are already assigned to the person and came from arxive,
    #they can be claimed regardless

    for bibrec in missing_bibrecs:
        tempticket.append({'pid':pid, 'bibref':str(bibrec), 'action':'confirm'})

    #check if ticket targets (bibref for pid) are already in ticket
    for t in list(tempticket):
        for e in list(ticket):
            if e['pid'] == t['pid'] and e['bibref'] == t['bibref']:
                ticket.remove(e)
        ticket.append(t)

    session.dirty = True

    if picked_profile != None and picked_profile != pid and picked_profile != -1:

        return ("chosen pid not available", pid)
    elif picked_profile != None and picked_profile == pid and picked_profile != -1:
        return ("pid assigned by user", pid)
    else:
        return ("pid", pid)
def check_transaction_permissions(uid, bibref, pid, action):
    '''
    Check if the user can perform the given action on the given pid,bibrefrec pair.
    return in: granted, denied, warning_granted, warning_denied

    @param uid: The internal ID of a user
    @type uid: int
    @param bibref: the bibref pair to check permissions for
    @type bibref: string
    @param pid: the Person ID to check on
    @type pid: int
    @param action: the action that is to be performed
    @type action: string

    @return: granted, denied, warning_granted xor warning_denied
    @rtype: string
    '''
    c_own = True
    c_override = False
    is_superadmin = isUserSuperAdmin({'uid': uid})

    access_right = _resolve_maximum_acces_rights(uid)
    bibref_status = dbapi.get_bibref_modification_status(bibref)
    old_flag = bibref_status[0]

    if old_flag == 2 or old_flag == -2:
        if action in ['confirm', 'assign']:
            new_flag = 2
        elif action in ['repeal']:
            new_flag = -2
        elif action in ['reset']:
            new_flag = 0
        if old_flag != new_flag:
            c_override = True

    uid_pid = dbapi.get_personid_from_uid([[uid]])
    if not uid_pid[1] or pid != uid_pid[0][0]:
        c_own = False

    #if we cannot override an already touched bibref, no need to go on checking
    if c_override:
        if is_superadmin:
            return 'warning_granted'
        if access_right[1] < bibref_status[1]:
            return "warning_denied"
    else:
        if is_superadmin:
            return 'granted'

    #let's check if invenio is allowing us the action we want to perform
    if c_own:
        action = bconfig.CLAIMPAPER_CLAIM_OWN_PAPERS
    else:
        action = bconfig.CLAIMPAPER_CLAIM_OTHERS_PAPERS
    auth = acc_authorize_action(uid, action)
    if auth[0] != 0:
        return "denied"

    #now we know if claiming for ourselfs, we can ask for external ideas
    if c_own:
        action = 'claim_own_paper'
    else:
        action = 'claim_other_paper'

    ext_permission = external_user_can_perform_action(uid)

    #if we are here invenio is allowing the thing and we are not overwriting a
    #user with higher privileges, if externals are ok we go on!
    if ext_permission:
        if not c_override:
            return "granted"
        else:
            return "warning_granted"

    return "denied"
def arxiv_login(req):
    '''
    Log in through arxive. If user already associated to a personid, returns the personid.
    If user has no pid, try to guess which personid to associate based on surname and papers
    from arxiv. If no compatible person is found, creates a new person.
    At the end of the process opens a ticket for the user claiming the papers from arxiv.
    !!! the user will find the open ticket, which will require him to go through the
    final review before getting committed.

    @param req: Apache request object
    @type req: Apache request object

    @return: Returns the pid resulting in the process
    @rtype: int
    '''
    def session_bareinit(req):
        session = get_session(req)
        try:
            pinfo = session["personinfo"]
            if 'ticket' not in pinfo:
                pinfo["ticket"] = []
        except KeyError:
            pinfo = dict()
            session['personinfo'] = pinfo
            pinfo["ticket"] = []
        session.save()

    session_bareinit(req)
    session = get_session(req)
    pinfo = session['personinfo']
    ticket = session['personinfo']['ticket']

    uinfo = collect_user_info(req)
    pinfo['external_first_entry'] = True
    session.save()

    arxiv_p_ids = []
    name = ''
    surname = ''
    try:
        for i in uinfo['external_arxivids'].split(';'):
            arxiv_p_ids.append(i)
        name = uinfo['external_firstname']
        surname = uinfo['external_familyname']
    #'external_arxivids': 'hep-th/0112017;hep-th/0112020',
    #'external_familyname': 'Weiler',
    #'external_firstname': 'Henning',
    except KeyError:
        pass

    found_bibrecs = []
    for arx in arxiv_p_ids:
        t = search_engine.perform_request_search(p='037:' + str(arx), of='id')
        for i in t:
            found_bibrecs.append(i)
    #found_bibrecs = [567700, 567744]

    uid = getUid(req)
    pid = dbapi.get_personid_from_uid([[uid]])
    if pid[1]:
        pid_bibrecs = dbapi.get_all_personids_recs(pid[0][0])
        pid_bibrecs = set(pid_bibrecs)
        missing_bibrecs = [bib for bib in found_bibrecs if int(bib) not in pid_bibrecs]
        found_bibrecs = [bib for bib in found_bibrecs if int(bib) in pid_bibrecs]
    else:
        missing_bibrecs = []

    bibrec_names = []
    for b in found_bibrecs + missing_bibrecs:
        bibrec_names.append([b, get_field_values_on_condition(b, source='API', get_table=['100', '700'], get_tag='a')])

    for n in list(bibrec_names):
        for i in list(n[1]):
            if nameapi.soft_compare_names(surname, i.encode('utf-8')) < 0.45:
                n[1].remove(i)
    #bibrec_names = [[78, set([u'M\xfcck, W'])]]

    #what is left are only suitable names for each record.
    bibrefrecs = []

    for bibrec in bibrec_names:
        for name in bibrec[1]:
            bibrefs = dbapi.get_bibrefs_from_name_string(name.encode('utf-8'))
            if len(bibrefs) < 1:
                continue
            for bibref in bibrefs[0][0].split(','):
                bibrefrecs.append(str(bibref) + ',' + str(bibrec[0]))
    #bibrefrecs = ['100:116,78', '700:505,78']

    person_papers = []
    if not pid[1]:
        brr = [[i] for i in bibrefrecs]
        possible_persons = dbapi.get_possible_personids_from_paperlist(brr)
        #[[0L, ['700:316,10']]]
        possible_persons = sorted(possible_persons, key=lambda k: len(k[1]))

        if len(possible_persons) > 1:
            for pp in possible_persons:
                pid = dbapi.assign_person_to_uid(uid, pp[0])
                person_papers = pp[1]
                if pid != -1:
                    break
            if pid == -1:
                pid = dbapi.assign_person_to_uid(uid, -1)
        elif len(possible_persons) == 1:
            pid = dbapi.assign_person_to_uid(uid, possible_persons[0][0])
            person_papers = possible_persons[0][1]
        else:
            pid = dbapi.assign_person_to_uid(uid, -1)
    else:
        pid = long(pid[0][0])

    tempticket = []
    #now we have to open the tickets...
    #person_papers contains the papers which are already assigned to the person and came from arxive,
    #they can be claimed regardless
    for bibref in person_papers:
        tempticket.append({'pid':pid, 'bibref':bibref, 'action':'confirm'})

    done_bibrecs = set(b.split(',')[1] for b in person_papers)
    for b in found_bibrecs + missing_bibrecs:
        if str(b) not in done_bibrecs:
            tempticket.append({'pid':pid, 'bibref':str(b), 'action':'confirm'})

    #check if ticket targets (bibref for pid) are already in ticket
    for t in list(tempticket):
        for e in list(ticket):
            if e['pid'] == t['pid'] and e['bibref'] == t['bibref']:
                ticket.remove(e)
        ticket.append(t)
    session.save()
    return pid
Beispiel #8
0
def arxiv_login(req):
    '''
    Log in through arxive. If user already associated to a personid, returns the personid.
    If user has no pid, try to guess which personid to associate based on surname and papers
    from arxiv. If no compatible person is found, creates a new person.
    At the end of the process opens a ticket for the user claiming the papers from arxiv.
    !!! the user will find the open ticket, which will require him to go through the
    final review before getting committed.

    @param req: Apache request object
    @type req: Apache request object

    @return: Returns the pid resulting in the process
    @rtype: int
    '''
    def session_bareinit(req):
        session = get_session(req)
        try:
            pinfo = session["personinfo"]
            if 'ticket' not in pinfo:
                pinfo["ticket"] = []
        except KeyError:
            pinfo = dict()
            session['personinfo'] = pinfo
            pinfo["ticket"] = []
        session.save()

    session_bareinit(req)
    session = get_session(req)
    pinfo = session['personinfo']
    ticket = session['personinfo']['ticket']

    uinfo = collect_user_info(req)
    pinfo['external_first_entry'] = True
    session.save()

    arxiv_p_ids = []
    name = ''
    surname = ''
    try:
        for i in uinfo['external_arxivids'].split(';'):
            arxiv_p_ids.append(i)
        name = uinfo['external_firstname']
        surname = uinfo['external_familyname']
    #'external_arxivids': 'hep-th/0112017;hep-th/0112020',
    #'external_familyname': 'Weiler',
    #'external_firstname': 'Henning',
    except KeyError:
        pass

    found_bibrecs = []
    for arx in arxiv_p_ids:
        t = search_engine.perform_request_search(p='037:' + str(arx), of='id')
        for i in t:
            found_bibrecs.append(i)
    #found_bibrecs = [567700, 567744]

    uid = getUid(req)
    pid = dbapi.get_personid_from_uid([[uid]])
    if pid[1]:
        pid_bibrecs = dbapi.get_all_personids_recs(pid[0][0])
        pid_bibrecs = set(pid_bibrecs)
        missing_bibrecs = [
            bib for bib in found_bibrecs if int(bib) not in pid_bibrecs
        ]
        found_bibrecs = [
            bib for bib in found_bibrecs if int(bib) in pid_bibrecs
        ]
    else:
        missing_bibrecs = []

    bibrec_names = []
    for b in found_bibrecs + missing_bibrecs:
        bibrec_names.append([
            b,
            get_field_values_on_condition(b,
                                          source='API',
                                          get_table=['100', '700'],
                                          get_tag='a')
        ])

    for n in list(bibrec_names):
        for i in list(n[1]):
            if nameapi.soft_compare_names(surname, i.encode('utf-8')) < 0.45:
                n[1].remove(i)
    #bibrec_names = [[78, set([u'M\xfcck, W'])]]

    #what is left are only suitable names for each record.
    bibrefrecs = []

    for bibrec in bibrec_names:
        for name in bibrec[1]:
            bibrefs = dbapi.get_bibrefs_from_name_string(name.encode('utf-8'))
            if len(bibrefs) < 1:
                continue
            for bibref in bibrefs[0][0].split(','):
                bibrefrecs.append(str(bibref) + ',' + str(bibrec[0]))
    #bibrefrecs = ['100:116,78', '700:505,78']

    person_papers = []
    if not pid[1]:
        brr = [[i] for i in bibrefrecs]
        possible_persons = dbapi.get_possible_personids_from_paperlist(brr)
        #[[0L, ['700:316,10']]]
        possible_persons = sorted(possible_persons, key=lambda k: len(k[1]))

        if len(possible_persons) > 1:
            for pp in possible_persons:
                pid = dbapi.assign_person_to_uid(uid, pp[0])
                person_papers = pp[1]
                if pid != -1:
                    break
            if pid == -1:
                pid = dbapi.assign_person_to_uid(uid, -1)
        elif len(possible_persons) == 1:
            pid = dbapi.assign_person_to_uid(uid, possible_persons[0][0])
            person_papers = possible_persons[0][1]
        else:
            pid = dbapi.assign_person_to_uid(uid, -1)
    else:
        pid = long(pid[0][0])

    tempticket = []
    #now we have to open the tickets...
    #person_papers contains the papers which are already assigned to the person and came from arxive,
    #they can be claimed regardless
    for bibref in person_papers:
        tempticket.append({'pid': pid, 'bibref': bibref, 'action': 'confirm'})

    done_bibrecs = set(b.split(',')[1] for b in person_papers)
    for b in found_bibrecs + missing_bibrecs:
        if str(b) not in done_bibrecs:
            tempticket.append({
                'pid': pid,
                'bibref': str(b),
                'action': 'confirm'
            })

    #check if ticket targets (bibref for pid) are already in ticket
    for t in list(tempticket):
        for e in list(ticket):
            if e['pid'] == t['pid'] and e['bibref'] == t['bibref']:
                ticket.remove(e)
        ticket.append(t)
    session.save()
    return pid