db95cea31a93ef195c5d4e631ce03318f7271c3e
[moodle.git] / message / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Library functions for messaging
19  *
20  * @package   core_message
21  * @copyright 2008 Luis Rodrigues
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 require_once($CFG->libdir.'/eventslib.php');
27 define ('MESSAGE_SHORTLENGTH', 300);
29 //$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
30 if (isset($PAGE)) {
31     //TODO: this is a mega crazy hack - it is not acceptable to call anything when including lib!!! (skodak)
32     $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
33 }
35 define ('MESSAGE_DISCUSSION_WIDTH',600);
36 define ('MESSAGE_DISCUSSION_HEIGHT',500);
38 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
40 define('MESSAGE_HISTORY_SHORT',0);
41 define('MESSAGE_HISTORY_ALL',1);
43 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
44 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
45 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
46 define('MESSAGE_VIEW_CONTACTS','contacts');
47 define('MESSAGE_VIEW_BLOCKED','blockedusers');
48 define('MESSAGE_VIEW_COURSE','course_');
49 define('MESSAGE_VIEW_SEARCH','search');
51 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
53 define('MESSAGE_CONTACTS_PER_PAGE',10);
54 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
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  */
66 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
67 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
69 define('MESSAGE_DISALLOWED', 0x04); // 0100
70 define('MESSAGE_PERMITTED', 0x08); // 1000
71 define('MESSAGE_FORCED', 0x0c); // 1100
73 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
75 /**
76  * Set default value for default outputs permitted setting
77  */
78 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
80 //TODO: defaults must be initialised via settings - this is a bad hack! (skodak)
81 if (!isset($CFG->message_contacts_refresh)) {  // Refresh the contacts list every 60 seconds
82     $CFG->message_contacts_refresh = 60;
83 }
84 if (!isset($CFG->message_chat_refresh)) {      // Look for new comments every 5 seconds
85     $CFG->message_chat_refresh = 5;
86 }
87 if (!isset($CFG->message_offline_time)) {
88     $CFG->message_offline_time = 300;
89 }
91 /**
92  * Print the selector that allows the user to view their contacts, course participants, their recent
93  * conversations etc
94  *
95  * @param int $countunreadtotal how many unread messages does the user have?
96  * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
97  * @param object $user1 the user whose messages are being viewed
98  * @param object $user2 the user $user1 is talking to
99  * @param array $blockedusers an array of users blocked by $user1
100  * @param array $onlinecontacts an array of $user1's online contacts
101  * @param array $offlinecontacts an array of $user1's offline contacts
102  * @param array $strangers an array of users who have messaged $user1 who aren't contacts
103  * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
104  * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
105  * @return void
106  */
107 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
108     global $PAGE;
110     echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
112     //if 0 unread messages and they've requested unread messages then show contacts
113     if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
114         $viewing = MESSAGE_VIEW_CONTACTS;
115     }
117     //if they have no blocked users and they've requested blocked users switch them over to contacts
118     if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
119         $viewing = MESSAGE_VIEW_CONTACTS;
120     }
122     $onlyactivecourses = true;
123     $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
124     $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
126     $strunreadmessages = null;
127     if ($countunreadtotal>0) { //if there are unread messages
128         $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
129     }
131     message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
133     if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
134         message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
135     } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
136         message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
137     } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
138         message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
139     } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
140         $courseidtoshow = intval(substr($viewing, 7));
142         if (!empty($courseidtoshow)
143             && array_key_exists($courseidtoshow, $coursecontexts)
144             && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
146             message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
147         } else {
148             //shouldn't get here. User trying to access a course they're not in perhaps.
149             add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
150         }
151     }
153     echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
154     echo html_writer::start_tag('fieldset');
155     $managebuttonclass = 'visible';
156     if ($viewing == MESSAGE_VIEW_SEARCH) {
157         $managebuttonclass = 'hiddenelement';
158     }
159     $strmanagecontacts = get_string('search','message');
160     echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
161     echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
162     echo html_writer::end_tag('fieldset');
163     echo html_writer::end_tag('form');
165     echo html_writer::end_tag('div');
168 /**
169  * Print course participants. Called by message_print_contact_selector()
170  *
171  * @param object $context the course context
172  * @param int $courseid the course ID
173  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
174  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
175  * @param string $titletodisplay Optionally specify a title to display above the participants
176  * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
177  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
178  * @return void
179  */
180 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
181     global $DB, $USER, $PAGE, $OUTPUT;
183     if (empty($titletodisplay)) {
184         $titletodisplay = get_string('participants');
185     }
187     $countparticipants = count_enrolled_users($context);
188     $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
190     $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
191     echo $OUTPUT->render($pagingbar);
193     echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
195     echo html_writer::start_tag('tr');
196     echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
197     echo html_writer::end_tag('tr');
199     //todo these need to come from somewhere if the course participants list is to show users with unread messages
200     $iscontact = true;
201     $isblocked = false;
202     foreach ($participants as $participant) {
203         if ($participant->id != $USER->id) {
204             $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
205             message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
206         }
207     }
209     echo html_writer::end_tag('table');
212 /**
213  * Retrieve users blocked by $user1
214  *
215  * @param object $user1 the user whose messages are being viewed
216  * @param object $user2 the user $user1 is talking to. If they are being blocked
217  *                      they will have a variable called 'isblocked' added to their user object
218  * @return array the users blocked by $user1
219  */
220 function message_get_blocked_users($user1=null, $user2=null) {
221     global $DB, $USER;
223     if (empty($user1)) {
224         $user1 = $USER;
225     }
227     if (!empty($user2)) {
228         $user2->isblocked = false;
229     }
231     $blockedusers = array();
233     $userfields = user_picture::fields('u', array('lastaccess'));
234     $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
235                           FROM {message_contacts} mc
236                           JOIN {user} u ON u.id = mc.contactid
237                           LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
238                          WHERE mc.userid = :user1id2 AND mc.blocked = 1
239                       GROUP BY $userfields
240                       ORDER BY u.firstname ASC";
241     $rs =  $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
243     foreach($rs as $rd) {
244         $blockedusers[] = $rd;
246         if (!empty($user2) && $user2->id == $rd->id) {
247             $user2->isblocked = true;
248         }
249     }
250     $rs->close();
252     return $blockedusers;
255 /**
256  * Print users blocked by $user1. Called by message_print_contact_selector()
257  *
258  * @param array $blockedusers the users blocked by $user1
259  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
260  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
261  * @param string $titletodisplay Optionally specify a title to display above the participants
262  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
263  * @return void
264  */
265 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
266     global $DB, $USER;
268     $countblocked = count($blockedusers);
270     echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
272     if (!empty($titletodisplay)) {
273         echo html_writer::start_tag('tr');
274         echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
275         echo html_writer::end_tag('tr');
276     }
278     if ($countblocked) {
279         echo html_writer::start_tag('tr');
280         echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
281         echo html_writer::end_tag('tr');
283         $isuserblocked = true;
284         $isusercontact = false;
285         foreach ($blockedusers as $blockeduser) {
286             message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
287         }
288     }
290     echo html_writer::end_tag('table');
293 /**
294  * Retrieve $user1's contacts (online, offline and strangers)
295  *
296  * @param object $user1 the user whose messages are being viewed
297  * @param object $user2 the user $user1 is talking to. If they are a contact
298  *                      they will have a variable called 'iscontact' added to their user object
299  * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
300  */
301 function message_get_contacts($user1=null, $user2=null) {
302     global $DB, $CFG, $USER;
304     if (empty($user1)) {
305         $user1 = $USER;
306     }
308     if (!empty($user2)) {
309         $user2->iscontact = false;
310     }
312     $timetoshowusers = 300; //Seconds default
313     if (isset($CFG->block_online_users_timetosee)) {
314         $timetoshowusers = $CFG->block_online_users_timetosee * 60;
315     }
317     // time which a user is counting as being active since
318     $timefrom = time()-$timetoshowusers;
320     // people in our contactlist who are online
321     $onlinecontacts  = array();
322     // people in our contactlist who are offline
323     $offlinecontacts = array();
324     // people who are not in our contactlist but have sent us a message
325     $strangers       = array();
327     $userfields = user_picture::fields('u', array('lastaccess'));
329     // get all in our contactlist who are not blocked in our contact list
330     // and count messages we have waiting from each of them
331     $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
332                      FROM {message_contacts} mc
333                      JOIN {user} u ON u.id = mc.contactid
334                      LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
335                     WHERE mc.userid = ? AND mc.blocked = 0
336                  GROUP BY $userfields
337                  ORDER BY u.firstname ASC";
339     $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
340     foreach ($rs as $rd) {
341         if ($rd->lastaccess >= $timefrom) {
342             // they have been active recently, so are counted online
343             $onlinecontacts[] = $rd;
345         } else {
346             $offlinecontacts[] = $rd;
347         }
349         if (!empty($user2) && $user2->id == $rd->id) {
350             $user2->iscontact = true;
351         }
352     }
353     $rs->close();
355     // get messages from anyone who isn't in our contact list and count the number
356     // of messages we have from each of them
357     $strangersql = "SELECT $userfields, count(m.id) as messagecount
358                       FROM {message} m
359                       JOIN {user} u  ON u.id = m.useridfrom
360                       LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
361                      WHERE mc.id IS NULL AND m.useridto = ?
362                   GROUP BY $userfields
363                   ORDER BY u.firstname ASC";
365     $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
366     foreach ($rs as $rd) {
367         $strangers[] = $rd;
368     }
369     $rs->close();
371     return array($onlinecontacts, $offlinecontacts, $strangers);
374 /**
375  * Print $user1's contacts. Called by message_print_contact_selector()
376  *
377  * @param array $onlinecontacts $user1's contacts which are online
378  * @param array $offlinecontacts $user1's contacts which are offline
379  * @param array $strangers users which are not contacts but who have messaged $user1
380  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
381  * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
382  *                         Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
383  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
384  * @param string $titletodisplay Optionally specify a title to display above the participants
385  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
386  * @return void
387  */
388 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
389     global $CFG, $PAGE, $OUTPUT;
391     $countonlinecontacts  = count($onlinecontacts);
392     $countofflinecontacts = count($offlinecontacts);
393     $countstrangers       = count($strangers);
394     $isuserblocked = null;
396     if ($countonlinecontacts + $countofflinecontacts == 0) {
397         echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
398     }
400     echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
402     if (!empty($titletodisplay)) {
403         message_print_heading($titletodisplay);
404     }
406     if($countonlinecontacts) {
407         /// print out list of online contacts
409         if (empty($titletodisplay)) {
410             message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
411         }
413         $isuserblocked = false;
414         $isusercontact = true;
415         foreach ($onlinecontacts as $contact) {
416             if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
417                 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
418             }
419         }
420     }
422     if ($countofflinecontacts) {
423         /// print out list of offline contacts
425         if (empty($titletodisplay)) {
426             message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
427         }
429         $isuserblocked = false;
430         $isusercontact = true;
431         foreach ($offlinecontacts as $contact) {
432             if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
433                 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
434             }
435         }
437     }
439     /// print out list of incoming contacts
440     if ($countstrangers) {
441         message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
443         $isuserblocked = false;
444         $isusercontact = false;
445         foreach ($strangers as $stranger) {
446             if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
447                 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
448             }
449         }
450     }
452     echo html_writer::end_tag('table');
454     if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) {  // Extra help
455         echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
456     }
459 /**
460  * Print a select box allowing the user to choose to view new messages, course participants etc.
461  *
462  * Called by message_print_contact_selector()
463  * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
464  * @param array $courses array of course objects. The courses the user is enrolled in.
465  * @param array $coursecontexts array of course contexts. Keyed on course id.
466  * @param int $countunreadtotal how many unread messages does the user have?
467  * @param int $countblocked how many users has the current user blocked?
468  * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
469  * @return void
470  */
471 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
472     $options = array();
474     if ($countunreadtotal>0) { //if there are unread messages
475         $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
476     }
478     $str = get_string('mycontacts', 'message');
479     $options[MESSAGE_VIEW_CONTACTS] = $str;
481     $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
482     $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
484     if (!empty($courses)) {
485         $courses_options = array();
487         foreach($courses as $course) {
488             if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
489                 //Not using short_text() as we want the end of the course name. Not the beginning.
490                 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
491                 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
492                     $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
493                 } else {
494                     $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
495                 }
496             }
497         }
499         if (!empty($courses_options)) {
500             $options[] = array(get_string('courses') => $courses_options);
501         }
502     }
504     if ($countblocked>0) {
505         $str = get_string('blockedusers','message', $countblocked);
506         $options[MESSAGE_VIEW_BLOCKED] = $str;
507     }
509     echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
510     echo html_writer::start_tag('fieldset');
511     echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
512     echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
513     echo html_writer::end_tag('fieldset');
514     echo html_writer::end_tag('form');
517 /**
518  * Load the course contexts for all of the users courses
519  *
520  * @param array $courses array of course objects. The courses the user is enrolled in.
521  * @return array of course contexts
522  */
523 function message_get_course_contexts($courses) {
524     $coursecontexts = array();
526     foreach($courses as $course) {
527         $coursecontexts[$course->id] = context_course::instance($course->id);
528     }
530     return $coursecontexts;
533 /**
534  * strip off action parameters like 'removecontact'
535  *
536  * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
537  * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
538  */
539 function message_remove_url_params($moodleurl) {
540     $newurl = new moodle_url($moodleurl);
541     $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
542     return $newurl->out();
545 /**
546  * Count the number of messages with a field having a specified value.
547  * if $field is empty then return count of the whole array
548  * if $field is non-existent then return 0
549  *
550  * @param array $messagearray array of message objects
551  * @param string $field the field to inspect on the message objects
552  * @param string $value the value to test the field against
553  */
554 function message_count_messages($messagearray, $field='', $value='') {
555     if (!is_array($messagearray)) return 0;
556     if ($field == '' or empty($messagearray)) return count($messagearray);
558     $count = 0;
559     foreach ($messagearray as $message) {
560         $count += ($message->$field == $value) ? 1 : 0;
561     }
562     return $count;
565 /**
566  * Returns the count of unread messages for user. Either from a specific user or from all users.
567  *
568  * @param object $user1 the first user. Defaults to $USER
569  * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
570  * @return int the count of $user1's unread messages
571  */
572 function message_count_unread_messages($user1=null, $user2=null) {
573     global $USER, $DB;
575     if (empty($user1)) {
576         $user1 = $USER;
577     }
579     if (!empty($user2)) {
580         return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
581             array($user1->id, $user2->id), "COUNT('id')");
582     } else {
583         return $DB->count_records_select('message', "useridto = ?",
584             array($user1->id), "COUNT('id')");
585     }
588 /**
589  * Count the number of users blocked by $user1
590  *
591  * @param object $user1 user object
592  * @return int the number of blocked users
593  */
594 function message_count_blocked_users($user1=null) {
595     global $USER, $DB;
597     if (empty($user1)) {
598         $user1 = $USER;
599     }
601     $sql = "SELECT count(mc.id)
602             FROM {message_contacts} mc
603             WHERE mc.userid = :userid AND mc.blocked = 1";
604     $params = array('userid' => $user1->id);
606     return $DB->count_records_sql($sql, $params);
609 /**
610  * Print the search form and search results if a search has been performed
611  *
612  * @param  boolean $advancedsearch show basic or advanced search form
613  * @param  object $user1 the current user
614  * @return boolean true if a search was performed
615  */
616 function message_print_search($advancedsearch = false, $user1=null) {
617     $frm = data_submitted();
619     $doingsearch = false;
620     if ($frm) {
621         if (confirm_sesskey()) {
622             $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
623         } else {
624             $frm = false;
625         }
626     }
628     if (!empty($frm->combinedsearch)) {
629         $combinedsearchstring = $frm->combinedsearch;
630     } else {
631         //$combinedsearchstring = get_string('searchcombined','message').'...';
632         $combinedsearchstring = '';
633     }
635     if ($doingsearch) {
636         if ($advancedsearch) {
638             $messagesearch = '';
639             if (!empty($frm->keywords)) {
640                 $messagesearch = $frm->keywords;
641             }
642             $personsearch = '';
643             if (!empty($frm->name)) {
644                 $personsearch = $frm->name;
645             }
646             include('search_advanced.html');
647         } else {
648             include('search.html');
649         }
651         $showicontext = false;
652         message_print_search_results($frm, $showicontext, $user1);
654         return true;
655     } else {
657         if ($advancedsearch) {
658             $personsearch = $messagesearch = '';
659             include('search_advanced.html');
660         } else {
661             include('search.html');
662         }
663         return false;
664     }
667 /**
668  * Get the users recent conversations meaning all the people they've recently
669  * sent or received a message from plus the most recent message sent to or received from each other user
670  *
671  * @param object $user the current user
672  * @param int $limitfrom can be used for paging
673  * @param int $limitto can be used for paging
674  * @return array
675  */
676 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
677     global $DB;
679     $userfields = user_picture::fields('u', array('lastaccess'));
680     //This query retrieves the last message received from and sent to each user
681     //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
682     //It then joins with some other tables to get some additional data we need
684     //message ID is used instead of timecreated as it should sort the same and will be much faster
686     //There is a separate query for read and unread queries as they are stored in different tables
687     //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
688     $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
689               FROM {message_read} mr
690               JOIN (
691                     SELECT messages.userid AS userid, MAX(messages.mid) AS mid
692                       FROM (
693                            SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
694                              FROM {message_read} mr1
695                             WHERE mr1.useridfrom = :userid1
696                                   AND mr1.notification = 0
697                          GROUP BY mr1.useridto
698                                   UNION
699                            SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
700                              FROM {message_read} mr2
701                             WHERE mr2.useridto = :userid2
702                                   AND mr2.notification = 0
703                          GROUP BY mr2.useridfrom
704                            ) messages
705                   GROUP BY messages.userid
706                    ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
707               JOIN {user} u ON u.id = messages2.userid
708          LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
709              WHERE u.deleted = '0'
710           ORDER BY mr.id DESC";
711     $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
712     $read =  $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
714     $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
715               FROM {message} m
716               JOIN (
717                     SELECT messages.userid AS userid, MAX(messages.mid) AS mid
718                       FROM (
719                            SELECT m1.useridto AS userid, MAX(m1.id) AS mid
720                              FROM {message} m1
721                             WHERE m1.useridfrom = :userid1
722                                   AND m1.notification = 0
723                          GROUP BY m1.useridto
724                                   UNION
725                            SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
726                              FROM {message} m2
727                             WHERE m2.useridto = :userid2
728                                   AND m2.notification = 0
729                          GROUP BY m2.useridfrom
730                            ) messages
731                   GROUP BY messages.userid
732                    ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
733               JOIN {user} u ON u.id = messages2.userid
734          LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
735              WHERE u.deleted = '0'
736              ORDER BY m.id DESC";
737     $unread =  $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
739     $conversations = array();
741     //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
742     //$conversation->id (the array key) is the other user's ID
743     $conversation_arrays = array($unread, $read);
744     foreach ($conversation_arrays as $conversation_array) {
745         foreach ($conversation_array as $conversation) {
746             if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
747                 $conversations[$conversation->id] = $conversation;
748             }
749         }
750     }
752     //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
753     //and there may be multiple conversations with the same timecreated value.
754     //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
755     usort($conversations, "conversationsort");
757     return $conversations;
760 /**
761  * Sort function used to order conversations
762  *
763  * @param object $a A conversation object
764  * @param object $b A conversation object
765  * @return integer
766  */
767 function conversationsort($a, $b)
769     if ($a->timecreated == $b->timecreated) {
770         return 0;
771     }
772     return ($a->timecreated > $b->timecreated) ? -1 : 1;
775 /**
776  * Get the users recent event notifications
777  *
778  * @param object $user the current user
779  * @param int $limitfrom can be used for paging
780  * @param int $limitto can be used for paging
781  * @return array
782  */
783 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
784     global $DB;
786     $userfields = user_picture::fields('u', array('lastaccess'));
787     $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
788               FROM {message_read} mr
789                    JOIN {user} u ON u.id=mr.useridfrom
790              WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
791              ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
792     $params = array('userid1' => $user->id, 'notification' => 1);
794     $notifications =  $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
795     return $notifications;
798 /**
799  * Print the user's recent conversations
800  *
801  * @param stdClass $user the current user
802  * @param bool $showicontext flag indicating whether or not to show text next to the action icons
803  */
804 function message_print_recent_conversations($user=null, $showicontext=false) {
805     global $USER;
807     echo html_writer::start_tag('p', array('class' => 'heading'));
808     echo get_string('mostrecentconversations', 'message');
809     echo html_writer::end_tag('p');
811     if (empty($user)) {
812         $user = $USER;
813     }
815     $conversations = message_get_recent_conversations($user);
817     // Attach context url information to create the "View this conversation" type links
818     foreach($conversations as $conversation) {
819         $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
820         $conversation->contexturlname = get_string('thisconversation', 'message');
821     }
823     $showotheruser = true;
824     message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
827 /**
828  * Print the user's recent notifications
829  *
830  * @param stdClass $user the current user
831  */
832 function message_print_recent_notifications($user=null) {
833     global $USER;
835     echo html_writer::start_tag('p', array('class' => 'heading'));
836     echo get_string('mostrecentnotifications', 'message');
837     echo html_writer::end_tag('p');
839     if (empty($user)) {
840         $user = $USER;
841     }
843     $notifications = message_get_recent_notifications($user);
845     $showicontext = false;
846     $showotheruser = false;
847     message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
850 /**
851  * Print a list of recent messages
852  *
853  * @param array $messages the messages to display
854  * @param object $user the current user
855  * @param bool $showotheruser display information on the other user?
856  * @param bool $showicontext show text next to the action icons?
857  * @return void
858  */
859 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
860     global $OUTPUT;
861     static $dateformat;
863     if (empty($dateformat)) {
864         $dateformat = get_string('strftimedatetimeshort');
865     }
867     echo html_writer::start_tag('div', array('class' => 'messagerecent'));
868     foreach ($messages as $message) {
869         echo html_writer::start_tag('div', array('class' => 'singlemessage'));
871         if ($showotheruser) {
872             if ( $message->contactlistid )  {
873                 if ($message->blocked == 0) { /// not blocked
874                     $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
875                     $strblock   = message_contact_link($message->id, 'block', true, null, $showicontext);
876                 } else { // blocked
877                     $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
878                     $strblock   = message_contact_link($message->id, 'unblock', true, null, $showicontext);
879                 }
880             } else {
881                 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
882                 $strblock   = message_contact_link($message->id, 'block', true, null, $showicontext);
883             }
885             //should we show just the icon or icon and text?
886             $histicontext = 'icon';
887             if ($showicontext) {
888                 $histicontext = 'both';
889             }
890             $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
892             echo html_writer::start_tag('span', array('class' => 'otheruser'));
894             echo html_writer::start_tag('span', array('class' => 'pix'));
895             echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
896             echo html_writer::end_tag('span');
898             echo html_writer::start_tag('span', array('class' => 'contact'));
900             $link = new moodle_url("/message/index.php?id=$message->id");
901             $action = null;
902             echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
904             echo html_writer::end_tag('span');//end contact
906             echo $strcontact.$strblock.$strhistory;
907             echo html_writer::end_tag('span');//end otheruser
908         }
909         $messagetoprint = null;
910         if (!empty($message->smallmessage)) {
911             $messagetoprint = $message->smallmessage;
912         } else {
913             $messagetoprint = $message->fullmessage;
914         }
916         echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
917         echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
918         echo message_format_contexturl($message);
919         echo html_writer::end_tag('div');//end singlemessage
920     }
921     echo html_writer::end_tag('div');//end messagerecent
924 /**
925  * Add the selected user as a contact for the current user
926  *
927  * @param int $contactid the ID of the user to add as a contact
928  * @param int $blocked 1 if you wish to block the contact
929  * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
930  *                  Otherwise returns the result of update_record() or insert_record()
931  */
932 function message_add_contact($contactid, $blocked=0) {
933     global $USER, $DB;
935     if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
936         return false;
937     }
939     if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
940     /// record already exists - we may be changing blocking status
942         if ($contact->blocked !== $blocked) {
943         /// change to blocking status
944             $contact->blocked = $blocked;
945             return $DB->update_record('message_contacts', $contact);
946         } else {
947         /// no changes to blocking status
948             return true;
949         }
951     } else {
952     /// new contact record
953         $contact = new stdClass();
954         $contact->userid = $USER->id;
955         $contact->contactid = $contactid;
956         $contact->blocked = $blocked;
957         return $DB->insert_record('message_contacts', $contact, false);
958     }
961 /**
962  * remove a contact
963  *
964  * @param int $contactid the user ID of the contact to remove
965  * @return bool returns the result of delete_records()
966  */
967 function message_remove_contact($contactid) {
968     global $USER, $DB;
969     return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
972 /**
973  * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
974  *
975  * @param int $contactid the user ID of the contact to unblock
976  * @return bool returns the result of delete_records()
977  */
978 function message_unblock_contact($contactid) {
979     global $USER, $DB;
980     return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
983 /**
984  * block a user
985  *
986  * @param int $contactid the user ID of the user to block
987  */
988 function message_block_contact($contactid) {
989     return message_add_contact($contactid, 1);
992 /**
993  * Load a user's contact record
994  *
995  * @param int $contactid the user ID of the user whose contact record you want
996  * @return array message contacts
997  */
998 function message_get_contact($contactid) {
999     global $USER, $DB;
1000     return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1003 /**
1004  * Print the results of a message search
1005  *
1006  * @param mixed $frm submitted form data
1007  * @param bool $showicontext show text next to action icons?
1008  * @param object $currentuser the current user
1009  * @return void
1010  */
1011 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1012     global $USER, $DB, $OUTPUT;
1014     if (empty($currentuser)) {
1015         $currentuser = $USER;
1016     }
1018     echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1020     $personsearch = false;
1021     $personsearchstring = null;
1022     if (!empty($frm->personsubmit) and !empty($frm->name)) {
1023         $personsearch = true;
1024         $personsearchstring = $frm->name;
1025     } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1026         $personsearch = true;
1027         $personsearchstring = $frm->combinedsearch;
1028     }
1030     /// search for person
1031     if ($personsearch) {
1032         if (optional_param('mycourses', 0, PARAM_BOOL)) {
1033             $users = array();
1034             $mycourses = enrol_get_my_courses();
1035             foreach ($mycourses as $mycourse) {
1036                 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1037                     foreach ($susers as $suser) $users[$suser->id] = $suser;
1038                 }
1039             }
1040         } else {
1041             $users = message_search_users(SITEID, $personsearchstring);
1042         }
1044         if (!empty($users)) {
1045             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1046             echo get_string('userssearchresults', 'message', count($users));
1047             echo html_writer::end_tag('p');
1049             echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1050             foreach ($users as $user) {
1052                 if ( $user->contactlistid )  {
1053                     if ($user->blocked == 0) { /// not blocked
1054                         $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1055                         $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
1056                     } else { // blocked
1057                         $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1058                         $strblock   = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1059                     }
1060                 } else {
1061                     $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1062                     $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
1063                 }
1065                 //should we show just the icon or icon and text?
1066                 $histicontext = 'icon';
1067                 if ($showicontext) {
1068                     $histicontext = 'both';
1069                 }
1070                 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1072                 echo html_writer::start_tag('tr');
1074                 echo html_writer::start_tag('td', array('class' => 'pix'));
1075                 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1076                 echo html_writer::end_tag('td');
1078                 echo html_writer::start_tag('td',array('class' => 'contact'));
1079                 $action = null;
1080                 $link = new moodle_url("/message/index.php?id=$user->id");
1081                 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1082                 echo html_writer::end_tag('td');
1084                 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1085                 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1086                 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1088                 echo html_writer::end_tag('tr');
1089             }
1090             echo html_writer::end_tag('table');
1092         } else {
1093             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1094             echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1095             echo html_writer::end_tag('p');
1096         }
1097     }
1099     // search messages for keywords
1100     $messagesearch = false;
1101     $messagesearchstring = null;
1102     if (!empty($frm->keywords)) {
1103         $messagesearch = true;
1104         $messagesearchstring = clean_text(trim($frm->keywords));
1105     } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1106         $messagesearch = true;
1107         $messagesearchstring = clean_text(trim($frm->combinedsearch));
1108     }
1110     if ($messagesearch) {
1111         if ($messagesearchstring) {
1112             $keywords = explode(' ', $messagesearchstring);
1113         } else {
1114             $keywords = array();
1115         }
1116         $tome     = false;
1117         $fromme   = false;
1118         $courseid = 'none';
1120         if (empty($frm->keywordsoption)) {
1121             $frm->keywordsoption = 'allmine';
1122         }
1124         switch ($frm->keywordsoption) {
1125             case 'tome':
1126                 $tome   = true;
1127                 break;
1128             case 'fromme':
1129                 $fromme = true;
1130                 break;
1131             case 'allmine':
1132                 $tome   = true;
1133                 $fromme = true;
1134                 break;
1135             case 'allusers':
1136                 $courseid = SITEID;
1137                 break;
1138             case 'courseusers':
1139                 $courseid = $frm->courseid;
1140                 break;
1141             default:
1142                 $tome   = true;
1143                 $fromme = true;
1144         }
1146         if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1148         /// get a list of contacts
1149             if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1150                 $contacts = array();
1151             }
1153         /// print heading with number of results
1154             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1155             $countresults = count($messages);
1156             if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1157                 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1158             } else {
1159                 echo get_string('keywordssearchresults', 'message', $countresults);
1160             }
1161             echo html_writer::end_tag('p');
1163         /// print table headings
1164             echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1166             $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1167             $headertdend   = html_writer::end_tag('td');
1168             echo html_writer::start_tag('tr');
1169             echo $headertdstart.get_string('from').$headertdend;
1170             echo $headertdstart.get_string('to').$headertdend;
1171             echo $headertdstart.get_string('message', 'message').$headertdend;
1172             echo $headertdstart.get_string('timesent', 'message').$headertdend;
1173             echo html_writer::end_tag('tr');
1175             $blockedcount = 0;
1176             $dateformat = get_string('strftimedatetimeshort');
1177             $strcontext = get_string('context', 'message');
1178             foreach ($messages as $message) {
1180             /// ignore messages to and from blocked users unless $frm->includeblocked is set
1181                 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1182                       ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1183                       ( isset($contacts[$message->useridto]  ) and ($contacts[$message->useridto]->blocked   == 1))
1184                                                 )
1185                    ) {
1186                     $blockedcount ++;
1187                     continue;
1188                 }
1190             /// load up user to record
1191                 if ($message->useridto !== $USER->id) {
1192                     $userto = $DB->get_record('user', array('id' => $message->useridto));
1193                     $tocontact = (array_key_exists($message->useridto, $contacts) and
1194                                     ($contacts[$message->useridto]->blocked == 0) );
1195                     $toblocked = (array_key_exists($message->useridto, $contacts) and
1196                                     ($contacts[$message->useridto]->blocked == 1) );
1197                 } else {
1198                     $userto = false;
1199                     $tocontact = false;
1200                     $toblocked = false;
1201                 }
1203             /// load up user from record
1204                 if ($message->useridfrom !== $USER->id) {
1205                     $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1206                     $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1207                                     ($contacts[$message->useridfrom]->blocked == 0) );
1208                     $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1209                                     ($contacts[$message->useridfrom]->blocked == 1) );
1210                 } else {
1211                     $userfrom = false;
1212                     $fromcontact = false;
1213                     $fromblocked = false;
1214                 }
1216             /// find date string for this message
1217                 $date = usergetdate($message->timecreated);
1218                 $datestring = $date['year'].$date['mon'].$date['mday'];
1220             /// print out message row
1221                 echo html_writer::start_tag('tr', array('valign' => 'top'));
1223                 echo html_writer::start_tag('td', array('class' => 'contact'));
1224                 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1225                 echo html_writer::end_tag('td');
1227                 echo html_writer::start_tag('td', array('class' => 'contact'));
1228                 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1229                 echo html_writer::end_tag('td');
1231                 echo html_writer::start_tag('td', array('class' => 'summary'));
1232                 echo message_get_fragment($message->fullmessage, $keywords);
1233                 echo html_writer::start_tag('div', array('class' => 'link'));
1235                 //If the user clicks the context link display message sender on the left
1236                 //EXCEPT if the current user is in the conversation. Current user == always on the left
1237                 $leftsideuserid = $rightsideuserid = null;
1238                 if ($currentuser->id == $message->useridto) {
1239                     $leftsideuserid = $message->useridto;
1240                     $rightsideuserid = $message->useridfrom;
1241                 } else {
1242                     $leftsideuserid = $message->useridfrom;
1243                     $rightsideuserid = $message->useridto;
1244                 }
1245                 message_history_link($leftsideuserid, $rightsideuserid, false,
1246                                      $messagesearchstring, 'm'.$message->id, $strcontext);
1247                 echo html_writer::end_tag('div');
1248                 echo html_writer::end_tag('td');
1250                 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1252                 echo html_writer::end_tag('tr');
1253             }
1256             if ($blockedcount > 0) {
1257                 echo html_writer::start_tag('tr');
1258                 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1259                 echo html_writer::end_tag('tr');
1260             }
1261             echo html_writer::end_tag('table');
1263         } else {
1264             echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1265         }
1266     }
1268     if (!$personsearch && !$messagesearch) {
1269         //they didn't enter any search terms
1270         echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1271     }
1273     echo html_writer::end_tag('div');
1276 /**
1277  * Print information on a user. Used when printing search results.
1278  *
1279  * @param object/bool $user the user to display or false if you just want $USER
1280  * @param bool $iscontact is the user being displayed a contact?
1281  * @param bool $isblocked is the user being displayed blocked?
1282  * @param bool $includeicontext include text next to the action icons?
1283  * @return void
1284  */
1285 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1286     global $USER, $OUTPUT;
1288     if ($user === false) {
1289         echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1290     } else {
1291         echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1292         echo '&nbsp;';
1294         $return = false;
1295         $script = null;
1296         if ($iscontact) {
1297             message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1298         } else {
1299             message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1300         }
1301         echo '&nbsp;';
1302         if ($isblocked) {
1303             message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1304         } else {
1305             message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1306         }
1308         $popupoptions = array(
1309                 'height' => MESSAGE_DISCUSSION_HEIGHT,
1310                 'width' => MESSAGE_DISCUSSION_WIDTH,
1311                 'menubar' => false,
1312                 'location' => false,
1313                 'status' => true,
1314                 'scrollbars' => true,
1315                 'resizable' => true);
1317         $link = new moodle_url("/message/index.php?id=$user->id");
1318         //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1319         $action = null;
1320         echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1322     }
1325 /**
1326  * Print a message contact link
1327  *
1328  * @param int $userid the ID of the user to apply to action to
1329  * @param string $linktype can be add, remove, block or unblock
1330  * @param bool $return if true return the link as a string. If false echo the link.
1331  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1332  * @param bool $text include text next to the icons?
1333  * @param bool $icon include a graphical icon?
1334  * @return string  if $return is true otherwise bool
1335  */
1336 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1337     global $OUTPUT, $PAGE;
1339     //hold onto the strings as we're probably creating a bunch of links
1340     static $str;
1342     if (empty($script)) {
1343         //strip off previous action params like 'removecontact'
1344         $script = message_remove_url_params($PAGE->url);
1345     }
1347     if (empty($str->blockcontact)) {
1348        $str = new stdClass();
1349        $str->blockcontact   =  get_string('blockcontact', 'message');
1350        $str->unblockcontact =  get_string('unblockcontact', 'message');
1351        $str->removecontact  =  get_string('removecontact', 'message');
1352        $str->addcontact     =  get_string('addcontact', 'message');
1353     }
1355     $command = $linktype.'contact';
1356     $string  = $str->{$command};
1358     $safealttext = s($string);
1360     $safestring = '';
1361     if (!empty($text)) {
1362         $safestring = $safealttext;
1363     }
1365     $img = '';
1366     if ($icon) {
1367         $iconpath = null;
1368         switch ($linktype) {
1369             case 'block':
1370                 $iconpath = 't/block';
1371                 break;
1372             case 'unblock':
1373                 $iconpath = 't/userblue';
1374                 break;
1375             case 'remove':
1376                 $iconpath = 'i/cross_red_big';
1377                 break;
1378             case 'add':
1379             default:
1380                 $iconpath = 't/addgreen';
1381         }
1383         $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1384     }
1386     $output = '<span class="'.$linktype.'contact">'.
1387               '<a href="'.$script.'&amp;'.$command.'='.$userid.
1388               '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1389               $img.
1390               $safestring.'</a></span>';
1392     if ($return) {
1393         return $output;
1394     } else {
1395         echo $output;
1396         return true;
1397     }
1400 /**
1401  * echo or return a link to take the user to the full message history between themselves and another user
1402  *
1403  * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1404  * @param int $userid2 the ID of the other user
1405  * @param bool $return true to return the link as a string. False to echo the link.
1406  * @param string $keywords any keywords to highlight in the message history
1407  * @param string $position anchor name to jump to within the message history
1408  * @param string $linktext optionally specify the link text
1409  * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1410  */
1411 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1412     global $OUTPUT;
1413     static $strmessagehistory;
1415     if (empty($strmessagehistory)) {
1416         $strmessagehistory = get_string('messagehistory', 'message');
1417     }
1419     if ($position) {
1420         $position = "#$position";
1421     }
1422     if ($keywords) {
1423         $keywords = "&search=".urlencode($keywords);
1424     }
1426     if ($linktext == 'icon') {  // Icon only
1427         $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1428     } else if ($linktext == 'both') {  // Icon and standard name
1429         $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1430         $fulllink .= '&nbsp;'.$strmessagehistory;
1431     } else if ($linktext) {    // Custom name
1432         $fulllink = $linktext;
1433     } else {                   // Standard name only
1434         $fulllink = $strmessagehistory;
1435     }
1437     $popupoptions = array(
1438             'height' => 500,
1439             'width' => 500,
1440             'menubar' => false,
1441             'location' => false,
1442             'status' => true,
1443             'scrollbars' => true,
1444             'resizable' => true);
1446     $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1447     $action = null;
1448     $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1450     $str = '<span class="history">'.$str.'</span>';
1452     if ($return) {
1453         return $str;
1454     } else {
1455         echo $str;
1456         return true;
1457     }
1461 /**
1462  * Search through course users
1463  *
1464  * If $coursid specifies the site course then this function searches
1465  * through all undeleted and confirmed users
1466  * @param int $courseid The course in question.
1467  * @param string $searchtext the text to search for
1468  * @param string $sort the column name to order by
1469  * @param string $exceptions comma separated list of user IDs to exclude
1470  * @return array  An array of {@link $USER} records.
1471  */
1472 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1473     global $CFG, $USER, $DB;
1475     $fullname = $DB->sql_fullname();
1477     if (!empty($exceptions)) {
1478         $except = ' AND u.id NOT IN ('. $exceptions .') ';
1479     } else {
1480         $except = '';
1481     }
1483     if (!empty($sort)) {
1484         $order = ' ORDER BY '. $sort;
1485     } else {
1486         $order = '';
1487     }
1489     $ufields = user_picture::fields('u');
1490     if (!$courseid or $courseid == SITEID) {
1491         $params = array($USER->id, "%$searchtext%");
1492         return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1493                                        FROM {user} u
1494                                        LEFT JOIN {message_contacts} mc
1495                                             ON mc.contactid = u.id AND mc.userid = ?
1496                                       WHERE u.deleted = '0' AND u.confirmed = '1'
1497                                             AND (".$DB->sql_like($fullname, '?', false).")
1498                                             $except
1499                                      $order", $params);
1500     } else {
1501 //TODO: add enabled enrolment join here (skodak)
1502         $context = context_course::instance($courseid);
1503         $contextlists = get_related_contexts_string($context);
1505         // everyone who has a role assignment in this course or higher
1506         $params = array($USER->id, "%$searchtext%");
1507         $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1508                                          FROM {user} u
1509                                          JOIN {role_assignments} ra ON ra.userid = u.id
1510                                          LEFT JOIN {message_contacts} mc
1511                                               ON mc.contactid = u.id AND mc.userid = ?
1512                                         WHERE u.deleted = '0' AND u.confirmed = '1'
1513                                               AND ra.contextid $contextlists
1514                                               AND (".$DB->sql_like($fullname, '?', false).")
1515                                               $except
1516                                        $order", $params);
1518         return $users;
1519     }
1522 /**
1523  * search a user's messages
1524  *
1525  * @param array $searchterms an array of search terms (strings)
1526  * @param bool $fromme include messages from the user?
1527  * @param bool $tome include messages to the user?
1528  * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1529  * @param int $userid the user ID of the current user
1530  * @return mixed An array of messages or false if no matching messages were found
1531  */
1532 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1533 /// Returns a list of posts found using an array of search terms
1534 /// eg   word  +word -word
1535 ///
1536     global $CFG, $USER, $DB;
1538     // If user is searching all messages check they are allowed to before doing anything else
1539     if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1540         print_error('accessdenied','admin');
1541     }
1543     /// If no userid sent then assume current user
1544     if ($userid == 0) $userid = $USER->id;
1546     /// Some differences in SQL syntax
1547     if ($DB->sql_regex_supported()) {
1548         $REGEXP    = $DB->sql_regex(true);
1549         $NOTREGEXP = $DB->sql_regex(false);
1550     }
1552     $searchcond = array();
1553     $params = array();
1554     $i = 0;
1556     //preprocess search terms to check whether we have at least 1 eligible search term
1557     //if we do we can drop words around it like 'a'
1558     $dropshortwords = false;
1559     foreach ($searchterms as $searchterm) {
1560         if (strlen($searchterm) >= 2) {
1561             $dropshortwords = true;
1562         }
1563     }
1565     foreach ($searchterms as $searchterm) {
1566         $i++;
1568         $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1570         if ($dropshortwords && strlen($searchterm) < 2) {
1571             continue;
1572         }
1573     /// Under Oracle and MSSQL, trim the + and - operators and perform
1574     /// simpler LIKE search
1575         if (!$DB->sql_regex_supported()) {
1576             if (substr($searchterm, 0, 1) == '-') {
1577                 $NOT = true;
1578             }
1579             $searchterm = trim($searchterm, '+-');
1580         }
1582         if (substr($searchterm,0,1) == "+") {
1583             $searchterm = substr($searchterm,1);
1584             $searchterm = preg_quote($searchterm, '|');
1585             $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1586             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1588         } else if (substr($searchterm,0,1) == "-") {
1589             $searchterm = substr($searchterm,1);
1590             $searchterm = preg_quote($searchterm, '|');
1591             $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1592             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1594         } else {
1595             $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1596             $params['ss'.$i] = "%$searchterm%";
1597         }
1598     }
1600     if (empty($searchcond)) {
1601         $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1602         $params['ss1'] = "%";
1603     } else {
1604         $searchcond = implode(" AND ", $searchcond);
1605     }
1607     /// There are several possibilities
1608     /// 1. courseid = SITEID : The admin is searching messages by all users
1609     /// 2. courseid = ??     : A teacher is searching messages by users in
1610     ///                        one of their courses - currently disabled
1611     /// 3. courseid = none   : User is searching their own messages;
1612     ///    a.  Messages from user
1613     ///    b.  Messages to user
1614     ///    c.  Messages to and from user
1616     if ($courseid == SITEID) { /// admin is searching all messages
1617         $m_read   = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1618                                             FROM {message_read} m
1619                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1620         $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1621                                             FROM {message} m
1622                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1624     } else if ($courseid !== 'none') {
1625         /// This has not been implemented due to security concerns
1626         $m_read   = array();
1627         $m_unread = array();
1629     } else {
1631         if ($fromme and $tome) {
1632             $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1633             $params['userid1'] = $userid;
1634             $params['userid2'] = $userid;
1636         } else if ($fromme) {
1637             $searchcond .= " AND m.useridfrom=:userid";
1638             $params['userid'] = $userid;
1640         } else if ($tome) {
1641             $searchcond .= " AND m.useridto=:userid";
1642             $params['userid'] = $userid;
1643         }
1645         $m_read   = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1646                                             FROM {message_read} m
1647                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1648         $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1649                                             FROM {message} m
1650                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1652     }
1654     /// The keys may be duplicated in $m_read and $m_unread so we can't
1655     /// do a simple concatenation
1656     $messages = array();
1657     foreach ($m_read as $m) {
1658         $messages[] = $m;
1659     }
1660     foreach ($m_unread as $m) {
1661         $messages[] = $m;
1662     }
1664     return (empty($messages)) ? false : $messages;
1667 /**
1668  * Given a message object that we already know has a long message
1669  * this function truncates the message nicely to the first
1670  * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1671  *
1672  * @param string $message the message
1673  * @param int $minlength the minimum length to trim the message to
1674  * @return string the shortened message
1675  */
1676 function message_shorten_message($message, $minlength = 0) {
1677     $i = 0;
1678     $tag = false;
1679     $length = strlen($message);
1680     $count = 0;
1681     $stopzone = false;
1682     $truncate = 0;
1683     if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1686     for ($i=0; $i<$length; $i++) {
1687         $char = $message[$i];
1689         switch ($char) {
1690             case "<":
1691                 $tag = true;
1692                 break;
1693             case ">":
1694                 $tag = false;
1695                 break;
1696             default:
1697                 if (!$tag) {
1698                     if ($stopzone) {
1699                         if ($char == '.' or $char == ' ') {
1700                             $truncate = $i+1;
1701                             break 2;
1702                         }
1703                     }
1704                     $count++;
1705                 }
1706                 break;
1707         }
1708         if (!$stopzone) {
1709             if ($count > $minlength) {
1710                 $stopzone = true;
1711             }
1712         }
1713     }
1715     if (!$truncate) {
1716         $truncate = $i;
1717     }
1719     return substr($message, 0, $truncate);
1723 /**
1724  * Given a string and an array of keywords, this function looks
1725  * for the first keyword in the string, and then chops out a
1726  * small section from the text that shows that word in context.
1727  *
1728  * @param string $message the text to search
1729  * @param array $keywords array of keywords to find
1730  */
1731 function message_get_fragment($message, $keywords) {
1733     $fullsize = 160;
1734     $halfsize = (int)($fullsize/2);
1736     $message = strip_tags($message);
1738     foreach ($keywords as $keyword) {  // Just get the first one
1739         if ($keyword !== '') {
1740             break;
1741         }
1742     }
1743     if (empty($keyword)) {   // None found, so just return start of message
1744         return message_shorten_message($message, 30);
1745     }
1747     $leadin = $leadout = '';
1749 /// Find the start of the fragment
1750     $start = 0;
1751     $length = strlen($message);
1753     $pos = strpos($message, $keyword);
1754     if ($pos > $halfsize) {
1755         $start = $pos - $halfsize;
1756         $leadin = '...';
1757     }
1758 /// Find the end of the fragment
1759     $end = $start + $fullsize;
1760     if ($end > $length) {
1761         $end = $length;
1762     } else {
1763         $leadout = '...';
1764     }
1766 /// Pull out the fragment and format it
1768     $fragment = substr($message, $start, $end - $start);
1769     $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1770     return $fragment;
1773 /**
1774  * Retrieve the messages between two users
1775  *
1776  * @param object $user1 the current user
1777  * @param object $user2 the other user
1778  * @param int $limitnum the maximum number of messages to retrieve
1779  * @param bool $viewingnewmessages are we currently viewing new messages?
1780  */
1781 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1782     global $DB, $CFG;
1784     $messages = array();
1786     //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1787     //desc to get the last $limitnum messages then flip the order in php
1788     $sort = 'asc';
1789     if ($limitnum>0) {
1790         $sort = 'desc';
1791     }
1793     $notificationswhere = null;
1794     //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1795     if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1796         $notificationswhere = 'AND notification=0';
1797     }
1799     //prevent notifications of your own actions appearing in your own message history
1800     $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1802     if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1803                                                     (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1804                                                     array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1805                                                     "timecreated $sort", '*', 0, $limitnum)) {
1806         foreach ($messages_read as $message) {
1807             $messages[$message->timecreated] = $message;
1808         }
1809     }
1810     if ($messages_new =  $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1811                                                     (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1812                                                     array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1813                                                     "timecreated $sort", '*', 0, $limitnum)) {
1814         foreach ($messages_new as $message) {
1815             $messages[$message->timecreated] = $message;
1816         }
1817     }
1819     //if we only want the last $limitnum messages
1820     ksort($messages);
1821     $messagecount = count($messages);
1822     if ($limitnum>0 && $messagecount>$limitnum) {
1823         $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1824     }
1826     return $messages;
1829 /**
1830  * Print the message history between two users
1831  *
1832  * @param object $user1 the current user
1833  * @param object $user2 the other user
1834  * @param string $search search terms to highlight
1835  * @param int $messagelimit maximum number of messages to return
1836  * @param string $messagehistorylink the html for the message history link or false
1837  * @param bool $viewingnewmessages are we currently viewing new messages?
1838  */
1839 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1840     global $CFG, $OUTPUT;
1842     echo $OUTPUT->box_start('center');
1843     echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1844     echo html_writer::start_tag('tr');
1846     echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1847     echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1848     echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1849     echo html_writer::end_tag('td');
1851     echo html_writer::start_tag('td', array('align' => 'center'));
1852     echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1853     echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1854     echo html_writer::end_tag('td');
1856     echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1857     echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1858     echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1860     if (isset($user2->iscontact) && isset($user2->isblocked)) {
1861         $incontactlist = $user2->iscontact;
1862         $isblocked = $user2->isblocked;
1864         $script = null;
1865         $text = true;
1866         $icon = false;
1868         $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1869         $strblock   = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1870         $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1872         echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1873     }
1875     echo html_writer::end_tag('td');
1876     echo html_writer::end_tag('tr');
1877     echo html_writer::end_tag('table');
1878     echo $OUTPUT->box_end();
1880     if (!empty($messagehistorylink)) {
1881         echo $messagehistorylink;
1882     }
1884     /// Get all the messages and print them
1885     if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1886         $tablecontents = '';
1888         $current = new stdClass();
1889         $current->mday = '';
1890         $current->month = '';
1891         $current->year = '';
1892         $messagedate = get_string('strftimetime');
1893         $blockdate   = get_string('strftimedaydate');
1894         foreach ($messages as $message) {
1895             if ($message->notification) {
1896                 $notificationclass = ' notification';
1897             } else {
1898                 $notificationclass = null;
1899             }
1900             $date = usergetdate($message->timecreated);
1901             if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1902                 $current->mday = $date['mday'];
1903                 $current->month = $date['month'];
1904                 $current->year = $date['year'];
1906                 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1907                 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1909                 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1910             }
1912             $formatted_message = $side = null;
1913             if ($message->useridfrom == $user1->id) {
1914                 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1915                 $side = 'left';
1916             } else {
1917                 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1918                 $side = 'right';
1919             }
1920             $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1921         }
1923         echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1924     } else {
1925         echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1926     }
1929 /**
1930  * Format a message for display in the message history
1931  *
1932  * @param object $message the message object
1933  * @param string $format optional date format
1934  * @param string $keywords keywords to highlight
1935  * @param string $class CSS class to apply to the div around the message
1936  * @return string the formatted message
1937  */
1938 function message_format_message($message, $format='', $keywords='', $class='other') {
1940     static $dateformat;
1942     //if we haven't previously set the date format or they've supplied a new one
1943     if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1944         if ($format) {
1945             $dateformat = $format;
1946         } else {
1947             $dateformat = get_string('strftimedatetimeshort');
1948         }
1949     }
1950     $time = userdate($message->timecreated, $dateformat);
1951     $options = new stdClass();
1952     $options->para = false;
1954     //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1955     if (!empty($message->smallmessage)) {
1956         $messagetext = $message->smallmessage;
1957     } else {
1958         $messagetext = $message->fullmessage;
1959     }
1960     if ($message->fullmessageformat == FORMAT_HTML) {
1961         //dont escape html tags by calling s() if html format or they will display in the UI
1962         $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1963     } else {
1964         $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1965     }
1967     $messagetext .= message_format_contexturl($message);
1969     if ($keywords) {
1970         $messagetext = highlight($keywords, $messagetext);
1971     }
1973     return <<<TEMPLATE
1974 <div class='message $class'>
1975     <a name="m'.{$message->id}.'"></a>
1976     <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
1977 </div>
1978 TEMPLATE;
1981 /**
1982  * Format a the context url and context url name of a message for display
1983  *
1984  * @param object $message the message object
1985  * @return string the formatted string
1986  */
1987 function message_format_contexturl($message) {
1988     $s = null;
1990     if (!empty($message->contexturl)) {
1991         $displaytext = null;
1992         if (!empty($message->contexturlname)) {
1993             $displaytext= $message->contexturlname;
1994         } else {
1995             $displaytext= $message->contexturl;
1996         }
1997         $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1998             $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1999         $s .= html_writer::end_tag('div');
2000     }
2002     return $s;
2005 /**
2006  * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2007  *
2008  * @param object $userfrom the message sender
2009  * @param object $userto the message recipient
2010  * @param string $message the message
2011  * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2012  * @return int|false the ID of the new message or false
2013  */
2014 function message_post_message($userfrom, $userto, $message, $format) {
2015     global $SITE, $CFG, $USER;
2017     $eventdata = new stdClass();
2018     $eventdata->component        = 'moodle';
2019     $eventdata->name             = 'instantmessage';
2020     $eventdata->userfrom         = $userfrom;
2021     $eventdata->userto           = $userto;
2023     //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2024     $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2026     if ($format == FORMAT_HTML) {
2027         $eventdata->fullmessagehtml  = $message;
2028         //some message processors may revert to sending plain text even if html is supplied
2029         //so we keep both plain and html versions if we're intending to send html
2030         $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2031     } else {
2032         $eventdata->fullmessage      = $message;
2033         $eventdata->fullmessagehtml  = '';
2034     }
2036     $eventdata->fullmessageformat = $format;
2037     $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.
2039     $s = new stdClass();
2040     $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2041     $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2043     $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2044     if (!empty($eventdata->fullmessage)) {
2045         $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2046     }
2047     if (!empty($eventdata->fullmessagehtml)) {
2048         $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2049     }
2051     $eventdata->timecreated     = time();
2052     return message_send($eventdata);
2055 /**
2056  * Print a row of contactlist displaying user picture, messages waiting and
2057  * block links etc
2058  *
2059  * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2060  * @param bool $incontactlist is the user a contact of ours?
2061  * @param bool $isblocked is the user blocked?
2062  * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2063  * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2064  * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2065  * @return void
2066  */
2067 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2068     global $OUTPUT, $USER;
2069     $fullname  = fullname($contact);
2070     $fullnamelink  = $fullname;
2072     $linkclass = '';
2073     if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2074         $linkclass = 'messageselecteduser';
2075     }
2077     /// are there any unread messages for this contact?
2078     if ($contact->messagecount > 0 ){
2079         $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2080     }
2082     $strcontact = $strblock = $strhistory = null;
2084     if ($showactionlinks) {
2085         $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2086         $strblock   = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2087         $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2088     }
2090     echo html_writer::start_tag('tr');
2091     echo html_writer::start_tag('td', array('class' => 'pix'));
2092     echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2093     echo html_writer::end_tag('td');
2095     echo html_writer::start_tag('td', array('class' => 'contact'));
2097     $popupoptions = array(
2098             'height' => MESSAGE_DISCUSSION_HEIGHT,
2099             'width' => MESSAGE_DISCUSSION_WIDTH,
2100             'menubar' => false,
2101             'location' => false,
2102             'status' => true,
2103             'scrollbars' => true,
2104             'resizable' => true);
2106     $link = $action = null;
2107     if (!empty($selectcontacturl)) {
2108         $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2109     } else {
2110         //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2111         $link = new moodle_url("/message/index.php?id=$contact->id");
2112         $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2113     }
2114     echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2116     echo html_writer::end_tag('td');
2118     echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2120     echo html_writer::end_tag('tr');
2123 /**
2124  * Constructs the add/remove contact link to display next to other users
2125  *
2126  * @param bool $incontactlist is the user a contact
2127  * @param bool $isblocked is the user blocked
2128  * @param stdClass $contact contact object
2129  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2130  * @param bool $text include text next to the icons?
2131  * @param bool $icon include a graphical icon?
2132  * @return string
2133  */
2134 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2135     $strcontact = '';
2137     if($incontactlist){
2138         $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2139     } else if ($isblocked) {
2140         $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2141     } else{
2142         $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2143     }
2145     return $strcontact;
2148 /**
2149  * Constructs the block contact link to display next to other users
2150  *
2151  * @param bool $incontactlist is the user a contact?
2152  * @param bool $isblocked is the user blocked?
2153  * @param stdClass $contact contact object
2154  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2155  * @param bool $text include text next to the icons?
2156  * @param bool $icon include a graphical icon?
2157  * @return string
2158  */
2159 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2160     $strblock   = '';
2162     //commented out to allow the user to block a contact without having to remove them first
2163     /*if ($incontactlist) {
2164         //$strblock = '';
2165     } else*/
2166     if ($isblocked) {
2167         $strblock   = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2168     } else{
2169         $strblock   = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2170     }
2172     return $strblock;
2175 /**
2176  * Moves messages from a particular user from the message table (unread messages) to message_read
2177  * This is typically only used when a user is deleted
2178  *
2179  * @param object $userid User id
2180  * @return boolean success
2181  */
2182 function message_move_userfrom_unread2read($userid) {
2183     global $DB;
2185     // move all unread messages from message table to message_read
2186     if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2187         foreach ($messages as $message) {
2188             message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2189         }
2190     }
2191     return true;
2194 /**
2195  * marks ALL messages being sent from $fromuserid to $touserid as read
2196  *
2197  * @param int $touserid the id of the message recipient
2198  * @param int $fromuserid the id of the message sender
2199  * @return void
2200  */
2201 function message_mark_messages_read($touserid, $fromuserid){
2202     global $DB;
2204     $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2205     $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2207     foreach ($messages as $message) {
2208         message_mark_message_read($message, time());
2209     }
2211     $messages->close();
2214 /**
2215  * Mark a single message as read
2216  *
2217  * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2218  * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2219  * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2220  * @return int the ID of the message in the message_read table
2221  */
2222 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2223     global $DB;
2225     $message->timeread = $timeread;
2227     $messageid = $message->id;
2228     unset($message->id);//unset because it will get a new id on insert into message_read
2230     //If any processors have pending actions abort them
2231     if (!$messageworkingempty) {
2232         $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2233     }
2234     $messagereadid = $DB->insert_record('message_read', $message);
2235     $DB->delete_records('message', array('id' => $messageid));
2236     return $messagereadid;
2239 /**
2240  * A helper function that prints a formatted heading
2241  *
2242  * @param string $title the heading to display
2243  * @param int $colspan
2244  * @return void
2245  */
2246 function message_print_heading($title, $colspan=3) {
2247     echo html_writer::start_tag('tr');
2248     echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2249     echo html_writer::end_tag('tr');
2252 /**
2253  * Get all message processors, validate corresponding plugin existance and
2254  * system configuration
2255  *
2256  * @param bool $ready only return ready-to-use processors
2257  * @return mixed $processors array of objects containing information on message processors
2258  */
2259 function get_message_processors($ready = false) {
2260     global $DB, $CFG;
2262     static $processors;
2264     if (empty($processors)) {
2265         // Get all processors, ensure the name column is the first so it will be the array key
2266         $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2267         foreach ($processors as &$processor){
2268             $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2269             if (is_readable($processorfile)) {
2270                 include_once($processorfile);
2271                 $processclass = 'message_output_' . $processor->name;
2272                 if (class_exists($processclass)) {
2273                     $pclass = new $processclass();
2274                     $processor->object = $pclass;
2275                     $processor->configured = 0;
2276                     if ($pclass->is_system_configured()) {
2277                         $processor->configured = 1;
2278                     }
2279                     $processor->hassettings = 0;
2280                     if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2281                         $processor->hassettings = 1;
2282                     }
2283                     $processor->available = 1;
2284                 } else {
2285                     print_error('errorcallingprocessor', 'message');
2286                 }
2287             } else {
2288                 $processor->available = 0;
2289             }
2290         }
2291     }
2292     if ($ready) {
2293         // Filter out enabled and system_configured processors
2294         $readyprocessors = $processors;
2295         foreach ($readyprocessors as $readyprocessor) {
2296             if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2297                 unset($readyprocessors[$readyprocessor->name]);
2298             }
2299         }
2300         return $readyprocessors;
2301     }
2303     return $processors;
2306 /**
2307  * Get all message providers, validate their plugin existance and
2308  * system configuration
2309  *
2310  * @return mixed $processors array of objects containing information on message processors
2311  */
2312 function get_message_providers() {
2313     global $CFG, $DB;
2314     require_once($CFG->libdir . '/pluginlib.php');
2315     $pluginman = plugin_manager::instance();
2317     $providers = $DB->get_records('message_providers', null, 'name');
2319     // Remove all the providers whose plugins are disabled or don't exist
2320     foreach ($providers as $providerid => $provider) {
2321         $plugin = $pluginman->get_plugin_info($provider->component);
2322         if ($plugin) {
2323             if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2324                 unset($providers[$providerid]);   // Plugins does not exist
2325                 continue;
2326             }
2327             if ($plugin->is_enabled() === false) {
2328                 unset($providers[$providerid]);   // Plugin disabled
2329                 continue;
2330             }
2331         }
2332     }
2333     return $providers;
2336 /**
2337  * Get an instance of the message_output class for one of the output plugins.
2338  * @param string $type the message output type. E.g. 'email' or 'jabber'.
2339  * @return message_output message_output the requested class.
2340  */
2341 function get_message_processor($type) {
2342     global $CFG;
2344     // Note, we cannot use the get_message_processors function here, becaues this
2345     // code is called during install after installing each messaging plugin, and
2346     // get_message_processors caches the list of installed plugins.
2348     $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2349     if (!is_readable($processorfile)) {
2350         throw new coding_exception('Unknown message processor type ' . $type);
2351     }
2353     include_once($processorfile);
2355     $processclass = 'message_output_' . $type;
2356     if (!class_exists($processclass)) {
2357         throw new coding_exception('Message processor ' . $type .
2358                 ' does not define the right class');
2359     }
2361     return new $processclass();
2364 /**
2365  * Get messaging outputs default (site) preferences
2366  *
2367  * @return object $processors object containing information on message processors
2368  */
2369 function get_message_output_default_preferences() {
2370     return get_config('message');
2373 /**
2374  * Translate message default settings from binary value to the array of string
2375  * representing the settings to be stored. Also validate the provided value and
2376  * use default if it is malformed.
2377  *
2378  * @param  int    $plugindefault Default setting suggested by plugin
2379  * @param  string $processorname The name of processor
2380  * @return array  $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2381  */
2382 function translate_message_default_setting($plugindefault, $processorname) {
2383     // Preset translation arrays
2384     $permittedvalues = array(
2385         0x04 => 'disallowed',
2386         0x08 => 'permitted',
2387         0x0c => 'forced',
2388     );
2390     $loggedinstatusvalues = array(
2391         0x00 => null, // use null if loggedin/loggedoff is not defined
2392         0x01 => 'loggedin',
2393         0x02 => 'loggedoff',
2394     );
2396     // define the default setting
2397     $processor = get_message_processor($processorname);
2398     $default = $processor->get_default_messaging_settings();
2400     // Validate the value. It should not exceed the maximum size
2401     if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2402         debugging(get_string('errortranslatingdefault', 'message'));
2403         $plugindefault = $default;
2404     }
2405     // Use plugin default setting of 'permitted' is 0
2406     if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2407         $plugindefault = $default;
2408     }
2410     $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2411     $loggedin = $loggedoff = null;
2413     if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2414         $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2415         $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2416     }
2418     return array($permitted, $loggedin, $loggedoff);
2421 /**
2422  * Return a list of page types
2423  * @param string $pagetype current page type
2424  * @param stdClass $parentcontext Block's parent context
2425  * @param stdClass $currentcontext Current context of block
2426  */
2427 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2428     return array('messages-*'=>get_string('page-message-x', 'message'));
2431 /**
2432  * Is $USER one of the supplied users?
2433  *
2434  * $user2 will be null if viewing a user's recent conversations
2435  *
2436  * @param stdClass the first user
2437  * @param stdClass the second user or null
2438  * @return bool True if the current user is one of either $user1 or $user2
2439  */
2440 function message_current_user_is_involved($user1, $user2) {
2441     global $USER;
2443     if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2444         throw new coding_exception('Invalid user object detected. Missing id.');
2445     }
2447     if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2448         return false;
2449     }
2450     return true;