protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
        global $DB;

        $record = new stdClass();
        $record->contextlevel = $contextlevel;
        $record->instanceid   = $instanceid;
        $record->depth        = 0;
        $record->path         = null; //not known before insert
        $record->locked       = 0;

        $record->id = $DB->insert_record('context', $record);

        // now add path if known - it can be added later
        if (!is_null($parentpath)) {
            $record->path = $parentpath.'/'.$record->id;
            $record->depth = substr_count($record->path, '/');
            $DB->update_record('context', $record);
        }

        return $record;
    }