Commit | Line | Data |
---|---|---|
eb5334ff | 1 | <?php |
eb5334ff | 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 | * Library functions for messaging | |
19 | * | |
6fbd60ef AD |
20 | * @package core_message |
21 | * @copyright 2008 Luis Rodrigues | |
22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
eb5334ff | 23 | */ |
172186b8 | 24 | |
3b120e46 | 25 | require_once($CFG->libdir.'/eventslib.php'); |
26 | ||
e8e2d7f1 | 27 | define ('MESSAGE_SHORTLENGTH', 300); |
d3875524 | 28 | |
c8621a02 AD |
29 | define ('MESSAGE_DISCUSSION_WIDTH',600); |
30 | define ('MESSAGE_DISCUSSION_HEIGHT',500); | |
31 | ||
32 | define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history | |
33 | ||
c8621a02 AD |
34 | define('MESSAGE_HISTORY_SHORT',0); |
35 | define('MESSAGE_HISTORY_ALL',1); | |
36 | ||
25bd5c75 | 37 | define('MESSAGE_VIEW_UNREAD_MESSAGES','unread'); |
38 | define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations'); | |
39 | define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications'); | |
40 | define('MESSAGE_VIEW_CONTACTS','contacts'); | |
41 | define('MESSAGE_VIEW_BLOCKED','blockedusers'); | |
42 | define('MESSAGE_VIEW_COURSE','course_'); | |
43 | define('MESSAGE_VIEW_SEARCH','search'); | |
c8621a02 | 44 | |
c3931654 AD |
45 | define('MESSAGE_SEARCH_MAX_RESULTS', 200); |
46 | ||
32ef43e1 | 47 | define('MESSAGE_CONTACTS_PER_PAGE',10); |
b2bce32f | 48 | define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30); |
32ef43e1 | 49 | |
3274d5ca RW |
50 | define('MESSAGE_UNREAD','unread'); |
51 | define('MESSAGE_READ','read'); | |
52 | define('MESSAGE_TYPE_NOTIFICATION','notification'); | |
53 | define('MESSAGE_TYPE_MESSAGE','message'); | |
54 | ||
55 | ||
7a04c476 RK |
56 | /** |
57 | * Define contants for messaging default settings population. For unambiguity of | |
58 | * plugin developer intentions we use 4-bit value (LSB numbering): | |
59 | * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN) | |
60 | * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF) | |
61 | * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED) | |
62 | * | |
63 | * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting | |
64 | */ | |
65 | ||
66 | define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001 | |
67 | define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010 | |
68 | ||
69 | define('MESSAGE_DISALLOWED', 0x04); // 0100 | |
70 | define('MESSAGE_PERMITTED', 0x08); // 1000 | |
71 | define('MESSAGE_FORCED', 0x0c); // 1100 | |
72 | ||
73 | define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100 | |
74 | ||
1d72e9d4 RK |
75 | /** |
76 | * Set default value for default outputs permitted setting | |
77 | */ | |
814e3735 | 78 | define('MESSAGE_DEFAULT_PERMITTED', 'permitted'); |
1d72e9d4 | 79 | |
bcab42da | 80 | /** |
ebe0c008 RK |
81 | * Retrieve users blocked by $user1 |
82 | * | |
83 | * @param object $user1 the user whose messages are being viewed | |
84 | * @param object $user2 the user $user1 is talking to. If they are being blocked | |
85 | * they will have a variable called 'isblocked' added to their user object | |
86 | * @return array the users blocked by $user1 | |
87 | */ | |
bcab42da | 88 | function message_get_blocked_users($user1=null, $user2=null) { |
c8621a02 AD |
89 | global $DB, $USER; |
90 | ||
91 | if (empty($user1)) { | |
92 | $user1 = $USER; | |
93 | } | |
94 | ||
95 | if (!empty($user2)) { | |
96 | $user2->isblocked = false; | |
97 | } | |
98 | ||
19c5532b AD |
99 | $blockedusers = array(); |
100 | ||
3a11c09f PS |
101 | $userfields = user_picture::fields('u', array('lastaccess')); |
102 | $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount | |
103 | FROM {message_contacts} mc | |
104 | JOIN {user} u ON u.id = mc.contactid | |
105 | LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1 | |
01393790 | 106 | WHERE u.deleted = 0 AND mc.userid = :user1id2 AND mc.blocked = 1 |
3a11c09f PS |
107 | GROUP BY $userfields |
108 | ORDER BY u.firstname ASC"; | |
bcab42da | 109 | $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id)); |
c8621a02 | 110 | |
19c5532b AD |
111 | foreach($rs as $rd) { |
112 | $blockedusers[] = $rd; | |
c8621a02 | 113 | |
19c5532b AD |
114 | if (!empty($user2) && $user2->id == $rd->id) { |
115 | $user2->isblocked = true; | |
c8621a02 | 116 | } |
c8621a02 | 117 | } |
19c5532b | 118 | $rs->close(); |
c8621a02 AD |
119 | |
120 | return $blockedusers; | |
121 | } | |
122 | ||
bcab42da | 123 | /** |
ebe0c008 RK |
124 | * Retrieve $user1's contacts (online, offline and strangers) |
125 | * | |
126 | * @param object $user1 the user whose messages are being viewed | |
127 | * @param object $user2 the user $user1 is talking to. If they are a contact | |
128 | * they will have a variable called 'iscontact' added to their user object | |
129 | * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers) | |
130 | */ | |
bcab42da | 131 | function message_get_contacts($user1=null, $user2=null) { |
c8621a02 | 132 | global $DB, $CFG, $USER; |
172186b8 | 133 | |
c8621a02 AD |
134 | if (empty($user1)) { |
135 | $user1 = $USER; | |
136 | } | |
137 | ||
138 | if (!empty($user2)) { | |
139 | $user2->iscontact = false; | |
140 | } | |
e8e2d7f1 | 141 | |
142 | $timetoshowusers = 300; //Seconds default | |
143 | if (isset($CFG->block_online_users_timetosee)) { | |
144 | $timetoshowusers = $CFG->block_online_users_timetosee * 60; | |
145 | } | |
e8e2d7f1 | 146 | |
f46b6587 | 147 | // time which a user is counting as being active since |
148 | $timefrom = time()-$timetoshowusers; | |
531e58f1 | 149 | |
f46b6587 | 150 | // people in our contactlist who are online |
151 | $onlinecontacts = array(); | |
152 | // people in our contactlist who are offline | |
153 | $offlinecontacts = array(); | |
154 | // people who are not in our contactlist but have sent us a message | |
627bb9ec AD |
155 | $strangers = array(); |
156 | ||
3a11c09f | 157 | $userfields = user_picture::fields('u', array('lastaccess')); |
f46b6587 | 158 | |
1d422980 | 159 | // get all in our contactlist who are not blocked in our contact list |
f46b6587 | 160 | // and count messages we have waiting from each of them |
3a11c09f | 161 | $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount |
fd1cb1e8 | 162 | FROM {message_contacts} mc |
163 | JOIN {user} u ON u.id = mc.contactid | |
164 | LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ? | |
01393790 | 165 | WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0 |
3a11c09f | 166 | GROUP BY $userfields |
bbe973da | 167 | ORDER BY u.firstname ASC"; |
fd1cb1e8 | 168 | |
20222a3d EL |
169 | $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id)); |
170 | foreach ($rs as $rd) { | |
171 | if ($rd->lastaccess >= $timefrom) { | |
172 | // they have been active recently, so are counted online | |
173 | $onlinecontacts[] = $rd; | |
174 | ||
175 | } else { | |
176 | $offlinecontacts[] = $rd; | |
177 | } | |
c8621a02 | 178 | |
bcab42da | 179 | if (!empty($user2) && $user2->id == $rd->id) { |
20222a3d | 180 | $user2->iscontact = true; |
e8e2d7f1 | 181 | } |
f46b6587 | 182 | } |
20222a3d | 183 | $rs->close(); |
f46b6587 | 184 | |
f46b6587 | 185 | // get messages from anyone who isn't in our contact list and count the number |
186 | // of messages we have from each of them | |
3a11c09f | 187 | $strangersql = "SELECT $userfields, count(m.id) as messagecount |
fd1cb1e8 | 188 | FROM {message} m |
189 | JOIN {user} u ON u.id = m.useridfrom | |
190 | LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto | |
01393790 | 191 | WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ? |
3a11c09f | 192 | GROUP BY $userfields |
bbe973da | 193 | ORDER BY u.firstname ASC"; |
fd1cb1e8 | 194 | |
20222a3d | 195 | $rs = $DB->get_recordset_sql($strangersql, array($USER->id)); |
25bd63b7 | 196 | // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users). |
20222a3d | 197 | foreach ($rs as $rd) { |
25bd63b7 | 198 | $strangers[$rd->id] = $rd; |
e8e2d7f1 | 199 | } |
20222a3d | 200 | $rs->close(); |
e8e2d7f1 | 201 | |
25bd63b7 | 202 | // Add noreply user and support user to the list, if they don't exist. |
9a90e7c5 | 203 | $supportuser = core_user::get_support_user(); |
25bd63b7 RT |
204 | if (!isset($strangers[$supportuser->id])) { |
205 | $supportuser->messagecount = message_count_unread_messages($USER, $supportuser); | |
206 | if ($supportuser->messagecount > 0) { | |
207 | $strangers[$supportuser->id] = $supportuser; | |
208 | } | |
9a90e7c5 | 209 | } |
25bd63b7 | 210 | |
9a90e7c5 | 211 | $noreplyuser = core_user::get_noreply_user(); |
25bd63b7 RT |
212 | if (!isset($strangers[$noreplyuser->id])) { |
213 | $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser); | |
214 | if ($noreplyuser->messagecount > 0) { | |
215 | $strangers[$noreplyuser->id] = $noreplyuser; | |
216 | } | |
9a90e7c5 | 217 | } |
c8621a02 AD |
218 | return array($onlinecontacts, $offlinecontacts, $strangers); |
219 | } | |
220 | ||
bcab42da | 221 | /** |
ebe0c008 RK |
222 | * Load the course contexts for all of the users courses |
223 | * | |
224 | * @param array $courses array of course objects. The courses the user is enrolled in. | |
225 | * @return array of course contexts | |
226 | */ | |
bcab42da | 227 | function message_get_course_contexts($courses) { |
c8621a02 AD |
228 | $coursecontexts = array(); |
229 | ||
230 | foreach($courses as $course) { | |
bf0f06b1 | 231 | $coursecontexts[$course->id] = context_course::instance($course->id); |
c8621a02 AD |
232 | } |
233 | ||
234 | return $coursecontexts; | |
235 | } | |
236 | ||
cee92282 AD |
237 | /** |
238 | * strip off action parameters like 'removecontact' | |
ebe0c008 | 239 | * |
bcab42da | 240 | * @param moodle_url/string $moodleurl a URL. Typically the current page URL. |
241 | * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact). | |
cee92282 | 242 | */ |
c8621a02 | 243 | function message_remove_url_params($moodleurl) { |
c8621a02 AD |
244 | $newurl = new moodle_url($moodleurl); |
245 | $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact'); | |
246 | return $newurl->out(); | |
247 | } | |
248 | ||
bcab42da | 249 | /** |
250 | * Count the number of messages with a field having a specified value. | |
251 | * if $field is empty then return count of the whole array | |
252 | * if $field is non-existent then return 0 | |
ebe0c008 | 253 | * |
bcab42da | 254 | * @param array $messagearray array of message objects |
255 | * @param string $field the field to inspect on the message objects | |
256 | * @param string $value the value to test the field against | |
257 | */ | |
e8e2d7f1 | 258 | function message_count_messages($messagearray, $field='', $value='') { |
259 | if (!is_array($messagearray)) return 0; | |
260 | if ($field == '' or empty($messagearray)) return count($messagearray); | |
531e58f1 | 261 | |
e8e2d7f1 | 262 | $count = 0; |
263 | foreach ($messagearray as $message) { | |
264 | $count += ($message->$field == $value) ? 1 : 0; | |
265 | } | |
266 | return $count; | |
172186b8 | 267 | } |
268 | ||
c8621a02 AD |
269 | /** |
270 | * Returns the count of unread messages for user. Either from a specific user or from all users. | |
ebe0c008 | 271 | * |
c8621a02 AD |
272 | * @param object $user1 the first user. Defaults to $USER |
273 | * @param object $user2 the second user. If null this function will count all of user 1's unread messages. | |
274 | * @return int the count of $user1's unread messages | |
275 | */ | |
276 | function message_count_unread_messages($user1=null, $user2=null) { | |
277 | global $USER, $DB; | |
e8e2d7f1 | 278 | |
c8621a02 AD |
279 | if (empty($user1)) { |
280 | $user1 = $USER; | |
281 | } | |
282 | ||
283 | if (!empty($user2)) { | |
284 | return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?", | |
285 | array($user1->id, $user2->id), "COUNT('id')"); | |
286 | } else { | |
287 | return $DB->count_records_select('message', "useridto = ?", | |
288 | array($user1->id), "COUNT('id')"); | |
289 | } | |
290 | } | |
291 | ||
bcab42da | 292 | /** |
293 | * Count the number of users blocked by $user1 | |
ebe0c008 RK |
294 | * |
295 | * @param object $user1 user object | |
296 | * @return int the number of blocked users | |
bcab42da | 297 | */ |
c8621a02 AD |
298 | function message_count_blocked_users($user1=null) { |
299 | global $USER, $DB; | |
300 | ||
301 | if (empty($user1)) { | |
302 | $user1 = $USER; | |
303 | } | |
304 | ||
305 | $sql = "SELECT count(mc.id) | |
306 | FROM {message_contacts} mc | |
307 | WHERE mc.userid = :userid AND mc.blocked = 1"; | |
bcab42da | 308 | $params = array('userid' => $user1->id); |
c8621a02 AD |
309 | |
310 | return $DB->count_records_sql($sql, $params); | |
311 | } | |
312 | ||
bcab42da | 313 | /** |
314 | * Get the users recent conversations meaning all the people they've recently | |
315 | * sent or received a message from plus the most recent message sent to or received from each other user | |
ebe0c008 | 316 | * |
879e2bef | 317 | * @param object|int $user the current user |
bcab42da | 318 | * @param int $limitfrom can be used for paging |
319 | * @param int $limitto can be used for paging | |
320 | * @return array | |
321 | */ | |
322 | function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) { | |
323 | global $DB; | |
324 | ||
879e2bef MN |
325 | if (is_numeric($user)) { |
326 | $userid = $user; | |
327 | $user = new stdClass(); | |
328 | $user->id = $userid; | |
329 | } | |
330 | ||
f68b11f7 TH |
331 | $userfields = user_picture::fields('otheruser', array('lastaccess')); |
332 | ||
333 | // This query retrieves the most recent message received from or sent to | |
334 | // seach other user. | |
335 | // | |
336 | // If two messages have the same timecreated, we take the one with the | |
337 | // larger id. | |
338 | // | |
339 | // There is a separate query for read and unread messages as they are stored | |
340 | // in different tables. They were originally retrieved in one query but it | |
341 | // was so large that it was difficult to be confident in its correctness. | |
3d9c8578 | 342 | $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto'); |
b5e9faa6 | 343 | $sql = "SELECT $uniquefield, $userfields, |
f68b11f7 | 344 | message.id as mid, message.notification, message.smallmessage, message.fullmessage, |
eda6bc19 | 345 | message.fullmessagehtml, message.fullmessageformat, message.timecreated, 1 as isread, |
f68b11f7 | 346 | contact.id as contactlistid, contact.blocked |
f68b11f7 | 347 | FROM {message_read} message |
b5e9faa6 AN |
348 | JOIN ( |
349 | SELECT MAX(id) AS messageid, | |
350 | matchedmessage.useridto, | |
351 | matchedmessage.useridfrom | |
352 | FROM {message_read} matchedmessage | |
353 | INNER JOIN ( | |
354 | SELECT MAX(recentmessages.timecreated) timecreated, | |
355 | recentmessages.useridfrom, | |
356 | recentmessages.useridto | |
357 | FROM {message_read} recentmessages | |
36d29c08 MN |
358 | WHERE ( |
359 | (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR | |
360 | (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0) | |
361 | ) | |
b5e9faa6 AN |
362 | GROUP BY recentmessages.useridfrom, recentmessages.useridto |
363 | ) recent ON matchedmessage.useridto = recent.useridto | |
364 | AND matchedmessage.useridfrom = recent.useridfrom | |
365 | AND matchedmessage.timecreated = recent.timecreated | |
36d29c08 MN |
366 | WHERE ( |
367 | (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR | |
368 | (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0) | |
369 | ) | |
b5e9faa6 AN |
370 | GROUP BY matchedmessage.useridto, matchedmessage.useridfrom |
371 | ) messagesubset ON messagesubset.messageid = message.id | |
372 | JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id) | |
373 | OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id) | |
a0bc890e | 374 | LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.contactid = otheruser.id |
b5e9faa6 | 375 | WHERE otheruser.deleted = 0 AND message.notification = 0 |
f68b11f7 | 376 | ORDER BY message.timecreated DESC"; |
b5e9faa6 AN |
377 | $params = array( |
378 | 'userid1' => $user->id, | |
379 | 'userid2' => $user->id, | |
380 | 'userid3' => $user->id, | |
381 | 'userid4' => $user->id, | |
382 | 'userid5' => $user->id, | |
36d29c08 MN |
383 | 'userid6' => $user->id, |
384 | 'userid7' => $user->id | |
b5e9faa6 | 385 | ); |
f68b11f7 TH |
386 | $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto); |
387 | ||
388 | // We want to get the messages that have not been read. These are stored in the 'message' table. It is the | |
389 | // exact same query as the one above, except for the table we are querying. So, simply replace references to | |
390 | // the 'message_read' table with the 'message' table. | |
391 | $sql = str_replace('{message_read}', '{message}', $sql); | |
eda6bc19 | 392 | $sql = str_replace('1 as isread', '0 as isread', $sql); |
f68b11f7 | 393 | $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto); |
bcab42da | 394 | |
f68b11f7 TH |
395 | // Union the 2 result sets together looking for the message with the most |
396 | // recent timecreated for each other user. | |
397 | // $conversation->id (the array key) is the other user's ID. | |
d9b5f9bb | 398 | $conversations = array(); |
bcab42da | 399 | $conversation_arrays = array($unread, $read); |
400 | foreach ($conversation_arrays as $conversation_array) { | |
401 | foreach ($conversation_array as $conversation) { | |
b5e9faa6 | 402 | if (!isset($conversations[$conversation->id])) { |
bcab42da | 403 | $conversations[$conversation->id] = $conversation; |
b5e9faa6 AN |
404 | } else { |
405 | $current = $conversations[$conversation->id]; | |
406 | if ($current->timecreated < $conversation->timecreated) { | |
407 | $conversations[$conversation->id] = $conversation; | |
408 | } else if ($current->timecreated == $conversation->timecreated) { | |
409 | if ($current->mid < $conversation->mid) { | |
410 | $conversations[$conversation->id] = $conversation; | |
411 | } | |
412 | } | |
bcab42da | 413 | } |
414 | } | |
415 | } | |
416 | ||
6109f7af AD |
417 | // Sort the conversations by $conversation->timecreated, newest to oldest |
418 | // There may be multiple conversations with the same timecreated | |
419 | // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work | |
2f1e464a | 420 | $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC); |
6109f7af | 421 | $conversations = array_reverse($conversations); |
bcab42da | 422 | |
423 | return $conversations; | |
424 | } | |
425 | ||
bcab42da | 426 | /** |
427 | * Get the users recent event notifications | |
ebe0c008 | 428 | * |
bcab42da | 429 | * @param object $user the current user |
430 | * @param int $limitfrom can be used for paging | |
431 | * @param int $limitto can be used for paging | |
432 | * @return array | |
433 | */ | |
434 | function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) { | |
435 | global $DB; | |
436 | ||
437 | $userfields = user_picture::fields('u', array('lastaccess')); | |
4048f5b3 | 438 | $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname |
bcab42da | 439 | FROM {message_read} mr |
440 | JOIN {user} u ON u.id=mr.useridfrom | |
441 | WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification | |
e6aae58d | 442 | ORDER BY mr.timecreated DESC"; |
bcab42da | 443 | $params = array('userid1' => $user->id, 'notification' => 1); |
444 | ||
445 | $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto); | |
446 | return $notifications; | |
447 | } | |
448 | ||
4048f5b3 PS |
449 | /** |
450 | * Try to guess how to convert the message to html. | |
451 | * | |
452 | * @access private | |
453 | * | |
454 | * @param stdClass $message | |
455 | * @param bool $forcetexttohtml | |
456 | * @return string html fragment | |
457 | */ | |
458 | function message_format_message_text($message, $forcetexttohtml = false) { | |
459 | // Note: this is a very nasty hack that tries to work around the weird messaging rules and design. | |
460 | ||
461 | $options = new stdClass(); | |
462 | $options->para = false; | |
64e83119 | 463 | $options->blanktarget = true; |
4048f5b3 PS |
464 | |
465 | $format = $message->fullmessageformat; | |
466 | ||
40e50128 | 467 | if (strval($message->smallmessage) !== '') { |
4048f5b3 | 468 | if ($message->notification == 1) { |
40e50128 | 469 | if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') { |
4048f5b3 PS |
470 | $format = FORMAT_PLAIN; |
471 | } | |
472 | } | |
473 | $messagetext = $message->smallmessage; | |
474 | ||
475 | } else if ($message->fullmessageformat == FORMAT_HTML) { | |
40e50128 | 476 | if (strval($message->fullmessagehtml) !== '') { |
4048f5b3 PS |
477 | $messagetext = $message->fullmessagehtml; |
478 | } else { | |
479 | $messagetext = $message->fullmessage; | |
480 | $format = FORMAT_MOODLE; | |
481 | } | |
482 | ||
483 | } else { | |
40e50128 | 484 | if (strval($message->fullmessage) !== '') { |
4048f5b3 PS |
485 | $messagetext = $message->fullmessage; |
486 | } else { | |
487 | $messagetext = $message->fullmessagehtml; | |
488 | $format = FORMAT_HTML; | |
489 | } | |
490 | } | |
491 | ||
492 | if ($forcetexttohtml) { | |
493 | // This is a crazy hack, why not set proper format when creating the notifications? | |
494 | if ($format === FORMAT_PLAIN) { | |
495 | $format = FORMAT_MOODLE; | |
496 | } | |
497 | } | |
498 | return format_text($messagetext, $format, $options); | |
499 | } | |
500 | ||
bcab42da | 501 | /** |
502 | * Add the selected user as a contact for the current user | |
ebe0c008 | 503 | * |
bcab42da | 504 | * @param int $contactid the ID of the user to add as a contact |
505 | * @param int $blocked 1 if you wish to block the contact | |
34c2f347 | 506 | * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified. |
bcab42da | 507 | * @return bool/int false if the $contactid isnt a valid user id. True if no changes made. |
508 | * Otherwise returns the result of update_record() or insert_record() | |
509 | */ | |
34c2f347 | 510 | function message_add_contact($contactid, $blocked = 0, $userid = 0) { |
fd1cb1e8 | 511 | global $USER, $DB; |
531e58f1 | 512 | |
bcab42da | 513 | if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid |
e8e2d7f1 | 514 | return false; |
515 | } | |
531e58f1 | 516 | |
34c2f347 MN |
517 | if (empty($userid)) { |
518 | $userid = $USER->id; | |
519 | } | |
520 | ||
3f3d9521 | 521 | // Check if a record already exists as we may be changing blocking status. |
34c2f347 | 522 | if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) { |
3f3d9521 | 523 | // Check if blocking status has been changed. |
42c0b047 | 524 | if ($contact->blocked != $blocked) { |
e8e2d7f1 | 525 | $contact->blocked = $blocked; |
3f3d9521 MN |
526 | $DB->update_record('message_contacts', $contact); |
527 | ||
528 | if ($blocked == 1) { | |
529 | // Trigger event for blocking a contact. | |
530 | $event = \core\event\message_contact_blocked::create(array( | |
531 | 'objectid' => $contact->id, | |
532 | 'userid' => $contact->userid, | |
533 | 'relateduserid' => $contact->contactid, | |
534 | 'context' => context_user::instance($contact->userid) | |
535 | )); | |
536 | $event->add_record_snapshot('message_contacts', $contact); | |
537 | $event->trigger(); | |
cd609365 MN |
538 | } else { |
539 | // Trigger event for unblocking a contact. | |
540 | $event = \core\event\message_contact_unblocked::create(array( | |
541 | 'objectid' => $contact->id, | |
542 | 'userid' => $contact->userid, | |
543 | 'relateduserid' => $contact->contactid, | |
544 | 'context' => context_user::instance($contact->userid) | |
545 | )); | |
546 | $event->add_record_snapshot('message_contacts', $contact); | |
547 | $event->trigger(); | |
3f3d9521 MN |
548 | } |
549 | ||
550 | return true; | |
e8e2d7f1 | 551 | } else { |
447df209 | 552 | // No change to blocking status. |
e8e2d7f1 | 553 | return true; |
554 | } | |
531e58f1 | 555 | |
172186b8 | 556 | } else { |
447df209 | 557 | // New contact record. |
92701024 | 558 | $contact = new stdClass(); |
34c2f347 | 559 | $contact->userid = $userid; |
e8e2d7f1 | 560 | $contact->contactid = $contactid; |
561 | $contact->blocked = $blocked; | |
0d9bdf61 MN |
562 | $contact->id = $DB->insert_record('message_contacts', $contact); |
563 | ||
2236a565 | 564 | $eventparams = array( |
0d9bdf61 MN |
565 | 'objectid' => $contact->id, |
566 | 'userid' => $contact->userid, | |
567 | 'relateduserid' => $contact->contactid, | |
568 | 'context' => context_user::instance($contact->userid) | |
2236a565 FM |
569 | ); |
570 | ||
571 | if ($blocked) { | |
572 | $event = \core\event\message_contact_blocked::create($eventparams); | |
573 | } else { | |
574 | $event = \core\event\message_contact_added::create($eventparams); | |
575 | } | |
576 | // Trigger event. | |
0d9bdf61 MN |
577 | $event->trigger(); |
578 | ||
579 | return true; | |
172186b8 | 580 | } |
581 | } | |
582 | ||
bcab42da | 583 | /** |
584 | * remove a contact | |
ebe0c008 | 585 | * |
6fbd60ef | 586 | * @param int $contactid the user ID of the contact to remove |
34c2f347 | 587 | * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified. |
bcab42da | 588 | * @return bool returns the result of delete_records() |
589 | */ | |
34c2f347 | 590 | function message_remove_contact($contactid, $userid = 0) { |
fd1cb1e8 | 591 | global $USER, $DB; |
5edf9f3b | 592 | |
34c2f347 MN |
593 | if (empty($userid)) { |
594 | $userid = $USER->id; | |
595 | } | |
596 | ||
597 | if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) { | |
5edf9f3b MN |
598 | $DB->delete_records('message_contacts', array('id' => $contact->id)); |
599 | ||
600 | // Trigger event for removing a contact. | |
601 | $event = \core\event\message_contact_removed::create(array( | |
602 | 'objectid' => $contact->id, | |
603 | 'userid' => $contact->userid, | |
604 | 'relateduserid' => $contact->contactid, | |
605 | 'context' => context_user::instance($contact->userid) | |
606 | )); | |
607 | $event->add_record_snapshot('message_contacts', $contact); | |
608 | $event->trigger(); | |
609 | ||
610 | return true; | |
611 | } | |
612 | ||
613 | return false; | |
e8e2d7f1 | 614 | } |
615 | ||
bcab42da | 616 | /** |
617 | * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact. | |
ebe0c008 | 618 | * |
bcab42da | 619 | * @param int $contactid the user ID of the contact to unblock |
34c2f347 MN |
620 | * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user |
621 | * if not specified. | |
bcab42da | 622 | * @return bool returns the result of delete_records() |
623 | */ | |
34c2f347 MN |
624 | function message_unblock_contact($contactid, $userid = 0) { |
625 | return message_add_contact($contactid, 0, $userid); | |
e8e2d7f1 | 626 | } |
627 | ||
bcab42da | 628 | /** |
3f3d9521 | 629 | * Block a user. |
ebe0c008 | 630 | * |
bcab42da | 631 | * @param int $contactid the user ID of the user to block |
34c2f347 MN |
632 | * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user |
633 | * if not specified. | |
3f3d9521 | 634 | * @return bool |
bcab42da | 635 | */ |
34c2f347 MN |
636 | function message_block_contact($contactid, $userid = 0) { |
637 | return message_add_contact($contactid, 1, $userid); | |
e8e2d7f1 | 638 | } |
639 | ||
36d29c08 MN |
640 | /** |
641 | * Checks if a user can delete a message. | |
642 | * | |
643 | * @param stdClass $message the message to delete | |
644 | * @param string $userid the user id of who we want to delete the message for (this may be done by the admin | |
645 | * but will still seem as if it was by the user) | |
646 | * @return bool Returns true if a user can delete the message, false otherwise. | |
647 | */ | |
648 | function message_can_delete_message($message, $userid) { | |
649 | global $USER; | |
650 | ||
651 | if ($message->useridfrom == $userid) { | |
652 | $userdeleting = 'useridfrom'; | |
653 | } else if ($message->useridto == $userid) { | |
654 | $userdeleting = 'useridto'; | |
655 | } else { | |
656 | return false; | |
657 | } | |
658 | ||
659 | $systemcontext = context_system::instance(); | |
660 | ||
661 | // Let's check if the user is allowed to delete this message. | |
662 | if (has_capability('moodle/site:deleteanymessage', $systemcontext) || | |
663 | ((has_capability('moodle/site:deleteownmessage', $systemcontext) && | |
664 | $USER->id == $message->$userdeleting))) { | |
665 | return true; | |
666 | } | |
667 | ||
668 | return false; | |
669 | } | |
670 | ||
671 | /** | |
672 | * Deletes a message. | |
673 | * | |
674 | * This function does not verify any permissions. | |
675 | * | |
676 | * @param stdClass $message the message to delete | |
677 | * @param string $userid the user id of who we want to delete the message for (this may be done by the admin | |
678 | * but will still seem as if it was by the user) | |
679 | * @return bool | |
680 | */ | |
681 | function message_delete_message($message, $userid) { | |
682 | global $DB; | |
683 | ||
684 | // The column we want to alter. | |
685 | if ($message->useridfrom == $userid) { | |
686 | $coltimedeleted = 'timeuserfromdeleted'; | |
687 | } else if ($message->useridto == $userid) { | |
688 | $coltimedeleted = 'timeusertodeleted'; | |
689 | } else { | |
690 | return false; | |
691 | } | |
692 | ||
693 | // Don't update it if it's already been deleted. | |
694 | if ($message->$coltimedeleted > 0) { | |
695 | return false; | |
696 | } | |
697 | ||
698 | // Get the table we want to update. | |
699 | if (isset($message->timeread)) { | |
700 | $messagetable = 'message_read'; | |
701 | } else { | |
702 | $messagetable = 'message'; | |
703 | } | |
704 | ||
705 | // Mark the message as deleted. | |
706 | $updatemessage = new stdClass(); | |
707 | $updatemessage->id = $message->id; | |
708 | $updatemessage->$coltimedeleted = time(); | |
b5e617e2 MN |
709 | $success = $DB->update_record($messagetable, $updatemessage); |
710 | ||
711 | if ($success) { | |
712 | // Trigger event for deleting a message. | |
713 | \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto, | |
714 | $userid, $messagetable, $message->id)->trigger(); | |
715 | } | |
716 | ||
717 | return $success; | |
36d29c08 MN |
718 | } |
719 | ||
bcab42da | 720 | /** |
721 | * Load a user's contact record | |
ebe0c008 | 722 | * |
bcab42da | 723 | * @param int $contactid the user ID of the user whose contact record you want |
ebe0c008 | 724 | * @return array message contacts |
bcab42da | 725 | */ |
e8e2d7f1 | 726 | function message_get_contact($contactid) { |
fd1cb1e8 | 727 | global $USER, $DB; |
bcab42da | 728 | return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid)); |
e8e2d7f1 | 729 | } |
531e58f1 | 730 | |
bcab42da | 731 | /** |
732 | * Print a message contact link | |
ebe0c008 | 733 | * |
bcab42da | 734 | * @param int $userid the ID of the user to apply to action to |
735 | * @param string $linktype can be add, remove, block or unblock | |
736 | * @param bool $return if true return the link as a string. If false echo the link. | |
737 | * @param string $script the URL to send the user to when the link is clicked. If null, the current page. | |
738 | * @param bool $text include text next to the icons? | |
739 | * @param bool $icon include a graphical icon? | |
740 | * @return string if $return is true otherwise bool | |
741 | */ | |
c8621a02 | 742 | function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) { |
bcab42da | 743 | global $OUTPUT, $PAGE; |
e520509a | 744 | |
6898e848 | 745 | //hold onto the strings as we're probably creating a bunch of links |
e520509a | 746 | static $str; |
747 | ||
c8621a02 | 748 | if (empty($script)) { |
cee92282 | 749 | //strip off previous action params like 'removecontact' |
4090a30f | 750 | $script = message_remove_url_params($PAGE->url); |
c8621a02 AD |
751 | } |
752 | ||
e520509a | 753 | if (empty($str->blockcontact)) { |
b85b25eb | 754 | $str = new stdClass(); |
e520509a | 755 | $str->blockcontact = get_string('blockcontact', 'message'); |
756 | $str->unblockcontact = get_string('unblockcontact', 'message'); | |
757 | $str->removecontact = get_string('removecontact', 'message'); | |
758 | $str->addcontact = get_string('addcontact', 'message'); | |
759 | } | |
760 | ||
5d6b319b | 761 | $command = $linktype.'contact'; |
762 | $string = $str->{$command}; | |
6898e848 AD |
763 | |
764 | $safealttext = s($string); | |
765 | ||
766 | $safestring = ''; | |
3a11c09f | 767 | if (!empty($text)) { |
6898e848 | 768 | $safestring = $safealttext; |
c8621a02 AD |
769 | } |
770 | ||
771 | $img = ''; | |
772 | if ($icon) { | |
6898e848 AD |
773 | $iconpath = null; |
774 | switch ($linktype) { | |
775 | case 'block': | |
776 | $iconpath = 't/block'; | |
777 | break; | |
778 | case 'unblock': | |
f2bba619 | 779 | $iconpath = 't/unblock'; |
6898e848 AD |
780 | break; |
781 | case 'remove': | |
f2bba619 | 782 | $iconpath = 't/removecontact'; |
6898e848 AD |
783 | break; |
784 | case 'add': | |
785 | default: | |
f2bba619 | 786 | $iconpath = 't/addcontact'; |
6898e848 AD |
787 | } |
788 | ||
789 | $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />'; | |
082864f9 | 790 | } |
5d6b319b | 791 | |
c8621a02 | 792 | $output = '<span class="'.$linktype.'contact">'. |
5d6b319b | 793 | '<a href="'.$script.'&'.$command.'='.$userid. |
01e85326 | 794 | '&sesskey='.sesskey().'" title="'.$safealttext.'">'. |
c8621a02 | 795 | $img. |
6898e848 | 796 | $safestring.'</a></span>'; |
5d6b319b | 797 | |
e520509a | 798 | if ($return) { |
799 | return $output; | |
082864f9 | 800 | } else { |
e520509a | 801 | echo $output; |
082864f9 | 802 | return true; |
803 | } | |
804 | } | |
805 | ||
bcab42da | 806 | /** |
807 | * echo or return a link to take the user to the full message history between themselves and another user | |
ebe0c008 | 808 | * |
dd6d83c1 | 809 | * @param int $userid1 the ID of the user displayed on the left (usually the current user) |
bcab42da | 810 | * @param int $userid2 the ID of the other user |
811 | * @param bool $return true to return the link as a string. False to echo the link. | |
812 | * @param string $keywords any keywords to highlight in the message history | |
813 | * @param string $position anchor name to jump to within the message history | |
814 | * @param string $linktext optionally specify the link text | |
815 | * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean. | |
816 | */ | |
817 | function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') { | |
8f0137e1 | 818 | global $OUTPUT, $PAGE; |
830d0af6 | 819 | static $strmessagehistory; |
820 | ||
821 | if (empty($strmessagehistory)) { | |
822 | $strmessagehistory = get_string('messagehistory', 'message'); | |
823 | } | |
2514081c | 824 | |
e520509a | 825 | if ($position) { |
826 | $position = "#$position"; | |
827 | } | |
38c6a928 | 828 | if ($keywords) { |
829 | $keywords = "&search=".urlencode($keywords); | |
830 | } | |
62119d65 | 831 | |
830d0af6 | 832 | if ($linktext == 'icon') { // Icon only |
f2bba619 | 833 | $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />'; |
830d0af6 | 834 | } else if ($linktext == 'both') { // Icon and standard name |
f2bba619 | 835 | $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />'; |
830d0af6 | 836 | $fulllink .= ' '.$strmessagehistory; |
837 | } else if ($linktext) { // Custom name | |
838 | $fulllink = $linktext; | |
839 | } else { // Standard name only | |
840 | $fulllink = $strmessagehistory; | |
fd7006f6 | 841 | } |
842 | ||
40a26286 | 843 | $popupoptions = array( |
844 | 'height' => 500, | |
845 | 'width' => 500, | |
846 | 'menubar' => false, | |
847 | 'location' => false, | |
848 | 'status' => true, | |
849 | 'scrollbars' => true, | |
850 | 'resizable' => true); | |
851 | ||
dd6d83c1 | 852 | $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position"); |
8f0137e1 MG |
853 | if ($PAGE->url && $PAGE->url->get_param('viewing')) { |
854 | $link->param('viewing', $PAGE->url->get_param('viewing')); | |
855 | } | |
c8621a02 | 856 | $action = null; |
bcab42da | 857 | $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory)); |
62119d65 | 858 | |
5d6b319b | 859 | $str = '<span class="history">'.$str.'</span>'; |
860 | ||
bcab42da | 861 | if ($return) { |
62119d65 | 862 | return $str; |
863 | } else { | |
864 | echo $str; | |
865 | return true; | |
866 | } | |
867 | } | |
e8e2d7f1 | 868 | |
869 | ||
870 | /** | |
a03330bd FM |
871 | * Search through course users. |
872 | * | |
873 | * If $courseids contains the site course then this function searches | |
874 | * through all undeleted and confirmed users. | |
e8e2d7f1 | 875 | * |
a03330bd FM |
876 | * @param int|array $courseids Course ID or array of course IDs. |
877 | * @param string $searchtext the text to search for. | |
878 | * @param string $sort the column name to order by. | |
2e2d1977 | 879 | * @param string|array $exceptions comma separated list or array of user IDs to exclude. |
a03330bd | 880 | * @return array An array of {@link $USER} records. |
e8e2d7f1 | 881 | */ |
a03330bd | 882 | function message_search_users($courseids, $searchtext, $sort='', $exceptions='') { |
fd1cb1e8 | 883 | global $CFG, $USER, $DB; |
e8e2d7f1 | 884 | |
a03330bd FM |
885 | // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value. |
886 | if (!$courseids) { | |
887 | $courseids = array(SITEID); | |
888 | } | |
889 | ||
890 | // Allow an integer to be passed. | |
891 | if (!is_array($courseids)) { | |
892 | $courseids = array($courseids); | |
893 | } | |
894 | ||
245ac557 | 895 | $fullname = $DB->sql_fullname(); |
2e2d1977 | 896 | $ufields = user_picture::fields('u'); |
e8e2d7f1 | 897 | |
898 | if (!empty($sort)) { | |
899 | $order = ' ORDER BY '. $sort; | |
900 | } else { | |
901 | $order = ''; | |
902 | } | |
903 | ||
2e2d1977 AD |
904 | $params = array( |
905 | 'userid' => $USER->id, | |
906 | 'query' => "%$searchtext%" | |
907 | ); | |
908 | ||
909 | if (empty($exceptions)) { | |
910 | $exceptions = array(); | |
911 | } else if (!empty($exceptions) && is_string($exceptions)) { | |
912 | $exceptions = explode(',', $exceptions); | |
913 | } | |
914 | ||
915 | // Ignore self and guest account. | |
916 | $exceptions[] = $USER->id; | |
917 | $exceptions[] = $CFG->siteguest; | |
918 | ||
919 | // Exclude exceptions from the search result. | |
920 | list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false); | |
921 | $except = ' AND u.id ' . $except; | |
922 | $params = array_merge($params_except, $params); | |
a03330bd FM |
923 | |
924 | if (in_array(SITEID, $courseids)) { | |
925 | // Search on site level. | |
3a11c09f | 926 | return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked |
d9eef08a | 927 | FROM {user} u |
fd1cb1e8 | 928 | LEFT JOIN {message_contacts} mc |
2e2d1977 | 929 | ON mc.contactid = u.id AND mc.userid = :userid |
3a11c09f | 930 | WHERE u.deleted = '0' AND u.confirmed = '1' |
2e2d1977 | 931 | AND (".$DB->sql_like($fullname, ':query', false).") |
fd1cb1e8 | 932 | $except |
933 | $order", $params); | |
e8e2d7f1 | 934 | } else { |
a03330bd | 935 | // Search in courses. |
a03330bd FM |
936 | |
937 | // Getting the context IDs or each course. | |
938 | $contextids = array(); | |
939 | foreach ($courseids as $courseid) { | |
940 | $context = context_course::instance($courseid); | |
941 | $contextids = array_merge($contextids, $context->get_parent_context_ids(true)); | |
942 | } | |
2e2d1977 | 943 | list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context'); |
a03330bd FM |
944 | $params = array_merge($params, $contextparams); |
945 | ||
946 | // Everyone who has a role assignment in this course or higher. | |
947 | // TODO: add enabled enrolment join here (skodak) | |
186fc534 | 948 | $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked |
b6e52658 | 949 | FROM {user} u |
fd1cb1e8 | 950 | JOIN {role_assignments} ra ON ra.userid = u.id |
951 | LEFT JOIN {message_contacts} mc | |
2e2d1977 | 952 | ON mc.contactid = u.id AND mc.userid = :userid |
3a11c09f | 953 | WHERE u.deleted = '0' AND u.confirmed = '1' |
2e2d1977 | 954 | AND (".$DB->sql_like($fullname, ':query', false).") |
a03330bd | 955 | AND ra.contextid $contextwhere |
fd1cb1e8 | 956 | $except |
957 | $order", $params); | |
d76a5a7f | 958 | |
959 | return $users; | |
e8e2d7f1 | 960 | } |
961 | } | |
962 | ||
bcab42da | 963 | /** |
447df209 AD |
964 | * Search a user's messages |
965 | * | |
966 | * Returns a list of posts found using an array of search terms | |
967 | * eg word +word -word | |
ebe0c008 | 968 | * |
bcab42da | 969 | * @param array $searchterms an array of search terms (strings) |
970 | * @param bool $fromme include messages from the user? | |
971 | * @param bool $tome include messages to the user? | |
972 | * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented | |
973 | * @param int $userid the user ID of the current user | |
974 | * @return mixed An array of messages or false if no matching messages were found | |
975 | */ | |
082864f9 | 976 | function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) { |
fd1cb1e8 | 977 | global $CFG, $USER, $DB; |
e8e2d7f1 | 978 | |
447df209 | 979 | // If user is searching all messages check they are allowed to before doing anything else. |
bf0f06b1 | 980 | if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) { |
48e03792 AD |
981 | print_error('accessdenied','admin'); |
982 | } | |
983 | ||
447df209 | 984 | // If no userid sent then assume current user. |
531e58f1 | 985 | if ($userid == 0) $userid = $USER->id; |
082864f9 | 986 | |
447df209 | 987 | // Some differences in SQL syntax. |
d9eef08a | 988 | if ($DB->sql_regex_supported()) { |
989 | $REGEXP = $DB->sql_regex(true); | |
990 | $NOTREGEXP = $DB->sql_regex(false); | |
e8e2d7f1 | 991 | } |
992 | ||
d9eef08a | 993 | $searchcond = array(); |
994 | $params = array(); | |
995 | $i = 0; | |
e8e2d7f1 | 996 | |
447df209 AD |
997 | // Preprocess search terms to check whether we have at least 1 eligible search term. |
998 | // If we do we can drop words around it like 'a'. | |
c3931654 AD |
999 | $dropshortwords = false; |
1000 | foreach ($searchterms as $searchterm) { | |
1001 | if (strlen($searchterm) >= 2) { | |
1002 | $dropshortwords = true; | |
1003 | } | |
1004 | } | |
1005 | ||
e8e2d7f1 | 1006 | foreach ($searchterms as $searchterm) { |
d9eef08a | 1007 | $i++; |
1008 | ||
447df209 | 1009 | $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle. |
d9eef08a | 1010 | |
c3931654 | 1011 | if ($dropshortwords && strlen($searchterm) < 2) { |
e8e2d7f1 | 1012 | continue; |
1013 | } | |
447df209 | 1014 | // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search. |
d9eef08a | 1015 | if (!$DB->sql_regex_supported()) { |
1016 | if (substr($searchterm, 0, 1) == '-') { | |
47586394 | 1017 | $NOT = true; |
d9eef08a | 1018 | } |
6bb4875f | 1019 | $searchterm = trim($searchterm, '+-'); |
1020 | } | |
1021 | ||
e8e2d7f1 | 1022 | if (substr($searchterm,0,1) == "+") { |
1023 | $searchterm = substr($searchterm,1); | |
d9eef08a | 1024 | $searchterm = preg_quote($searchterm, '|'); |
3d143595 | 1025 | $searchcond[] = "m.fullmessage $REGEXP :ss$i"; |
d9eef08a | 1026 | $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)"; |
1027 | ||
e8e2d7f1 | 1028 | } else if (substr($searchterm,0,1) == "-") { |
1029 | $searchterm = substr($searchterm,1); | |
d9eef08a | 1030 | $searchterm = preg_quote($searchterm, '|'); |
3d143595 | 1031 | $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i"; |
d9eef08a | 1032 | $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)"; |
1033 | ||
e8e2d7f1 | 1034 | } else { |
47586394 | 1035 | $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT); |
d9eef08a | 1036 | $params['ss'.$i] = "%$searchterm%"; |
e8e2d7f1 | 1037 | } |
172186b8 | 1038 | } |
1039 | ||
d9eef08a | 1040 | if (empty($searchcond)) { |
dd54dc31 | 1041 | $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false); |
ff49c389 | 1042 | $params['ss1'] = "%"; |
1043 | } else { | |
1044 | $searchcond = implode(" AND ", $searchcond); | |
8a51efe9 | 1045 | } |
e8e2d7f1 | 1046 | |
447df209 AD |
1047 | // There are several possibilities |
1048 | // 1. courseid = SITEID : The admin is searching messages by all users | |
1049 | // 2. courseid = ?? : A teacher is searching messages by users in | |
1050 | // one of their courses - currently disabled | |
1051 | // 3. courseid = none : User is searching their own messages; | |
1052 | // a. Messages from user | |
1053 | // b. Messages to user | |
1054 | // c. Messages to and from user | |
082864f9 | 1055 | |
36d29c08 MN |
1056 | if ($fromme && $tome) { |
1057 | $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR | |
1058 | (useridfrom = :useridfrom AND timeuserfromdeleted = 0))"; | |
1059 | $params['useridto'] = $userid; | |
1060 | $params['useridfrom'] = $userid; | |
1061 | } else if ($fromme) { | |
1062 | $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)"; | |
1063 | $params['useridfrom'] = $userid; | |
1064 | } else if ($tome) { | |
1065 | $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)"; | |
1066 | $params['useridto'] = $userid; | |
1067 | } | |
447df209 | 1068 | if ($courseid == SITEID) { // Admin is searching all messages. |
f91528d9 | 1069 | $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated |
d9eef08a | 1070 | FROM {message_read} m |
c3931654 | 1071 | WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS); |
f91528d9 | 1072 | $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated |
d9eef08a | 1073 | FROM {message} m |
c3931654 | 1074 | WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS); |
d9eef08a | 1075 | |
1076 | } else if ($courseid !== 'none') { | |
447df209 | 1077 | // This has not been implemented due to security concerns. |
d9eef08a | 1078 | $m_read = array(); |
1079 | $m_unread = array(); | |
e8e2d7f1 | 1080 | |
082864f9 | 1081 | } else { |
531e58f1 | 1082 | |
d9eef08a | 1083 | if ($fromme and $tome) { |
1084 | $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)"; | |
1085 | $params['userid1'] = $userid; | |
1086 | $params['userid2'] = $userid; | |
1087 | ||
1088 | } else if ($fromme) { | |
1089 | $searchcond .= " AND m.useridfrom=:userid"; | |
1090 | $params['userid'] = $userid; | |
531e58f1 | 1091 | |
d9eef08a | 1092 | } else if ($tome) { |
1093 | $searchcond .= " AND m.useridto=:userid"; | |
1094 | $params['userid'] = $userid; | |
1095 | } | |
531e58f1 | 1096 | |
f91528d9 | 1097 | $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated |
d9eef08a | 1098 | FROM {message_read} m |
c3931654 | 1099 | WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS); |
f91528d9 | 1100 | $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated |
d9eef08a | 1101 | FROM {message} m |
c3931654 | 1102 | WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS); |
531e58f1 | 1103 | |
e8e2d7f1 | 1104 | } |
1105 | ||
082864f9 | 1106 | /// The keys may be duplicated in $m_read and $m_unread so we can't |
1107 | /// do a simple concatenation | |
92701024 | 1108 | $messages = array(); |
d9eef08a | 1109 | foreach ($m_read as $m) { |
1110 | $messages[] = $m; | |
1111 | } | |
1112 | foreach ($m_unread as $m) { | |
1113 | $messages[] = $m; | |
1114 | } | |
e8e2d7f1 | 1115 | |
1116 | return (empty($messages)) ? false : $messages; | |
172186b8 | 1117 | } |
1118 | ||
bcab42da | 1119 | /** |
1120 | * Given a message object that we already know has a long message | |
1121 | * this function truncates the message nicely to the first | |
1122 | * sane place between $CFG->forum_longpost and $CFG->forum_shortpost | |
ebe0c008 | 1123 | * |
bcab42da | 1124 | * @param string $message the message |
1125 | * @param int $minlength the minimum length to trim the message to | |
1126 | * @return string the shortened message | |
1127 | */ | |
1128 | function message_shorten_message($message, $minlength = 0) { | |
e8e2d7f1 | 1129 | $i = 0; |
1130 | $tag = false; | |
1131 | $length = strlen($message); | |
1132 | $count = 0; | |
1133 | $stopzone = false; | |
1134 | $truncate = 0; | |
1135 | if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH; | |
531e58f1 | 1136 | |
e8e2d7f1 | 1137 | |
1138 | for ($i=0; $i<$length; $i++) { | |
1139 | $char = $message[$i]; | |
1140 | ||
1141 | switch ($char) { | |
1142 | case "<": | |
1143 | $tag = true; | |
1144 | break; | |
1145 | case ">": | |
1146 | $tag = false; | |
1147 | break; | |
1148 | default: | |
1149 | if (!$tag) { | |
1150 | if ($stopzone) { | |
1151 | if ($char == '.' or $char == ' ') { | |
1152 | $truncate = $i+1; | |
1153 | break 2; | |
1154 | } | |
1155 | } | |
1156 | $count++; | |
1157 | } | |
1158 | break; | |
1159 | } | |
1160 | if (!$stopzone) { | |
1161 | if ($count > $minlength) { | |
1162 | $stopzone = true; | |
1163 | } | |
1164 | } | |
1165 | } | |
1166 | ||
1167 | if (!$truncate) { | |
1168 | $truncate = $i; | |
1169 | } | |
1170 | ||
1171 | return substr($message, 0, $truncate); | |
1172 | } | |
1173 | ||
38c6a928 | 1174 | |
d9eef08a | 1175 | /** |
38c6a928 | 1176 | * Given a string and an array of keywords, this function looks |
1177 | * for the first keyword in the string, and then chops out a | |
1178 | * small section from the text that shows that word in context. | |
ebe0c008 | 1179 | * |
bcab42da | 1180 | * @param string $message the text to search |
1181 | * @param array $keywords array of keywords to find | |
38c6a928 | 1182 | */ |
1183 | function message_get_fragment($message, $keywords) { | |
1184 | ||
f3832596 | 1185 | $fullsize = 160; |
38c6a928 | 1186 | $halfsize = (int)($fullsize/2); |
1187 | ||
1188 | $message = strip_tags($message); | |
1189 | ||
1190 | foreach ($keywords as $keyword) { // Just get the first one | |
1191 | if ($keyword !== '') { | |
1192 | break; | |
1193 | } | |
1194 | } | |
1195 | if (empty($keyword)) { // None found, so just return start of message | |
1196 | return message_shorten_message($message, 30); | |
1197 | } | |
1198 | ||
1199 | $leadin = $leadout = ''; | |
1200 | ||
1201 | /// Find the start of the fragment | |
1202 | $start = 0; | |
1203 | $length = strlen($message); | |
1204 | ||
1205 | $pos = strpos($message, $keyword); | |
1206 | if ($pos > $halfsize) { | |
1207 | $start = $pos - $halfsize; | |
1208 | $leadin = '...'; | |
1209 | } | |
1210 | /// Find the end of the fragment | |
1211 | $end = $start + $fullsize; | |
1212 | if ($end > $length) { | |
1213 | $end = $length; | |
1214 | } else { | |
1215 | $leadout = '...'; | |
1216 | } | |
1217 | ||
1218 | /// Pull out the fragment and format it | |
1219 | ||
1220 | $fragment = substr($message, $start, $end - $start); | |
1221 | $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout; | |
1222 | return $fragment; | |
1223 | } | |
1224 | ||
bcab42da | 1225 | /** |
1226 | * Retrieve the messages between two users | |
ebe0c008 | 1227 | * |
bcab42da | 1228 | * @param object $user1 the current user |
1229 | * @param object $user2 the other user | |
1230 | * @param int $limitnum the maximum number of messages to retrieve | |
1231 | * @param bool $viewingnewmessages are we currently viewing new messages? | |
1232 | */ | |
a813a748 AD |
1233 | function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) { |
1234 | global $DB, $CFG; | |
fd1cb1e8 | 1235 | |
c8621a02 AD |
1236 | $messages = array(); |
1237 | ||
1238 | //we want messages sorted oldest to newest but if getting a subset of messages we need to sort | |
1239 | //desc to get the last $limitnum messages then flip the order in php | |
1240 | $sort = 'asc'; | |
1241 | if ($limitnum>0) { | |
1242 | $sort = 'desc'; | |
1243 | } | |
1244 | ||
a813a748 AD |
1245 | $notificationswhere = null; |
1246 | //we have just moved new messages to read. If theyre here to see new messages dont hide notifications | |
1247 | if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) { | |
1248 | $notificationswhere = 'AND notification=0'; | |
1249 | } | |
1250 | ||
33bd52f3 AD |
1251 | //prevent notifications of your own actions appearing in your own message history |
1252 | $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)'; | |
1253 | ||
36d29c08 MN |
1254 | $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR |
1255 | (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))"; | |
1256 | if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere, | |
33bd52f3 | 1257 | array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id), |
c8621a02 AD |
1258 | "timecreated $sort", '*', 0, $limitnum)) { |
1259 | foreach ($messages_read as $message) { | |
6109f7af | 1260 | $messages[] = $message; |
c8621a02 AD |
1261 | } |
1262 | } | |
36d29c08 | 1263 | if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere, |
33bd52f3 | 1264 | array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id), |
c8621a02 | 1265 | "timecreated $sort", '*', 0, $limitnum)) { |
b9ee0638 | 1266 | foreach ($messages_new as $message) { |
6109f7af | 1267 | $messages[] = $message; |
b9ee0638 | 1268 | } |
1269 | } | |
c8621a02 | 1270 | |
2f1e464a | 1271 | $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC); |
6109f7af | 1272 | |
c8621a02 | 1273 | //if we only want the last $limitnum messages |
2846b9a6 | 1274 | $messagecount = count($messages); |
6109f7af AD |
1275 | if ($limitnum > 0 && $messagecount > $limitnum) { |
1276 | $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true); | |
c8621a02 | 1277 | } |
3a11c09f | 1278 | |
b9ee0638 | 1279 | return $messages; |
1280 | } | |
1281 | ||
bcab42da | 1282 | /** |
1283 | * Format a message for display in the message history | |
ebe0c008 | 1284 | * |
bcab42da | 1285 | * @param object $message the message object |
1286 | * @param string $format optional date format | |
1287 | * @param string $keywords keywords to highlight | |
1288 | * @param string $class CSS class to apply to the div around the message | |
1289 | * @return string the formatted message | |
1290 | */ | |
1291 | function message_format_message($message, $format='', $keywords='', $class='other') { | |
acd21a2d | 1292 | |
1293 | static $dateformat; | |
1294 | ||
bcab42da | 1295 | //if we haven't previously set the date format or they've supplied a new one |
1296 | if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) { | |
acd21a2d | 1297 | if ($format) { |
1298 | $dateformat = $format; | |
1299 | } else { | |
bcab42da | 1300 | $dateformat = get_string('strftimedatetimeshort'); |
acd21a2d | 1301 | } |
b9ee0638 | 1302 | } |
acd21a2d | 1303 | $time = userdate($message->timecreated, $dateformat); |
6ee2611c | 1304 | |
4048f5b3 | 1305 | $messagetext = message_format_message_text($message, false); |
bcab42da | 1306 | |
1307 | if ($keywords) { | |
1308 | $messagetext = highlight($keywords, $messagetext); | |
1309 | } | |
1310 | ||
4048f5b3 PS |
1311 | $messagetext .= message_format_contexturl($message); |
1312 | ||
1555e10c PS |
1313 | $messagetext = clean_text($messagetext, FORMAT_HTML); |
1314 | ||
a2592fec AD |
1315 | return <<<TEMPLATE |
1316 | <div class='message $class'> | |
f5482be6 | 1317 | <a name="m{$message->id}"></a> |
a2592fec AD |
1318 | <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span> |
1319 | </div> | |
1320 | TEMPLATE; | |
bcab42da | 1321 | } |
1322 | ||
1323 | /** | |
1324 | * Format a the context url and context url name of a message for display | |
ebe0c008 | 1325 | * |
bcab42da | 1326 | * @param object $message the message object |
1327 | * @return string the formatted string | |
1328 | */ | |
1329 | function message_format_contexturl($message) { | |
1330 | $s = null; | |
1331 | ||
14a0e7dd AD |
1332 | if (!empty($message->contexturl)) { |
1333 | $displaytext = null; | |
1334 | if (!empty($message->contexturlname)) { | |
1335 | $displaytext= $message->contexturlname; | |
1336 | } else { | |
1337 | $displaytext= $message->contexturl; | |
1338 | } | |
bcab42da | 1339 | $s .= html_writer::start_tag('div',array('class' => 'messagecontext')); |
1340 | $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl)); | |
1341 | $s .= html_writer::end_tag('div'); | |
38c6a928 | 1342 | } |
14a0e7dd | 1343 | |
bcab42da | 1344 | return $s; |
b9ee0638 | 1345 | } |
e8e2d7f1 | 1346 | |
fd1cb1e8 | 1347 | /** |
bcab42da | 1348 | * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences |
ebe0c008 | 1349 | * |
bcab42da | 1350 | * @param object $userfrom the message sender |
1351 | * @param object $userto the message recipient | |
1352 | * @param string $message the message | |
1353 | * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML | |
3a00a167 | 1354 | * @return int|false the ID of the new message or false |
405f01ee | 1355 | */ |
bcab42da | 1356 | function message_post_message($userfrom, $userto, $message, $format) { |
27a39763 | 1357 | global $SITE, $CFG, $USER; |
4ffa1463 | 1358 | |
8e803c3f | 1359 | $eventdata = new stdClass(); |
1560760f | 1360 | $eventdata->component = 'moodle'; |
1c50df9f | 1361 | $eventdata->name = 'instantmessage'; |
3b120e46 | 1362 | $eventdata->userfrom = $userfrom; |
1363 | $eventdata->userto = $userto; | |
4ffa1463 AD |
1364 | |
1365 | //using string manager directly so that strings in the message will be in the message recipients language rather than the senders | |
1366 | $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang); | |
1367 | ||
bcab42da | 1368 | if ($format == FORMAT_HTML) { |
156205fc | 1369 | $eventdata->fullmessagehtml = $message; |
22e23da6 AD |
1370 | //some message processors may revert to sending plain text even if html is supplied |
1371 | //so we keep both plain and html versions if we're intending to send html | |
1372 | $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml); | |
156205fc AD |
1373 | } else { |
1374 | $eventdata->fullmessage = $message; | |
1375 | $eventdata->fullmessagehtml = ''; | |
1376 | } | |
31da70cc | 1377 | |
c8621a02 | 1378 | $eventdata->fullmessageformat = $format; |
7e98f60b | 1379 | $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output. |
27a39763 AD |
1380 | |
1381 | $s = new stdClass(); | |
bf0f06b1 | 1382 | $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID))); |
536a56e7 | 1383 | $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id; |
27a39763 | 1384 | |
4ffa1463 | 1385 | $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang); |
6ee2611c AD |
1386 | if (!empty($eventdata->fullmessage)) { |
1387 | $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline; | |
1388 | } | |
6ee2611c AD |
1389 | if (!empty($eventdata->fullmessagehtml)) { |
1390 | $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline; | |
1391 | } | |
31da70cc | 1392 | |
a1b53dcf | 1393 | $eventdata->timecreated = time(); |
5e12b369 | 1394 | $eventdata->notification = 0; |
7c7d3afa | 1395 | return message_send($eventdata); |
405f01ee | 1396 | } |
e8e2d7f1 | 1397 | |
bcab42da | 1398 | /** |
1399 | * Constructs the add/remove contact link to display next to other users | |
ebe0c008 | 1400 | * |
bcab42da | 1401 | * @param bool $incontactlist is the user a contact |
1402 | * @param bool $isblocked is the user blocked | |
6fbd60ef | 1403 | * @param stdClass $contact contact object |
bcab42da | 1404 | * @param string $script the URL to send the user to when the link is clicked. If null, the current page. |
1405 | * @param bool $text include text next to the icons? | |
1406 | * @param bool $icon include a graphical icon? | |
1407 | * @return string | |
1408 | */ | |
c8621a02 AD |
1409 | function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) { |
1410 | $strcontact = ''; | |
1411 | ||
1412 | if($incontactlist){ | |
1413 | $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon); | |
1414 | } else if ($isblocked) { | |
1415 | $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon); | |
1416 | } else{ | |
1417 | $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon); | |
1418 | } | |
1419 | ||
1420 | return $strcontact; | |
1421 | } | |
1422 | ||
bcab42da | 1423 | /** |
1424 | * Constructs the block contact link to display next to other users | |
ebe0c008 | 1425 | * |
6fbd60ef AD |
1426 | * @param bool $incontactlist is the user a contact? |
1427 | * @param bool $isblocked is the user blocked? | |
1428 | * @param stdClass $contact contact object | |
bcab42da | 1429 | * @param string $script the URL to send the user to when the link is clicked. If null, the current page. |
1430 | * @param bool $text include text next to the icons? | |
1431 | * @param bool $icon include a graphical icon? | |
1432 | * @return string | |
1433 | */ | |
c8621a02 AD |
1434 | function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) { |
1435 | $strblock = ''; | |
1436 | ||
1437 | //commented out to allow the user to block a contact without having to remove them first | |
1438 | /*if ($incontactlist) { | |
1439 | //$strblock = ''; | |
1440 | } else*/ | |
1441 | if ($isblocked) { | |
35fe9b8a | 1442 | $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon); |
c8621a02 | 1443 | } else{ |
35fe9b8a | 1444 | $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon); |
c8621a02 AD |
1445 | } |
1446 | ||
1447 | return $strblock; | |
1448 | } | |
1449 | ||
ebe0c008 RK |
1450 | /** |
1451 | * Moves messages from a particular user from the message table (unread messages) to message_read | |
1452 | * This is typically only used when a user is deleted | |
1453 | * | |
1454 | * @param object $userid User id | |
1455 | * @return boolean success | |
1456 | */ | |
6bdf4c99 | 1457 | function message_move_userfrom_unread2read($userid) { |
6bdf4c99 | 1458 | global $DB; |
1459 | ||
71666cf3 | 1460 | // move all unread messages from message table to message_read |
6bdf4c99 | 1461 | if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) { |
1462 | foreach ($messages as $message) { | |
ee7cd81a | 1463 | message_mark_message_read($message, 0); //set timeread to 0 as the message was never read |
6bdf4c99 | 1464 | } |
1465 | } | |
1466 | return true; | |
1467 | } | |
1468 | ||
ee7cd81a | 1469 | /** |
ebe0c008 RK |
1470 | * marks ALL messages being sent from $fromuserid to $touserid as read |
1471 | * | |
1472 | * @param int $touserid the id of the message recipient | |
1473 | * @param int $fromuserid the id of the message sender | |
1474 | * @return void | |
1475 | */ | |
727c69ca | 1476 | function message_mark_messages_read($touserid, $fromuserid) { |
3274d5ca RW |
1477 | return message_mark_all_read_for_user($touserid, $fromuserid); |
1478 | } | |
1479 | ||
1480 | /** | |
1481 | * marks ALL messages being sent from $fromuserid to $touserid as read. Can | |
1482 | * be filtered by type. | |
1483 | * | |
1484 | * @param int $touserid the id of the message recipient | |
1485 | * @param int $fromuserid the id of the message sender | |
1486 | * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all. | |
1487 | * @return void | |
1488 | */ | |
1489 | function message_mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') { | |
c8621a02 AD |
1490 | global $DB; |
1491 | ||
3274d5ca RW |
1492 | $params = array(); |
1493 | $where = ''; | |
1494 | ||
1495 | if (!empty($touserid)) { | |
1496 | $params['useridto'] = $touserid; | |
1497 | } | |
1498 | ||
1499 | if (!empty($fromuserid)) { | |
1500 | $params['useridfrom'] = $fromuserid; | |
1501 | } | |
1502 | ||
1503 | if (!empty($type)) { | |
1504 | if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) { | |
1505 | $params['notification'] = 1; | |
1506 | } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) { | |
1507 | $params['notification'] = 0; | |
1508 | } | |
1509 | } | |
1510 | ||
1511 | $sql = sprintf('SELECT m.* FROM {message} m WHERE m.%s = ?', implode('= ? AND m.', array_keys($params))); | |
1512 | $messages = $DB->get_recordset_sql($sql, array_values($params)); | |
1560760f | 1513 | |
c8621a02 | 1514 | foreach ($messages as $message) { |
ee7cd81a AD |
1515 | message_mark_message_read($message, time()); |
1516 | } | |
19c5532b AD |
1517 | |
1518 | $messages->close(); | |
ee7cd81a AD |
1519 | } |
1520 | ||
1521 | /** | |
ebe0c008 RK |
1522 | * Mark a single message as read |
1523 | * | |
6fbd60ef | 1524 | * @param stdClass $message An object with an object property ie $message->id which is an id in the message table |
ebe0c008 RK |
1525 | * @param int $timeread the timestamp for when the message should be marked read. Usually time(). |
1526 | * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message? | |
1527 | * @return int the ID of the message in the message_read table | |
1528 | */ | |
ee7cd81a AD |
1529 | function message_mark_message_read($message, $timeread, $messageworkingempty=false) { |
1530 | global $DB; | |
31da70cc | 1531 | |
ee7cd81a | 1532 | $message->timeread = $timeread; |
c8621a02 | 1533 | |
ee7cd81a AD |
1534 | $messageid = $message->id; |
1535 | unset($message->id);//unset because it will get a new id on insert into message_read | |
1560760f | 1536 | |
ee7cd81a AD |
1537 | //If any processors have pending actions abort them |
1538 | if (!$messageworkingempty) { | |
1539 | $DB->delete_records('message_working', array('unreadmessageid' => $messageid)); | |
c8621a02 | 1540 | } |
3a00a167 | 1541 | $messagereadid = $DB->insert_record('message_read', $message); |
5b091909 | 1542 | |
ee7cd81a | 1543 | $DB->delete_records('message', array('id' => $messageid)); |
5b091909 | 1544 | |
cbfd685a MN |
1545 | // Get the context for the user who received the message. |
1546 | $context = context_user::instance($message->useridto, IGNORE_MISSING); | |
1547 | // If the user no longer exists the context value will be false, in this case use the system context. | |
1548 | if ($context === false) { | |
1549 | $context = context_system::instance(); | |
1550 | } | |
1551 | ||
5b091909 | 1552 | // Trigger event for reading a message. |
f3d98189 | 1553 | $event = \core\event\message_viewed::create(array( |
5b091909 MN |
1554 | 'objectid' => $messagereadid, |
1555 | 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action. | |
cbfd685a | 1556 | 'context' => $context, |
5b091909 MN |
1557 | 'relateduserid' => $message->useridfrom, |
1558 | 'other' => array( | |
1559 | 'messageid' => $messageid | |
1560 | ) | |
1561 | )); | |
1562 | $event->trigger(); | |
1563 | ||
3a00a167 | 1564 | return $messagereadid; |
65fbace7 | 1565 | } |
bcab42da | 1566 | |
75c34c23 | 1567 | /** |
814e3735 RK |
1568 | * Get all message processors, validate corresponding plugin existance and |
1569 | * system configuration | |
ebe0c008 | 1570 | * |
814e3735 | 1571 | * @param bool $ready only return ready-to-use processors |
ed23ad31 | 1572 | * @param bool $reset Reset list of message processors (used in unit tests) |
e61a9638 | 1573 | * @param bool $resetonly Just reset, then exit |
814e3735 | 1574 | * @return mixed $processors array of objects containing information on message processors |
75c34c23 | 1575 | */ |
e61a9638 | 1576 | function get_message_processors($ready = false, $reset = false, $resetonly = false) { |
75c34c23 RK |
1577 | global $DB, $CFG; |
1578 | ||
1d72e9d4 | 1579 | static $processors; |
ed23ad31 YB |
1580 | if ($reset) { |
1581 | $processors = array(); | |
e61a9638 MN |
1582 | |
1583 | if ($resetonly) { | |
1584 | return $processors; | |
1585 | } | |
ed23ad31 | 1586 | } |
1d72e9d4 RK |
1587 | |
1588 | if (empty($processors)) { | |
814e3735 RK |
1589 | // Get all processors, ensure the name column is the first so it will be the array key |
1590 | $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled'); | |
1d72e9d4 RK |
1591 | foreach ($processors as &$processor){ |
1592 | $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php'; | |
1593 | if (is_readable($processorfile)) { | |
1594 | include_once($processorfile); | |
1595 | $processclass = 'message_output_' . $processor->name; | |
1596 | if (class_exists($processclass)) { | |
1597 | $pclass = new $processclass(); | |
814e3735 | 1598 | $processor->object = $pclass; |
1d72e9d4 RK |
1599 | $processor->configured = 0; |
1600 | if ($pclass->is_system_configured()) { | |
1601 | $processor->configured = 1; | |
1602 | } | |
1603 | $processor->hassettings = 0; | |
1604 | if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) { | |
1605 | $processor->hassettings = 1; | |
1606 | } | |
1607 | $processor->available = 1; | |
1608 | } else { | |
1609 | print_error('errorcallingprocessor', 'message'); | |
75c34c23 | 1610 | } |
75c34c23 | 1611 | } else { |
1d72e9d4 | 1612 | $processor->available = 0; |
75c34c23 | 1613 | } |
75c34c23 RK |
1614 | } |
1615 | } | |
814e3735 | 1616 | if ($ready) { |
72e6af03 RK |
1617 | // Filter out enabled and system_configured processors |
1618 | $readyprocessors = $processors; | |
1619 | foreach ($readyprocessors as $readyprocessor) { | |
1620 | if (!($readyprocessor->enabled && $readyprocessor->configured)) { | |
1621 | unset($readyprocessors[$readyprocessor->name]); | |
1622 | } | |
1623 | } | |
1624 | return $readyprocessors; | |
1d72e9d4 RK |
1625 | } |
1626 | ||
75c34c23 RK |
1627 | return $processors; |
1628 | } | |
814e3735 | 1629 | |
7fcd3c30 RK |
1630 | /** |
1631 | * Get all message providers, validate their plugin existance and | |
1632 | * system configuration | |
1633 | * | |
1634 | * @return mixed $processors array of objects containing information on message processors | |
1635 | */ | |
1636 | function get_message_providers() { | |
1637 | global $CFG, $DB; | |
e87214bd PS |
1638 | |
1639 | $pluginman = core_plugin_manager::instance(); | |
7fcd3c30 RK |
1640 | |
1641 | $providers = $DB->get_records('message_providers', null, 'name'); | |
1642 | ||
1643 | // Remove all the providers whose plugins are disabled or don't exist | |
1644 | foreach ($providers as $providerid => $provider) { | |
1645 | $plugin = $pluginman->get_plugin_info($provider->component); | |
1646 | if ($plugin) { | |
e87214bd | 1647 | if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) { |
7fcd3c30 RK |
1648 | unset($providers[$providerid]); // Plugins does not exist |
1649 | continue; | |
1650 | } | |
1651 | if ($plugin->is_enabled() === false) { | |
1652 | unset($providers[$providerid]); // Plugin disabled | |
1653 | continue; | |
1654 | } | |
1655 | } | |
1656 | } | |
1657 | return $providers; | |
1658 | } | |
1659 | ||
7529f9e9 TH |
1660 | /** |
1661 | * Get an instance of the message_output class for one of the output plugins. | |
1662 | * @param string $type the message output type. E.g. 'email' or 'jabber'. | |
1663 | * @return message_output message_output the requested class. | |
1664 | */ | |
1665 | function get_message_processor($type) { | |
1666 | global $CFG; | |
1667 | ||
1668 | // Note, we cannot use the get_message_processors function here, becaues this | |
1669 | // code is called during install after installing each messaging plugin, and | |
1670 | // get_message_processors caches the list of installed plugins. | |
1671 | ||
1672 | $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php"; | |
1673 | if (!is_readable($processorfile)) { | |
1674 | throw new coding_exception('Unknown message processor type ' . $type); | |
1675 | } | |
1676 | ||
1677 | include_once($processorfile); | |
1678 | ||
1679 | $processclass = 'message_output_' . $type; | |
1680 | if (!class_exists($processclass)) { | |
1681 | throw new coding_exception('Message processor ' . $type . | |
1682 | ' does not define the right class'); | |
1683 | } | |
1684 | ||
1685 | return new $processclass(); | |
1686 | } | |
1687 | ||
814e3735 RK |
1688 | /** |
1689 | * Get messaging outputs default (site) preferences | |
ebe0c008 | 1690 | * |
814e3735 RK |
1691 | * @return object $processors object containing information on message processors |
1692 | */ | |
1693 | function get_message_output_default_preferences() { | |
820a8188 | 1694 | return get_config('message'); |
814e3735 | 1695 | } |
7a04c476 RK |
1696 | |
1697 | /** | |
1698 | * Translate message default settings from binary value to the array of string | |
1699 | * representing the settings to be stored. Also validate the provided value and | |
1700 | * use default if it is malformed. | |
ebe0c008 | 1701 | * |
7a04c476 RK |
1702 | * @param int $plugindefault Default setting suggested by plugin |
1703 | * @param string $processorname The name of processor | |
1704 | * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff. | |
1705 | */ | |
1706 | function translate_message_default_setting($plugindefault, $processorname) { | |
1707 | // Preset translation arrays | |
1708 | $permittedvalues = array( | |
1709 | 0x04 => 'disallowed', | |
1710 | 0x08 => 'permitted', | |
1711 | 0x0c => 'forced', | |
1712 | ); | |
1713 | ||
1714 | $loggedinstatusvalues = array( | |
1715 | 0x00 => null, // use null if loggedin/loggedoff is not defined | |
1716 | 0x01 => 'loggedin', | |
1717 | 0x02 => 'loggedoff', | |
1718 | ); | |
1719 | ||
1720 | // define the default setting | |
7529f9e9 TH |
1721 | $processor = get_message_processor($processorname); |
1722 | $default = $processor->get_default_messaging_settings(); | |
7a04c476 RK |
1723 | |
1724 | // Validate the value. It should not exceed the maximum size | |
1725 | if (!is_int($plugindefault) || ($plugindefault > 0x0f)) { | |
681570b4 | 1726 | debugging(get_string('errortranslatingdefault', 'message')); |
7a04c476 RK |
1727 | $plugindefault = $default; |
1728 | } | |
1729 | // Use plugin default setting of 'permitted' is 0 | |
1730 | if (!($plugindefault & MESSAGE_PERMITTED_MASK)) { | |
1731 | $plugindefault = $default; | |
1732 | } | |
1733 | ||
1734 | $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK]; | |
83807514 | 1735 | $loggedin = $loggedoff = null; |
7a04c476 RK |
1736 | |
1737 | if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) { | |
83807514 RK |
1738 | $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN]; |
1739 | $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF]; | |
7a04c476 RK |
1740 | } |
1741 | ||
1742 | return array($permitted, $loggedin, $loggedoff); | |
1743 | } | |
46d3b9be | 1744 | |
35d72562 AD |
1745 | /** |
1746 | * Return a list of page types | |
1747 | * @param string $pagetype current page type | |
1748 | * @param stdClass $parentcontext Block's parent context | |
1749 | * @param stdClass $currentcontext Current context of block | |
1750 | */ | |
b38e2e28 | 1751 | function message_page_type_list($pagetype, $parentcontext, $currentcontext) { |
35d72562 AD |
1752 | return array('messages-*'=>get_string('page-message-x', 'message')); |
1753 | } | |
babc03f4 | 1754 | |
193edf7f | 1755 | /** |
127ef540 | 1756 | * Get messages sent or/and received by the specified users. |
ea21d637 | 1757 | * Please note that this function return deleted messages too. |
193edf7f JL |
1758 | * |
1759 | * @param int $useridto the user id who received the message | |
127ef540 | 1760 | * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user |
193edf7f | 1761 | * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both |
127ef540 | 1762 | * @param bool $read true for retrieving read messages, false for unread |
193edf7f JL |
1763 | * @param string $sort the column name to order by including optionally direction |
1764 | * @param int $limitfrom limit from | |
1765 | * @param int $limitnum limit num | |
1766 | * @return external_description | |
1767 | * @since 2.8 | |
1768 | */ | |
1769 | function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true, | |
1770 | $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) { | |
1771 | global $DB; | |
1772 | ||
1773 | $messagetable = $read ? '{message_read}' : '{message}'; | |
193edf7f JL |
1774 | $params = array('deleted' => 0); |
1775 | ||
1776 | // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user. | |
1777 | if (empty($useridto)) { | |
1778 | $userfields = get_all_user_name_fields(true, 'u', '', 'userto'); | |
1779 | $joinsql = "JOIN {user} u ON u.id = mr.useridto"; | |
1780 | $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted"; | |
1781 | $params['useridfrom'] = $useridfrom; | |
1782 | } else { | |
1783 | $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom'); | |
1784 | // Left join because useridfrom may be -10 or -20 (no-reply and support users). | |
1785 | $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom"; | |
1786 | $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)"; | |
1787 | $params['useridto'] = $useridto; | |
1788 | if (!empty($useridfrom)) { | |
1789 | $usersql .= " AND mr.useridfrom = :useridfrom"; | |
1790 | $params['useridfrom'] = $useridfrom; | |
1791 | } | |
1792 | } | |
1793 | ||
1794 | // Now, if retrieve notifications, conversations or both. | |
1795 | $typesql = ""; | |
1796 | if ($notifications !== -1) { | |
1797 | $typesql = "AND mr.notification = :notification"; | |
1798 | $params['notification'] = ($notifications) ? 1 : 0; | |
1799 | } | |
1800 | ||
1801 | $sql = "SELECT mr.*, $userfields | |
1802 | FROM $messagetable mr | |
127ef540 SH |
1803 | $joinsql |
1804 | WHERE $usersql | |
1805 | $typesql | |
193edf7f JL |
1806 | ORDER BY $sort"; |
1807 | ||
1808 | $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum); | |
1809 | return $messages; | |
1810 | } | |
cf4a17cb | 1811 | |
3274d5ca | 1812 | /** |
ada7695d | 1813 | * Get popup notifications for the specified users. |
3274d5ca RW |
1814 | * |
1815 | * @param int $useridto the user id who received the notification | |
3274d5ca | 1816 | * @param bool $status MESSAGE_READ for retrieving read notifications, MESSAGE_UNREAD for unread, empty for both |
3274d5ca RW |
1817 | * @param bool $embeduserto embed the to user details in the notification response |
1818 | * @param bool $embeduserfrom embed the from user details in the notification response | |
ada7695d | 1819 | * @param string $sort the column name to order by including optionally direction |
3274d5ca RW |
1820 | * @param int $limit limit the number of result returned |
1821 | * @param int $offset offset the result set by this amount | |
1822 | * @return array array of notification records | |
ada7695d | 1823 | * @since 3.2 |
3274d5ca | 1824 | */ |
ada7695d | 1825 | function message_get_popup_notifications($useridto = 0, $status = '', |
3274d5ca RW |
1826 | $embeduserto = false, $embeduserfrom = false, $sort = 'DESC', $limit = 0, $offset = 0) { |
1827 | global $DB; | |
1828 | ||
1829 | if (!empty($status) && $status != MESSAGE_READ && $status != MESSAGE_UNREAD) { | |
1830 | throw new moodle_exception(sprintf('invalid parameter: status: must be "%s" or "%s"', | |
1831 | MESSAGE_READ, MESSAGE_UNREAD)); | |
1832 | } | |
1833 | ||
1834 | $sort = strtoupper($sort); | |
1835 | if ($sort != 'DESC' && $sort != 'ASC') { | |
1836 | throw new moodle_exception('invalid parameter: sort: must be "DESC" or "ASC"'); | |
1837 | } | |
1838 | ||
ada7695d RW |
1839 | if (empty($useridto)) { |
1840 | $useridto = $USER->id; | |
1841 | } | |
1842 | ||
3274d5ca RW |
1843 | $params = array(); |
1844 | ||
ada7695d RW |
1845 | $buildtablesql = function($table, $prefix, $additionalfields, $messagestatus) |
1846 | use ($status, $useridto, $embeduserto, $embeduserfrom) { | |
1847 | ||
1848 | $joinsql = ''; | |
3274d5ca RW |
1849 | $fields = "concat('$prefix', $prefix.id) as uniqueid, $prefix.id, $prefix.useridfrom, $prefix.useridto, |
1850 | $prefix.subject, $prefix.fullmessage, $prefix.fullmessageformat, | |
1851 | $prefix.fullmessagehtml, $prefix.smallmessage, $prefix.notification, $prefix.contexturl, | |
1852 | $prefix.contexturlname, $prefix.timecreated, $prefix.timeuserfromdeleted, $prefix.timeusertodeleted, | |
1853 | $prefix.component, $prefix.eventtype, $additionalfields"; | |
ada7695d RW |
1854 | $where = " AND $prefix.useridto = :{$prefix}useridto"; |
1855 | $params = ["{$prefix}useridto" => $useridto]; | |
3274d5ca RW |
1856 | |
1857 | if ($embeduserto) { | |
1858 | $embedprefix = "{$prefix}ut"; | |
1859 | $fields .= ", " . get_all_user_name_fields(true, $embedprefix, '', 'userto'); | |
1860 | $joinsql .= " LEFT JOIN {user} $embedprefix ON $embedprefix.id = $prefix.useridto"; | |
1861 | } | |
1862 | ||
1863 | if ($embeduserfrom) { | |
1864 | $embedprefix = "{$prefix}uf"; | |
1865 | $fields .= ", " . get_all_user_name_fields(true, $embedprefix, '', 'userfrom'); | |
1866 | $joinsql .= " LEFT JOIN {user} $embedprefix ON $embedprefix.id = $prefix.useridfrom"; | |
1867 | } | |
1868 | ||
ada7695d RW |
1869 | if ($messagestatus == MESSAGE_READ) { |
1870 | $isread = '1'; | |
1871 | } else { | |
1872 | $isread = '0'; | |
1873 | } | |
1874 | ||
1875 | return array( | |
1876 | sprintf( | |
1877 | "SELECT %s | |
1878 | FROM %s %s %s | |
1879 | WHERE %s.notification = 1 | |
1880 | AND %s.id IN (SELECT messageid FROM {message_popup} WHERE isread = %s) | |
1881 | %s", | |
1882 | $fields, $table, $prefix, $joinsql, $prefix, $prefix, $isread, $where | |
1883 | ), | |
1884 | $params | |
1885 | ); | |
3274d5ca RW |
1886 | }; |
1887 | ||
1888 | $sql = ''; | |
1889 | switch ($status) { | |
1890 | case MESSAGE_READ: | |
ada7695d | 1891 | list($sql, $readparams) = $buildtablesql('{message_read}', 'r', 'r.timeread', MESSAGE_READ); |
3274d5ca RW |
1892 | $params = array_merge($params, $readparams); |
1893 | break; | |
1894 | case MESSAGE_UNREAD: | |
ada7695d | 1895 | list($sql, $unreadparams) = $buildtablesql('{message}', 'u', '0 as timeread', MESSAGE_UNREAD); |
3274d5ca RW |
1896 | $params = array_merge($params, $unreadparams); |
1897 | break; | |
1898 | default: | |
ada7695d RW |
1899 | list($readsql, $readparams) = $buildtablesql('{message_read}', 'r', 'r.timeread', MESSAGE_READ); |
1900 | list($unreadsql, $unreadparams) = $buildtablesql('{message}', 'u', '0 as timeread', MESSAGE_UNREAD); | |
3274d5ca RW |
1901 | $sql = sprintf("SELECT * FROM (%s UNION %s) f", $readsql, $unreadsql); |
1902 | $params = array_merge($params, $readparams, $unreadparams); | |
1903 | } | |
1904 | ||
1905 | $sql .= " ORDER BY timecreated $sort, timeread $sort, id $sort"; | |
1906 | ||
1907 | return array_values($DB->get_records_sql($sql, $params, $offset, $limit)); | |
1908 | } | |
1909 | ||
1910 | /** | |
1911 | * Count the unread notifications for a user. | |
1912 | * | |
1913 | * @param int $useridto the user id who received the notification | |
3274d5ca | 1914 | * @return int count of the unread notifications |
ada7695d | 1915 | * @since 3.2 |
3274d5ca | 1916 | */ |
ada7695d | 1917 | function message_count_unread_popup_notifications($useridto = 0) { |
3274d5ca RW |
1918 | global $USER, $DB; |
1919 | ||
1920 | if (empty($useridto)) { | |
1921 | $useridto = $USER->id; | |
1922 | } | |
1923 | ||
ada7695d RW |
1924 | return $DB->count_records_sql( |
1925 | "SELECT count(id) | |
1926 | FROM {message} | |
1927 | WHERE id IN (SELECT messageid FROM {message_popup} WHERE isread = 0) | |
1928 | AND useridto = ?", | |
1929 | [$useridto] | |
1930 | ); | |
3274d5ca RW |
1931 | } |
1932 | ||
cf4a17cb FM |
1933 | /** |
1934 | * Requires the JS libraries to send a message using a dialog. | |
1935 | * | |
1936 | * @return void | |
1937 | */ | |
1938 | function message_messenger_requirejs() { | |
1939 | global $PAGE; | |
1940 | ||
1941 | static $done = false; | |
1942 | if ($done) { | |
1943 | return; | |
1944 | } | |
1945 | ||
1946 | $PAGE->requires->yui_module( | |
1947 | array('moodle-core_message-messenger'), | |
1948 | 'Y.M.core_message.messenger.init', | |
1949 | array(array()) | |
1950 | ); | |
1951 | $PAGE->requires->strings_for_js(array( | |
1952 | 'errorwhilesendingmessage', | |
1953 | 'messagesent', | |
1954 | 'messagetosend', | |
1955 | 'sendingmessage', | |
1956 | 'sendmessage', | |
1957 | 'viewconversation', | |
1958 | ), 'core_message'); | |
cd0c9ac8 RW |
1959 | $PAGE->requires->strings_for_js(array( |
1960 | 'userisblockingyou', | |
1961 | 'userisblockingyounoncontact' | |
1962 | ), 'message'); | |
cf4a17cb FM |
1963 | $PAGE->requires->string_for_js('error', 'core'); |
1964 | ||
1965 | $done = true; | |
1966 | } | |
1967 | ||
12d8c7b2 RW |
1968 | /** |
1969 | * Requires the JS libraries for the toggle contact button. | |
1970 | * | |
1971 | * @return void | |
1972 | */ | |
1973 | function message_togglecontact_requirejs() { | |
1974 | global $PAGE; | |
1975 | ||
1976 | static $done = false; | |
1977 | if ($done) { | |
1978 | return; | |
1979 | } | |
1980 | ||
9e8a29c9 | 1981 | $PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button')); |
12d8c7b2 RW |
1982 | $done = true; |
1983 | } | |
1984 | ||
cf4a17cb FM |
1985 | /** |
1986 | * Returns the attributes to place on a link to open the 'Send message' dialog. | |
1987 | * | |
1988 | * @param object $user User object. | |
1989 | * @return void | |
1990 | */ | |
1991 | function message_messenger_sendmessage_link_params($user) { | |
cd0c9ac8 | 1992 | $params = array( |
cf4a17cb FM |
1993 | 'data-trigger' => 'core_message-messenger::sendmessage', |
1994 | 'data-fullname' => fullname($user), | |
1995 | 'data-userid' => $user->id, | |
1996 | 'role' => 'button' | |
1997 | ); | |
cd0c9ac8 RW |
1998 | |
1999 | if (message_is_user_non_contact_blocked($user)) { | |
2000 | $params['data-blocked-string'] = 'userisblockingyounoncontact'; | |
2001 | } else if (message_is_user_blocked($user)) { | |
2002 | $params['data-blocked-string'] = 'userisblockingyou'; | |
2003 | } | |
2004 | ||
2005 | return $params; | |
2006 | } | |
2007 | ||
12d8c7b2 RW |
2008 | /** |
2009 | * Returns the attributes to place on a contact button. | |
2010 | * | |
2011 | * @param object $user User object. | |
2012 | * @param bool $iscontact | |
2013 | * @return void | |
2014 | */ | |
2015 | function message_togglecontact_link_params($user, $iscontact = false) { | |
2016 | $params = array( | |
2017 | 'data-userid' => $user->id, | |
2018 | 'data-is-contact' => $iscontact, | |
2019 | 'id' => 'toggle-contact-button', | |
2020 | 'role' => 'button', | |
2021 | 'class' => 'ajax-contact-button', | |
2022 | ); | |
2023 | ||
2024 | return $params; | |
2025 | } | |
2026 | ||
cd0c9ac8 RW |
2027 | /** |
2028 | * Determines if a user is permitted to send another user a private message. | |
2029 | * If no sender is provided then it defaults to the logged in user. | |
2030 | * | |
2031 | * @param object $recipient User object. | |
2032 | * @param object $sender User object. | |
2033 | * @return bool true if user is permitted, false otherwise. | |
2034 | */ | |
2035 | function message_can_post_message($recipient, $sender = null) { | |
2036 | global $USER, $DB; | |
2037 | ||
2038 | if (is_null($sender)) { | |
2039 | // The message is from the logged in user, unless otherwise specified. | |
2040 | $sender = $USER; | |
2041 | } | |
2042 | ||
2043 | if (!has_capability('moodle/site:sendmessage', context_system::instance(), $sender)) { | |
2044 | return false; | |
2045 | } | |
2046 | ||
2047 | // The recipient blocks messages from non-contacts and the | |
2048 | // sender isn't a contact. | |
2049 | if (message_is_user_non_contact_blocked($recipient, $sender)) { | |
2050 | return false; | |
2051 | } | |
2052 | ||
2053 | // The recipient has specifically blocked this sender. | |
2054 | if (message_is_user_blocked($recipient, $sender)) { | |
2055 | return false; | |
2056 | } | |
2057 | ||
2058 | return true; | |
2059 | } | |
2060 | ||
2061 | /** | |
2062 | * Checks if the recipient is allowing messages from users that aren't a | |
2063 | * contact. If not then it checks to make sure the sender is in the | |
2064 | * recipient's contacts. | |
2065 | * | |
2066 | * @param object $recipient User object. | |
2067 | * @param object $sender User object. | |
2068 | * @return bool true if $sender is blocked, false otherwise. | |
2069 | */ | |
2070 | function message_is_user_non_contact_blocked($recipient, $sender = null) { | |
2071 | global $USER, $DB; | |
2072 | ||
2073 | if (is_null($sender)) { | |
2074 | // The message is from the logged in user, unless otherwise specified. | |
2075 | $sender = $USER; | |
2076 | } | |
2077 | ||
2078 | $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id); | |
2079 | if (!empty($blockednoncontacts)) { | |
2080 | // Confirm the sender is a contact of the recipient. | |
2081 | $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id)); | |
2082 | if ($exists) { | |
2083 | // All good, the recipient is a contact of the sender. | |
2084 | return false; | |
2085 | } else { | |
2086 | // Oh no, the recipient is not a contact. Looks like we can't send the message. | |
2087 | return true; | |
2088 | } | |
2089 | } | |
2090 | ||
2091 | return false; | |
2092 | } | |
2093 | ||
2094 | /** | |
2095 | * Checks if the recipient has specifically blocked the sending user. | |
2096 | * | |
2097 | * Note: This function will always return false if the sender has the | |
2098 | * readallmessages capability at the system context level. | |
2099 | * | |
2100 | * @param object $recipient User object. | |
2101 | * @param object $sender User object. | |
2102 | * @return bool true if $sender is blocked, false otherwise. | |
2103 | */ | |
2104 | function message_is_user_blocked($recipient, $sender = null) { | |
2105 | global $USER, $DB; | |
2106 | ||
2107 | if (is_null($sender)) { | |
2108 | // The message is from the logged in user, unless otherwise specified. | |
2109 | $sender = $USER; | |
2110 | } | |
2111 | ||
2112 | $systemcontext = context_system::instance(); | |
2113 | if (has_capability('moodle/site:readallmessages', $systemcontext, $sender)) { | |
2114 | return false; | |
2115 | } | |
2116 | ||
2117 | if ($contact = $DB->get_record('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id))) { | |
2118 | if ($contact->blocked) { | |
2119 | return true; | |
2120 | } | |
2121 | } | |
2122 | ||
2123 | return false; | |
cf4a17cb | 2124 | } |
643b015d RW |
2125 | |
2126 | function get_providers_preferences($providers, $userid) { | |
2127 | $preferences = new stdClass(); | |
2128 | ||
2129 | /// Get providers preferences | |
2130 | foreach ($providers as $provider) { | |
2131 | foreach (array('loggedin', 'loggedoff') as $state) { | |
2132 | $linepref = get_user_preferences('message_provider_'.$provider->component.'_'.$provider->name.'_'.$state, '', $userid); | |
2133 | if ($linepref == ''){ | |
2134 | continue; | |
2135 | } | |
2136 | $lineprefarray = explode(',', $linepref); | |
2137 | $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array(); | |
2138 | foreach ($lineprefarray as $pref) { | |
2139 | $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1; | |
2140 | } | |
2141 | } | |
2142 | } | |
2143 | ||
2144 | return $preferences; | |
2145 | } | |
2146 | ||
2147 | function message_output_fragment_processor_settings($args = []) { | |
2148 | global $PAGE; | |
2149 | ||
2150 | if (!isset($args['type'])) { | |
2151 | throw new moodle_exception('Must provide a processor type'); | |
2152 | } | |
2153 | ||
2154 | if (!isset($args['userid'])) { | |
2155 | throw new moodle_exception('Must provide a userid'); | |
2156 | } | |
2157 | ||
2158 | $type = $args['type']; | |
2159 | $userid = $args['userid']; | |
2160 | ||
2161 | $user = core_user::get_user($userid, '*', MUST_EXIST); | |
2162 | $processor = get_message_processor($type); | |
2163 | $providers = message_get_providers_for_user($userid); | |
2164 | $preferences = get_providers_preferences($providers, $userid); | |
2165 | ||
2166 | $processor->load_data($preferences, $userid); | |
2167 | ||
2168 | $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type); | |
2169 | $renderer = $PAGE->get_renderer('core', 'message'); | |
2170 | ||
2171 | return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer)); | |
2172 | } |