I have given this ans in following link, look into that.
Hope it will help you.
Thank you! I will use this code to implement my function, as soon as I find out where to add it.
Do you by any chance know what the path field in the context table represents?
It is the hierarchy of contexts (parent context id, the parent of that parent context id etc, e.g. /sitecontextid/categorycontextid/coursecontextid/modulecontextid). Its used for speed optimisation of permission checking.