MDL-55637 core_message: create helper function for WS to define contacts
[moodle.git] / message / classes / api.php
CommitLineData
879e2bef
MN
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Contains class used to return information to display for the message area.
19 *
20 * @package core_message
21 * @copyright 2016 Mark Nelson <markn@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_message;
26
27require_once($CFG->dirroot . '/lib/messagelib.php');
28
29defined('MOODLE_INTERNAL') || die();
30
31/**
32 * Class used to return information to display for the message area.
33 *
34 * @copyright 2016 Mark Nelson <markn@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class api {
38
cd03b8d7
MN
39 /**
40 * Handles searching for messages in the message area.
41 *
42 * @param int $userid The user id doing the searching
43 * @param string $search The string the user is searching
44 * @param int $limitfrom
45 * @param int $limitnum
46 * @return \core_message\output\messagearea\message_search_results
47 */
48 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
49 global $DB;
50
51 // Get the user fields we want.
52 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
53 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
54
55 // Get all the messages for the user.
56 $sql = "SELECT m.id, m.useridfrom, m.useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
57 m.smallmessage, m.notification, m.timecreated, 0 as isread, $ufields, $ufields2
58 FROM {message} m
59 JOIN {user} u
60 ON m.useridfrom = u.id
61 JOIN {user} u2
62 ON m.useridto = u2.id
63 WHERE ((useridto = ? AND timeusertodeleted = 0)
64 OR (useridfrom = ? AND timeuserfromdeleted = 0))
65 AND notification = 0
66 AND u.deleted = 0
67 AND u2.deleted = 0
68 AND " . $DB->sql_like('smallmessage', '?', false) . "
69 UNION ALL
70 SELECT mr.id, mr.useridfrom, mr.useridto, mr.subject, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat,
71 mr.smallmessage, mr.notification, mr.timecreated, 1 as isread, $ufields, $ufields2
72 FROM {message_read} mr
73 JOIN {user} u
74 ON mr.useridfrom = u.id
75 JOIN {user} u2
76 ON mr.useridto = u2.id
77 WHERE ((useridto = ? AND timeusertodeleted = 0)
78 OR (useridfrom = ? AND timeuserfromdeleted = 0))
79 AND notification = 0
80 AND u.deleted = 0
81 AND u2.deleted = 0
82 AND " . $DB->sql_like('smallmessage', '?', false) . "
83 ORDER BY timecreated DESC";
84 $params = array($userid, $userid, '%' . $search . '%',
85 $userid, $userid, '%' . $search . '%');
86
87 // Convert the messages into searchable contacts with their last message being the message that was searched.
88 $contacts = array();
89 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
90 foreach ($messages as $message) {
91 $prefix = 'userfrom_';
92 if ($userid == $message->useridfrom) {
93 $prefix = 'userto_';
94 // If it from the user, then mark it as read, even if it wasn't by the receiver.
95 $message->isread = true;
96 }
97 $message->messageid = $message->id;
98 $contacts[] = \core_message\helper::create_contact($message, $prefix);
99 }
100 }
101
102 return new \core_message\output\messagearea\message_search_results($userid, $contacts);
103 }
104
105 /**
106 * Handles searching for people in a particular course in the message area.
107 *
108 * @param int $userid The user id doing the searching
109 * @param int $courseid The id of the course we are searching in
110 * @param string $search The string the user is searching
111 * @param int $limitfrom
112 * @param int $limitnum
113 * @return \core_message\output\messagearea\people_search_results
114 */
115 public static function search_people_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
116 global $DB;
117
118 // Get all the users in the course.
119 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
120 $sql = "SELECT u.*
121 FROM {user} u
122 JOIN ($esql) je ON je.id = u.id
123 WHERE u.deleted = 0";
124 // Add more conditions.
125 $fullname = $DB->sql_fullname();
126 $sql .= " AND u.id != :userid
127 AND " . $DB->sql_like($fullname, ':search', false) . "
128 ORDER BY " . $DB->sql_fullname();
129 $params = array_merge(array('userid' => $userid, 'search' => '%' . $search . '%'), $params);
130
131
132 // Convert all the user records into contacts.
133 $contacts = array();
134 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
135 foreach ($users as $user) {
136 $contacts[] = \core_message\helper::create_contact($user);
137 }
138 }
139
140 return new \core_message\output\messagearea\people_search_results($contacts);
141 }
142
143 /**
144 * Handles searching for people in the message area.
145 *
146 * @param int $userid The user id doing the searching
147 * @param string $search The string the user is searching
148 * @param int $limitnum
149 * @return \core_message\output\messagearea\people_search_results
150 */
151 public static function search_people($userid, $search, $limitnum = 0) {
152 global $CFG, $DB;
153
154 require_once($CFG->dirroot . '/lib/coursecatlib.php');
155
156 // Used to search for contacts.
157 $fullname = $DB->sql_fullname();
158 $ufields = \user_picture::fields('u', array('lastaccess'));
159
160 // Users not to include.
161 $excludeusers = array($userid, $CFG->siteguest);
162 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
163
164 // Ok, let's search for contacts first.
165 $contacts = array();
166 $sql = "SELECT $ufields
167 FROM {user} u
168 JOIN {message_contacts} mc
169 ON u.id = mc.contactid
170 WHERE mc.userid = :userid
171 AND u.deleted = 0
172 AND u.confirmed = 1
173 AND " . $DB->sql_like($fullname, ':search', false) . "
174 AND u.id $exclude
175 ORDER BY " . $DB->sql_fullname();
176 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') +
177 $excludeparams, 0, $limitnum)) {
178 foreach ($users as $user) {
179 $contacts[] = \core_message\helper::create_contact($user);
180 }
181 }
182
183 // Now, let's get the courses.
184 $courses = array();
185 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum))) {
186 foreach ($arrcourses as $course) {
187 $data = new \stdClass();
188 $data->id = $course->id;
189 $data->shortname = $course->shortname;
190 $data->fullname = $course->fullname;
191 $courses[] = $data;
192 }
193 }
194
195 // Let's get those non-contacts. Toast them gears boi.
196 $noncontacts = array();
197 $sql = "SELECT $ufields
198 FROM {user} u
199 WHERE u.deleted = 0
200 AND u.confirmed = 1
201 AND " . $DB->sql_like($fullname, ':search', false) . "
202 AND u.id $exclude
203 AND u.id NOT IN (SELECT contactid
204 FROM {message_contacts}
205 WHERE userid = :userid)
206 ORDER BY " . $DB->sql_fullname();
207 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') +
208 $excludeparams, 0, $limitnum)) {
209 foreach ($users as $user) {
210 $noncontacts[] = \core_message\helper::create_contact($user);
211 }
212 }
213
214 return new \core_message\output\messagearea\people_search_results($contacts, $courses, $noncontacts);
215 }
216
879e2bef
MN
217 /**
218 * Returns the contacts and their conversation to display in the contacts area.
219 *
220 * @param int $userid The user id
221 * @param int $otheruserid The id of the user we have selected, 0 if none have been selected
222 * @param int $limitfrom
223 * @param int $limitnum
1e5f751f 224 * @return \core_message\output\messagearea\contacts
879e2bef
MN
225 */
226 public static function get_conversations($userid, $otheruserid = 0, $limitfrom = 0, $limitnum = 0) {
227 $arrcontacts = array();
228 if ($conversations = message_get_recent_conversations($userid, $limitfrom, $limitnum)) {
229 foreach ($conversations as $conversation) {
230 $arrcontacts[] = \core_message\helper::create_contact($conversation);
231 }
232 }
233
1e5f751f 234 return new \core_message\output\messagearea\contacts($userid, $otheruserid, $arrcontacts);
879e2bef
MN
235 }
236
237 /**
238 * Returns the contacts to display in the contacts area.
239 *
240 * @param int $userid The user id
241 * @param int $limitfrom
242 * @param int $limitnum
1e5f751f 243 * @return \core_message\output\messagearea\contacts
879e2bef
MN
244 */
245 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
246 global $DB;
247
248 $arrcontacts = array();
249 $sql = "SELECT u.*
250 FROM {message_contacts} mc
251 JOIN {user} u
252 ON mc.contactid = u.id
253 WHERE mc.userid = :userid
254 AND u.deleted = 0
255 ORDER BY " . $DB->sql_fullname();
256 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
257 foreach ($contacts as $contact) {
258 $arrcontacts[] = \core_message\helper::create_contact($contact);
259 }
260 }
261
4d1b76ee 262 return new \core_message\output\messagearea\contacts($userid, 0, $arrcontacts, false);
879e2bef
MN
263 }
264
265 /**
266 * Returns the messages to display in the message area.
267 *
268 * @param int $userid the current user
269 * @param int $otheruserid the other user
270 * @param int $limitfrom
271 * @param int $limitnum
8ec78c48 272 * @param string $sort
1e5f751f 273 * @return \core_message\output\messagearea\messages
879e2bef 274 */
8ec78c48 275 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0, $sort = 'timecreated ASC') {
879e2bef 276 $arrmessages = array();
8ec78c48 277 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum, $sort)) {
879e2bef
MN
278 $arrmessages = \core_message\helper::create_messages($userid, $messages);
279 }
280
1e5f751f 281 return new \core_message\output\messagearea\messages($userid, $otheruserid, $arrmessages);
879e2bef 282 }
c060cd49
MN
283
284 /**
285 * Returns the most recent message between two users.
286 *
287 * @param int $userid the current user
288 * @param int $otheruserid the other user
1e5f751f 289 * @return \core_message\output\messagearea\message|null
c060cd49
MN
290 */
291 public static function get_most_recent_message($userid, $otheruserid) {
292 // We want two messages here so we get an accurate 'blocktime' value.
dec0cd99 293 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
294 // Swap the order so we now have them in historical order.
295 $messages = array_reverse($messages);
296 $arrmessages = \core_message\helper::create_messages($userid, $messages);
297 return array_pop($arrmessages);
298 }
299
300 return null;
301 }
c6e97f54
MN
302
303 /**
304 * Returns the profile information for a contact for a user.
305 *
306 * @param int $userid The user id
307 * @param int $otheruserid The id of the user whose profile we want to view.
1e5f751f 308 * @return \core_message\output\messagearea\profile
c6e97f54
MN
309 */
310 public static function get_profile($userid, $otheruserid) {
311 global $CFG, $DB;
312
313 require_once($CFG->dirroot . '/user/lib.php');
314
315 if ($user = \core_user::get_user($otheruserid)) {
316 // Create the data we are going to pass to the renderable.
317 $userfields = user_get_user_details($user, null, array('city', 'country', 'email',
bf58081d 318 'profileimageurl', 'profileimageurlsmall', 'lastaccess'));
edac7c80
DW
319 if ($userfields) {
320 $data = new \stdClass();
321 $data->userid = $userfields['id'];
322 $data->fullname = $userfields['fullname'];
323 $data->city = isset($userfields['city']) ? $userfields['city'] : '';
324 $data->country = isset($userfields['country']) ? $userfields['country'] : '';
325 $data->email = isset($userfields['email']) ? $userfields['email'] : '';
326 $data->profileimageurl = isset($userfields['profileimageurl']) ? $userfields['profileimageurl'] : '';
327 $data->profileimageurlsmall = isset($userfields['profileimageurlsmall']) ?
328 $userfields['profileimageurlsmall'] : '';
329 if (isset($userfields['lastaccess'])) {
330 $data->isonline = \core_message\helper::is_online($userfields['lastaccess']);
331 } else {
332 $data->isonline = 0;
333 }
bf58081d 334 } else {
edac7c80
DW
335 // Technically the access checks in user_get_user_details are correct,
336 // but messaging has never obeyed them. In order to keep messaging working
337 // we at least need to return a minimal user record.
338 $data = new \stdClass();
339 $data->userid = $otheruserid;
340 $data->fullname = fullname($user);
341 $data->city = '';
342 $data->country = '';
343 $data->email = '';
344 $data->profileimageurl = '';
345 $data->profileimageurlsmall = '';
bf58081d
MN
346 $data->isonline = 0;
347 }
c6e97f54
MN
348 // Check if the contact has been blocked.
349 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
350 if ($contact) {
351 $data->isblocked = $contact->blocked;
352 $data->iscontact = true;
353 } else {
354 $data->isblocked = false;
355 $data->iscontact = false;
356 }
357
1e5f751f 358 return new \core_message\output\messagearea\profile($userid, $data);
c6e97f54
MN
359 }
360 }
dec0cd99
MN
361
362 /**
363 * Checks if a user can delete messages they have either received or sent.
364 *
365 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
366 * but will still seem as if it was by the user)
367 * @return bool Returns true if a user can delete the message, false otherwise.
368 */
369 public static function can_delete_conversation($userid) {
370 global $USER;
371
372 $systemcontext = \context_system::instance();
373
374 // Let's check if the user is allowed to delete this message.
375 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
376 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
377 $USER->id == $userid))) {
378 return true;
379 }
380
381 return false;
382 }
383
384 /**
385 * Deletes a conversation.
386 *
387 * This function does not verify any permissions.
388 *
389 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
390 * but will still seem as if it was by the user)
391 * @param int $otheruserid The id of the other user in the conversation
392 * @return bool
393 */
394 public static function delete_conversation($userid, $otheruserid) {
395 global $DB, $USER;
396
397 // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
398 // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
399 // This won't be a particularly heavily used function (at least I hope not), so let's hope MDL-36941 gets worked on
400 // soon for the sake of any developers' sanity when dealing with the messaging system.
401 $now = time();
402 $sql = "UPDATE {message}
403 SET timeuserfromdeleted = :time
404 WHERE useridfrom = :userid
405 AND useridto = :otheruserid
406 AND notification = 0";
407 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
408
409 $sql = "UPDATE {message}
410 SET timeusertodeleted = :time
411 WHERE useridto = :userid
412 AND useridfrom = :otheruserid
413 AND notification = 0";
414 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
415
416 $sql = "UPDATE {message_read}
417 SET timeuserfromdeleted = :time
418 WHERE useridfrom = :userid
419 AND useridto = :otheruserid
420 AND notification = 0";
421 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
422
423 $sql = "UPDATE {message_read}
424 SET timeusertodeleted = :time
425 WHERE useridto = :userid
426 AND useridfrom = :otheruserid
427 AND notification = 0";
428 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
429
430 // Now we need to trigger events for these.
431 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, $now)) {
432 // Loop through and trigger a deleted event.
433 foreach ($messages as $message) {
434 $messagetable = 'message';
435 if (!empty($message->timeread)) {
436 $messagetable = 'message_read';
437 }
438
439 // Trigger event for deleting the message.
440 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
441 $USER->id, $messagetable, $message->id)->trigger();
442 }
443 }
444
445 return true;
446 }
879e2bef 447}