Hmmmm. It's all a big mess.
Once the new code is in, you can just do
- get_my_courses() on the "looked-at" user (which will fetch the courses with a handy context obj)
- loop over those and ask if the looking user has_capability() over each of those course contexts
This will only take into account "shared course contexts", this will incur in 3 DBq to load get_my_courses() for the looked-at user, and the rest will be damn fast if the "looker" is $USER. Otherwise, it'll be an additional 3DBq.
Looking strictly at shared course contexts makes sense IMHO, and keeps you well within the optimised codepaths in the new accesslib.
With a vanilla v1.8... you cannot resolve it efficiently without the path field. Your starting point would be
SELECT rc.roleid,rc.capability,rc.permission,ctx.path
FROM mdl_role_capabilities rc
JOIN mdl_context ctx
ONrc.contextid=ctx.id
JOIN mdl_role_assignments ra
ON rc.roleid=ra.roleid
WHERE ctx.contextlevel in (10,40,50)
AND ra.userid=$mylookinguser
AND (rc.capability='moodle/user:viewdetails'
OR rc.capability='moodle/user:whatever');
And a similar one for the looked-at user to find where he is a participant.
But then to draw overlaps and aggregate the "permission" field properly based on those 2 datasets, you need the context path.