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