public static function data_for_messagearea_search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $systemcontext = context_system::instance();

        $params = array(
            'userid' => $userid,
            'search' => $search,
            'limitfrom' => $limitfrom,
            'limitnum' => $limitnum

        );
        $params = self::validate_parameters(self::data_for_messagearea_search_messages_parameters(), $params);
        self::validate_context($systemcontext);

        if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
            throw new moodle_exception('You do not have permission to perform this action.');
        }

        $messages = \core_message\api::search_messages(
            $params['userid'],
            $params['search'],
            $params['limitfrom'],
            $params['limitnum']
        );

        $data = new \stdClass();
        $data->contacts = [];
        foreach ($messages as $message) {
            $contact = new \stdClass();
            $contact->userid = $message->userid;
            $contact->fullname = $message->fullname;
            $contact->profileimageurl = $message->profileimageurl;
            $contact->profileimageurlsmall = $message->profileimageurlsmall;
            $contact->messageid = $message->messageid;
            $contact->ismessaging = $message->ismessaging;
            $contact->sentfromcurrentuser = false;
            if ($message->lastmessage) {
                if ($message->userid !== $message->useridfrom) {
                    $contact->sentfromcurrentuser = true;
                }
                $contact->lastmessage = shorten_text($message->lastmessage, 60);
            } else {
                $contact->lastmessage = null;
            }
            $contact->lastmessagedate = $message->lastmessagedate;
            $contact->showonlinestatus = is_null($message->isonline) ? false : true;
            $contact->isonline = $message->isonline;
            $contact->isblocked = $message->isblocked;
            $contact->isread = $message->isread;
            $contact->unreadcount = $message->unreadcount;
            $contact->conversationid = $message->conversationid;

            $data->contacts[] = $contact;
        }

        return $data;
    }