Create event using ids.

@param int $userfromid
@param int $usertoid
@param int $notificationid
@param int $courseid course id the event is related with - SITEID if no relation exists.
@return notification_sent
971106
public static function create_from_ids($userfromid, $usertoid, $notificationid, $courseid) {
        // We may be sending a notification from the 'noreply' address, which means we are not actually sending a
        // notification from a valid user. In this case, we will set the userid to 0.
        // Check if the userid is valid.
        if (!\core_user::is_real_user($userfromid)) {
            $userfromid = 0;
        }

        // If the courseid is null, then set it to the site id.
        if (is_null($courseid)) {
            $courseid = SITEID;
        }

        $event = self::create(
            [
                'objectid' => $notificationid,
                'userid' => $userfromid,
                'context' => \context_system::instance(),
                'relateduserid' => $usertoid,
                'other' => [
                    'courseid' => $courseid
                ]
            ]
        );

        return $event;
    }
38899
public function getNotificationById(int $notificationId): Notification
    {
        $notification = $this->mapper->extractNotificationsFromRows(
            $this->gateway->getNotificationById($notificationId)
        );

        if (count($notification) < 1) {
            throw new NotFoundException('Notification', $notificationId);
        }

        return reset($notification);
    }
262338
private function createAuthorization($userId, $instanceId)
    {
        $apiAll = $this->getNavitiaApiAllId();
        $this->call($this->tyrUrl . '/' . $this->version . '/users/' . $userId . '/authorizations/?api_id=' . $apiAll->id . '&instance_id=' . $instanceId, 'POST');

        return true;
    }
1295866
public function sendByUserId(int $userId, string $msg, ?string $dest = null, bool $flush = false) : void
    {
        $msg = $this->composeMsg($msg, $dest);

        foreach ($this->subscriptionTable->findActive()->where('user_id', $userId) as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }
966882
public static function count_proficient_competencies($courseid, $userid) {
        global $DB;

        $sql = 'SELECT COUNT(comp.id)
                  FROM {' . self::TABLE . '} usercoursecomp
                  JOIN {' . course_competency::TABLE . '} cc
                    ON usercoursecomp.competencyid = cc.competencyid AND cc.courseid = usercoursecomp.courseid
                  JOIN {' . competency::TABLE . '} comp
                    ON usercoursecomp.competencyid = comp.id
                 WHERE usercoursecomp.courseid = ? AND usercoursecomp.userid = ? AND usercoursecomp.proficiency = ?';
        $params = array($courseid, $userid, true);

        $results = $DB->count_records_sql($sql, $params);

        return $results;
    }
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;
    }
427085
public static function can_create_data_deletion_request_for_children(int $userid, int $requesterid = null): bool {
        global $USER;
        $requesterid = $requesterid ?: $USER->id;
        return has_capability('tool/dataprivacy:makedatadeletionrequestsforchildren', \context_user::instance($userid),
            $requesterid);
    }
338054
protected static function get_calendar_event_ids_by_context(\context $context, $userids = array()) {
        global $DB;

        // Calendar Events can exist at Site (CONTEXT_SYSTEM), Course Category (CONTEXT_COURSECAT),
        // Course and Course Group (CONTEXT_COURSE), User (CONTEXT_USER), or Course Modules (CONTEXT_MODULE) contexts.
        if (!in_array($context->contextlevel, [CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_USER, CONTEXT_MODULE])) {
            return [];
        }

        $whereusersql = '';
        $userparams = array();
        if (!empty($userids)) {
            list($usersql, $userparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
            $whereusersql = "AND e.userid {$usersql}";
        }

        if ($context->contextlevel == CONTEXT_MODULE) { // Course Module events.
            $params = ['cmid' => $context->instanceid];

            // Get Calendar Events for the specified Course Module context.
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {course_modules} cm
                      JOIN {modules} m ON m.id = cm.module
                      JOIN {event} e ON e.modulename = m.name AND e.courseid = cm.course AND e.instance = cm.instance
                     WHERE cm.id = :cmid
                           $whereusersql";
        } else if ($context->contextlevel == CONTEXT_SYSTEM) { // Site events.
            $params = [];
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {event} e
                     WHERE e.eventtype = 'site'
                           $whereusersql";
        } else { // The rest.
            $eventfields = [
                CONTEXT_COURSECAT   => 'categoryid',
                CONTEXT_COURSE      => 'courseid',
                CONTEXT_USER        => 'userid'
            ];
            $eventfield = $eventfields[$context->contextlevel];

            $eventtypes = [
                CONTEXT_COURSECAT   => 'category',
                CONTEXT_COURSE      => ['course' , 'group'],
                CONTEXT_USER        => 'user'
            ];
            list($eventtypesql, $eventtypeparams) = $DB->get_in_or_equal($eventtypes[$context->contextlevel], SQL_PARAMS_NAMED);

            $params = $eventtypeparams + ['instanceid' => $context->instanceid];

            // Get Calendar Events for the specified Moodle context.
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {event} e
                     WHERE e.eventtype $eventtypesql
                           AND e.{$eventfield} = :instanceid
                           $whereusersql";
        }

        $params += $userparams;

        return $DB->get_records_sql($sql, $params);
    }
617410
public function send(string $recipientID, Notification $notification): void
    {
        $app = App::get();

        if ($notification->id === null) {
            $notification->id = 'n' . uniqid() . 'x' . base_convert(rand(0, 999999999), 10, 16);
        }
        if ($notification->dateCreated === null) {
            $notification->dateCreated = time();
        }

        if ($this->hasEventListeners('beforeSendNotification')) {
            $eventDetails = new \IvoPetkov\BearFrameworkAddons\Notifications\BeforeSendNotificationEventDetails($recipientID, $notification);
            $this->dispatchEvent('beforeSendNotification', $eventDetails);
            if ($eventDetails->preventDefault) {
                return;
            }
        }

        if (strlen($notification->type) > 0) {
            $otherNotifications = $this->getList($recipientID);
            foreach ($otherNotifications as $otherNotification) {
                if ((string) $notification->type === (string) $otherNotification->type) {
                    $this->delete($recipientID, $otherNotification->id);
                }
            }
        }

        $this->set($recipientID, $notification);

        if ($this->hasEventListeners('sendNotification')) {
            $eventDetails = new \IvoPetkov\BearFrameworkAddons\Notifications\SendNotificationEventDetails($recipientID, $notification);
            $this->dispatchEvent('sendNotification', $eventDetails);
        }
    }
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;
    }
