Create contacts.

@deprecated since Moodle 3.6
@param array $userids array of user IDs.
@param int $userid The id of the user we are creating the contacts for
@return external_description
@since Moodle 2.5
768102
public static function create_contacts($userids, $userid = 0) {
        global $CFG, $USER;

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

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

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = array('userids' => $userids, 'userid' => $userid);
        $params = self::validate_parameters(self::create_contacts_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        $warnings = array();
        foreach ($params['userids'] as $id) {
            if (!message_add_contact($id, 0, $params['userid'])) {
                $warnings[] = array(
                    'item' => 'user',
                    'itemid' => $id,
                    'warningcode' => 'contactnotcreated',
                    'message' => 'The contact could not be created'
                );
            }
        }
        return $warnings;
    }
1283885
public function generate_user_ws_tokens($userid) {
        global $CFG, $DB;

        // generate a token for non admin if web service are enable and the user has the capability to create a token
        if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
            // for every service than the user is authorised on, create a token (if it doesn't already exist)

            // get all services which are set to all user (no restricted to specific users)
            $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
            $serviceidlist = array();
            foreach ($norestrictedservices as $service) {
                $serviceidlist[] = $service->id;
            }

            // get all services which are set to the current user (the current user is specified in the restricted user list)
            $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
            foreach ($servicesusers as $serviceuser) {
                if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
                     $serviceidlist[] = $serviceuser->externalserviceid;
                }
            }

            // get all services which already have a token set for the current user
            $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
            $tokenizedservice = array();
            foreach ($usertokens as $token) {
                    $tokenizedservice[]  = $token->externalserviceid;
            }

            // create a token for the service which have no token already
            foreach ($serviceidlist as $serviceid) {
                if (!in_array($serviceid, $tokenizedservice)) {
                    // create the token for this service
                    $newtoken = new stdClass();
                    $newtoken->token = md5(uniqid(rand(),1));
                    // check that the user has capability on this service
                    $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
                    $newtoken->userid = $userid;
                    $newtoken->externalserviceid = $serviceid;
                    // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
                    $newtoken->contextid = context_system::instance()->id;
                    $newtoken->creatorid = $userid;
                    $newtoken->timecreated = time();
                    $newtoken->privatetoken = null;

                    $DB->insert_record('external_tokens', $newtoken);
                }
            }


        }
    }
675428
public function addUser($id, $userId)
    {
        $xml = new \SimpleXMLElement('<?xml version="1.0"?><user_id>'.$userId.'</user_id>');

        return $this->post('/groups/'.$id.'/users.xml', $xml->asXML());
    }
930320
public function createContacts(User $currentUser, array $users)
    {
        $this->om->startFlushSuite();
        $createdContacts = [];

        foreach ($users as $user) {
            $contact = $this->contactRepo->findOneBy(['user' => $currentUser, 'contact' => $user]);

            if (is_null($contact)) {
                $contact = new Contact();
                $contact->setUser($currentUser);
                $contact->setContact($user);
                $this->om->persist($contact);
                $createdContacts[] = $contact;
            }
        }
        $this->om->endFlushSuite();

        return $createdContacts;
    }
614814
private function createBatch($userId)
    {
        $entity = new EBatch();
        $entity->setUserRef($userId);
        $result = $this->daoBatch->create($entity);
        return $result;
    }
714988
public static function create($userId, $params = null, $options = null)
    {
        return self::_userBasedCreate($userId, $params, $options);
    }
626678
public static function create_conversation_between_users(array $userids) {
        debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
            '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);

        // This method was always used for individual conversations.
        $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);

        return $conversation->id;
    }
216362
protected static function export_user_data_contact_requests(int $userid) {
        global $DB;

        $context = \context_user::instance($userid);

        if ($contactrequests = $DB->get_records_select('message_contact_requests', 'userid = ? OR requesteduserid = ?',
                [$userid, $userid], 'id ASC')) {
            $contactrequestsdata = [];
            foreach ($contactrequests as $contactrequest) {
                if ($userid == $contactrequest->requesteduserid) {
                    $maderequest = false;
                    $contactid = $contactrequest->userid;
                } else {
                    $maderequest = true;
                    $contactid = $contactrequest->requesteduserid;
                }

                $contactrequestsdata[] = (object) [
                    'contactrequest' => transform::user($contactid),
                    'maderequest' => transform::yesno($maderequest)
                ];
            }
            writer::with_context($context)->export_data([get_string('contactrequests', 'core_message')],
                (object) $contactrequestsdata);
        }
    }
548188
public function addUser($userId)
    {
        if (true === is_numeric($userId) && false === in_array($userId, $this->users)) {
            $this->users[] = (int)$userId;
        }
        return $this;
    }
929441
public static function create_from_userid($userid) {
        $data = array(
            'objectid' => $userid,
            'relateduserid' => $userid,
            'context' => \context_user::instance($userid)
        );

        // Create user_updated event.
        $event = self::create($data);
        return $event;
    }
905452
protected static function export_user_data_notifications(int $userid) {
        global $DB;

        $context = \context_user::instance($userid);

        $notificationdata = [];
        $select = "useridfrom = ? OR useridto = ?";
        $notifications = $DB->get_recordset_select('notifications', $select, [$userid, $userid], 'timecreated ASC');
        foreach ($notifications as $notification) {
            $timeread = !is_null($notification->timeread) ? transform::datetime($notification->timeread) : '-';

            $data = (object) [
                'subject' => $notification->subject,
                'fullmessage' => $notification->fullmessage,
                'smallmessage' => $notification->smallmessage,
                'component' => $notification->component,
                'eventtype' => $notification->eventtype,
                'contexturl' => $notification->contexturl,
                'contexturlname' => $notification->contexturlname,
                'timeread' => $timeread,
                'timecreated' => transform::datetime($notification->timecreated),
                'customdata' => $notification->customdata,
            ];

            $notificationdata[] = $data;
        }
        $notifications->close();

        writer::with_context($context)->export_data([get_string('notifications', 'core_message')], (object) $notificationdata);
    }
1110085
public static function unmute_conversations(int $userid, array $conversationids) {
        global $CFG, $USER;

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

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = ['userid' => $userid, 'conversationids' => $conversationids];
        $params = self::validate_parameters(self::unmute_conversations_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        foreach ($params['conversationids'] as $conversationid) {
            \core_message\api::unmute_conversation($params['userid'], $conversationid);
        }

        return [];
    }
454374
public function addParticipant($userId)
    {
        $userIds = is_array($userId) ? $userId : (array) func_get_args();

        collect($userIds)->each(function ($userId) {
            Models::participant()->firstOrCreate([
                'user_id' => $userId,
                'thread_id' => $this->id,
            ]);
        });
    }
651281
public function deleteSoft(array $userIds): void
    {
        $deleted = $this->getRepository()->deleteSoft($userIds);

        event(new HCUserSoftDeleted($deleted));
    }
256343
public static function can_create_contact(int $userid, int $requesteduserid) : bool {
        global $CFG;

        // If we can't message at all, then we can't create a contact.
        if (empty($CFG->messaging)) {
            return false;
        }

        // If we can message anyone on the site then we can create a contact.
        if ($CFG->messagingallusers) {
            return true;
        }

        // We need to check if they are in the same course.
        return enrol_sharing_course($userid, $requesteduserid);
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
700134
public static function count_contacts(int $userid) : int {
        global $DB;

        $sql = "SELECT COUNT(id)
                  FROM {message_contacts}
                 WHERE userid = ? OR contactid = ?";
        return $DB->count_records_sql($sql, [$userid, $userid]);
    }