public static function create_subscription($ruleid, $courseid, $cmid, $userid = 0) {
        global $DB, $USER;

        $subscription = new \stdClass();
        $subscription->ruleid = $ruleid;
        $subscription->courseid = $courseid;
        $subscription->cmid = $cmid;
        $subscription->userid = empty($userid) ? $USER->id : $userid;
        if ($DB->record_exists('tool_monitor_subscriptions', (array)$subscription)) {
            // Subscription already exists.
            return false;
        }

        $subscription->timecreated = time();
        $subscription->id = $DB->insert_record('tool_monitor_subscriptions', $subscription);

        // Trigger a subscription created event.
        if ($subscription->id) {
            if (!empty($subscription->courseid)) {
                $courseid = $subscription->courseid;
                $context = \context_course::instance($subscription->courseid);
            } else {
                $courseid = 0;
                $context = \context_system::instance();
            }

            $params = array(
                'objectid' => $subscription->id,
                'courseid' => $courseid,
                'context' => $context
            );
            $event = \tool_monitor\event\subscription_created::create($params);
            $event->trigger();

            // Let's invalidate the cache.
            $cache = \cache::make('tool_monitor', 'eventsubscriptions');
            $cache->delete($courseid);
        }

        return $subscription->id;
    }