public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
        // Delete duplicates.
        $courseids = array_unique($courseids);
        $warnings = array();

        // Remove courses which are not even requested.
        $courses =  array_intersect_key($courses, array_flip($courseids));

        foreach ($courseids as $cid) {
            // Check the user can function in this context.
            try {
                $context = context_course::instance($cid);
                external_api::validate_context($context);

                if (!isset($courses[$cid])) {
                    $courses[$cid] = get_course($cid);
                }
                if ($addcontext) {
                    $courses[$cid]->context = $context;
                }
            } catch (Exception $e) {
                unset($courses[$cid]);
                $warnings[] = array(
                    'item' => 'course',
                    'itemid' => $cid,
                    'warningcode' => '1',
                    'message' => 'No access rights in course context'
                );
            }
        }

        return array($courses, $warnings);
    }