1357514
public static function block_user(int $userid, int $blockeduserid) {
        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, 'blockeduserid' => $blockeduserid];
        $params = self::validate_parameters(self::block_user_parameters(), $params);

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

        if (!\core_message\api::is_blocked($params['userid'], $params['blockeduserid'])) {
            \core_message\api::block_user($params['userid'], $params['blockeduserid']);
        }

        return [];
    }
767678
private function createRememberDirective($userId, $duration) {
		$selector = self::createRandomString(24);
		$token = self::createRandomString(32);
		$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
		$expires = \time() + ((int) $duration);

		try {
			$this->db->insert(
				$this->makeTableNameComponents('users_remembered'),
				[
					'user' => $userId,
					'selector' => $selector,
					'token' => $tokenHashed,
					'expires' => $expires
				]
			);
		}
		catch (Error $e) {
			throw new DatabaseError($e->getMessage());
		}

		$this->setRememberCookie($selector, $token, $expires);
	}
300618
public static function can_grade_user_in_course($userid, $courseid) {
        $ratecap = 'moodle/competency:competencygrade';
        return has_capability($ratecap, context_course::instance($courseid))
            || static::can_grade_user($userid);
    }
279052
protected static function export_user_data_in_course_contexts_associations($userid, $courseids, $path) {
        global $DB;

        // Fetch all the courses with associations we created or modified.
        $compfields = competency::get_sql_fields('c', 'c_');
        $ccfields = course_competency::get_sql_fields('cc', 'cc_');
        $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
        list($insql, $inparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
        $sql = "
            SELECT $compfields, $ccfields, $ctxfields
              FROM {" . course_competency::TABLE . "} cc
              JOIN {" . competency::TABLE . "} c
                ON c.id = cc.competencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
              JOIN {context} ctx
                ON ctx.id = f.contextid
             WHERE cc.usermodified = :userid
               AND cc.courseid $insql
          ORDER BY cc.courseid, c.id";
        $params = array_merge($inparams, ['userid' => $userid]);
        $recordset = $DB->get_recordset_sql($sql, $params);

        // Export the data.
        static::recordset_loop_and_export($recordset, 'cc_courseid', [], function($carry, $record) {
            context_helper::preload_from_record($record);
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $cc = new course_competency(null, course_competency::extract_record($record, 'cc_'));
            $carry[] = array_merge(static::transform_competency_brief($competency), [
                'timemodified' => transform::datetime($cc->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno(true)
            ]);
            return $carry;

        }, function($courseid, $data) use ($path, $userid, $DB) {
            $context = context_course::instance($courseid);
            writer::with_context($context)->export_related_data($path, 'associations', (object) ['competencies' => $data]);
        });
    }
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,
            ]);
        });
    }
615800
public static final function create_from_user_evidence(user_evidence $userevidence) {
        if (!$userevidence->get('id')) {
            throw new \coding_exception('The evidence of prior learning ID must be set.');
        }
        $event = static::create(array(
            'contextid'  => $userevidence->get_context()->id,
            'objectid' => $userevidence->get('id'),
            'relateduserid' => $userevidence->get('userid')
        ));
        $event->add_record_snapshot(user_evidence::TABLE, $userevidence->to_record());
        return $event;
    }
622818
public static function view_notes($courseid, $userid = 0) {
        global $CFG;
        require_once($CFG->dirroot . "/notes/lib.php");

        if (empty($CFG->enablenotes)) {
            throw new moodle_exception('notesdisabled', 'notes');
        }

        $warnings = array();
        $arrayparams = array(
            'courseid' => $courseid,
            'userid' => $userid
        );
        $params = self::validate_parameters(self::view_notes_parameters(), $arrayparams);

        if (empty($params['courseid'])) {
            $params['courseid'] = SITEID;
        }

        $course = get_course($params['courseid']);

        if ($course->id == SITEID) {
            $context = context_system::instance();
        } else {
            $context = context_course::instance($course->id);
        }

        // First of all, validate the context before do further permission checks.
        self::validate_context($context);
        require_capability('moodle/notes:view', $context);

        if (!empty($params['userid'])) {
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
            core_user::require_active_user($user);

            if ($course->id != SITEID and !can_access_course($course, $user, '', true)) {
                throw new moodle_exception('notenrolledprofile');
            }
        }

        note_view($context, $params['userid']);

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;

    }