public static function list_plans_to_review($skip = 0, $limit = 100, $userid = null) {
        global $DB, $USER;
        static::require_enabled();

        if ($userid === null) {
            $userid = $USER->id;
        }

        $planfields = plan::get_sql_fields('p', 'plan_');
        $tplfields = template::get_sql_fields('t', 'tpl_');
        $usercols = array('id') + get_user_fieldnames();
        $userfields = array();
        foreach ($usercols as $field) {
            $userfields[] = "u." . $field . " AS usr_" . $field;
        }
        $userfields = implode(',', $userfields);

        $select = "SELECT $planfields, $tplfields, $userfields";
        $countselect = "SELECT COUNT('x')";

        $sql = "  FROM {" . plan::TABLE . "} p
                  JOIN {user} u
                    ON u.id = p.userid
             LEFT JOIN {" . template::TABLE . "} t
                    ON t.id = p.templateid
                 WHERE (p.status = :waitingforreview
                    OR (p.status = :inreview AND p.reviewerid = :reviewerid))
                   AND p.userid != :userid";

        $params = array(
            'waitingforreview' => plan::STATUS_WAITING_FOR_REVIEW,
            'inreview' => plan::STATUS_IN_REVIEW,
            'reviewerid' => $userid,
            'userid' => $userid
        );

        // Primary check to avoid the hard work of getting the users in which the user has permission.
        $count = $DB->count_records_sql($countselect . $sql, $params);
        if ($count < 1) {
            return array('count' => 0, 'plans' => array());
        }

        // TODO MDL-52243 Use core function.
        list($insql, $inparams) = self::filter_users_with_capability_on_user_context_sql('moodle/competency:planreview',
            $userid, SQL_PARAMS_NAMED);
        $sql .= " AND p.userid $insql";
        $params += $inparams;

        // Order by ID just to have some ordering in place.
        $ordersql = " ORDER BY p.id ASC";

        $plans = array();
        $records = $DB->get_recordset_sql($select . $sql . $ordersql, $params, $skip, $limit);
        foreach ($records as $record) {
            $plan = new plan(0, plan::extract_record($record, 'plan_'));
            $template = null;

            if ($plan->is_based_on_template()) {
                $template = new template(0, template::extract_record($record, 'tpl_'));
            }

            $plans[] = (object) array(
                'plan' => $plan,
                'template' => $template,
                'owner' => persistent::extract_record($record, 'usr_'),
            );
        }
        $records->close();

        return array(
            'count' => $DB->count_records_sql($countselect . $sql, $params),
            'plans' => $plans
        );
    }