MDL-13805 core_message: altered some strings so it isnt weird when viewing a differen...
[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 define ('MESSAGE_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
50 /**
51  * Define contants for messaging default settings population. For unambiguity of
52  * plugin developer intentions we use 4-bit value (LSB numbering):
53  * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54  * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55  * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
56  *
57  * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
58  */
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
69 /**
70  * Set default value for default outputs permitted setting
71  */
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 /**
75  * Print the selector that allows the user to view their contacts, course participants, their recent
76  * conversations etc
77  *
78  * @param int $countunreadtotal how many unread messages does the user have?
79  * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80  * @param object $user1 the user whose messages are being viewed
81  * @param object $user2 the user $user1 is talking to
82  * @param array $blockedusers an array of users blocked by $user1
83  * @param array $onlinecontacts an array of $user1's online contacts
84  * @param array $offlinecontacts an array of $user1's offline contacts
85  * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86  * @param bool $showactionlinks show action links (add/remove contact etc)
87  * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
88  * @return void
89  */
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
91     global $PAGE;
93     echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
95     //if 0 unread messages and they've requested unread messages then show contacts
96     if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97         $viewing = MESSAGE_VIEW_CONTACTS;
98     }
100     //if they have no blocked users and they've requested blocked users switch them over to contacts
101     if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102         $viewing = MESSAGE_VIEW_CONTACTS;
103     }
105     $onlyactivecourses = true;
106     $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107     $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109     $strunreadmessages = null;
110     if ($countunreadtotal>0) { //if there are unread messages
111         $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
112     }
114     message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
116     if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
117         message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
118     } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
119         message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
120     } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
121         message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
122     } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
123         $courseidtoshow = intval(substr($viewing, 7));
125         if (!empty($courseidtoshow)
126             && array_key_exists($courseidtoshow, $coursecontexts)
127             && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129             message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
130         } else {
131             //shouldn't get here. User trying to access a course they're not in perhaps.
132             add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
133         }
134     }
136     // Only show the search button if we're viewing our own messages.
137     // Search isn't currently able to deal with user A wanting to search user B's messages.
138     if ($showactionlinks) {
139         echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
140         echo html_writer::start_tag('fieldset');
141         $managebuttonclass = 'visible';
142         if ($viewing == MESSAGE_VIEW_SEARCH) {
143             $managebuttonclass = 'hiddenelement';
144         }
145         $strmanagecontacts = get_string('search','message');
146         echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
147         echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
148         echo html_writer::end_tag('fieldset');
149         echo html_writer::end_tag('form');
150     }
152     echo html_writer::end_tag('div');
155 /**
156  * Print course participants. Called by message_print_contact_selector()
157  *
158  * @param object $context the course context
159  * @param int $courseid the course ID
160  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
161  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
162  * @param string $titletodisplay Optionally specify a title to display above the participants
163  * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
164  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
165  * @return void
166  */
167 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
168     global $DB, $USER, $PAGE, $OUTPUT;
170     if (empty($titletodisplay)) {
171         $titletodisplay = get_string('participants');
172     }
174     $countparticipants = count_enrolled_users($context);
176     list($esql, $params) = get_enrolled_sql($context);
177     $params['mcuserid'] = $USER->id;
178     $ufields = user_picture::fields('u');
180     $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
181               FROM {user} u
182               JOIN ($esql) je ON je.id = u.id
183               LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
184              WHERE u.deleted = 0";
186     $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
188     $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
189     echo $OUTPUT->render($pagingbar);
191     echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
193     echo html_writer::start_tag('tr');
194     echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
195     echo html_writer::end_tag('tr');
197     foreach ($participants as $participant) {
198         if ($participant->id != $USER->id) {
200             $iscontact = false;
201             $isblocked = false;
202             if ( $participant->contactlistid )  {
203                 if ($participant->blocked == 0) {
204                     // Is contact. Is not blocked.
205                     $iscontact = true;
206                     $isblocked = false;
207                 } else {
208                     // Is blocked.
209                     $iscontact = false;
210                     $isblocked = true;
211                 }
212             }
214             $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
215             message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
216         }
217     }
219     echo html_writer::end_tag('table');
222 /**
223  * Retrieve users blocked by $user1
224  *
225  * @param object $user1 the user whose messages are being viewed
226  * @param object $user2 the user $user1 is talking to. If they are being blocked
227  *                      they will have a variable called 'isblocked' added to their user object
228  * @return array the users blocked by $user1
229  */
230 function message_get_blocked_users($user1=null, $user2=null) {
231     global $DB, $USER;
233     if (empty($user1)) {
234         $user1 = $USER;
235     }
237     if (!empty($user2)) {
238         $user2->isblocked = false;
239     }
241     $blockedusers = array();
243     $userfields = user_picture::fields('u', array('lastaccess'));
244     $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
245                           FROM {message_contacts} mc
246                           JOIN {user} u ON u.id = mc.contactid
247                           LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
248                          WHERE mc.userid = :user1id2 AND mc.blocked = 1
249                       GROUP BY $userfields
250                       ORDER BY u.firstname ASC";
251     $rs =  $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
253     foreach($rs as $rd) {
254         $blockedusers[] = $rd;
256         if (!empty($user2) && $user2->id == $rd->id) {
257             $user2->isblocked = true;
258         }
259     }
260     $rs->close();
262     return $blockedusers;
265 /**
266  * Print users blocked by $user1. Called by message_print_contact_selector()
267  *
268  * @param array $blockedusers the users blocked by $user1
269  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
270  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
271  * @param string $titletodisplay Optionally specify a title to display above the participants
272  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
273  * @return void
274  */
275 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
276     global $DB, $USER;
278     $countblocked = count($blockedusers);
280     echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
282     if (!empty($titletodisplay)) {
283         echo html_writer::start_tag('tr');
284         echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
285         echo html_writer::end_tag('tr');
286     }
288     if ($countblocked) {
289         echo html_writer::start_tag('tr');
290         echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
291         echo html_writer::end_tag('tr');
293         $isuserblocked = true;
294         $isusercontact = false;
295         foreach ($blockedusers as $blockeduser) {
296             message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
297         }
298     }
300     echo html_writer::end_tag('table');
303 /**
304  * Retrieve $user1's contacts (online, offline and strangers)
305  *
306  * @param object $user1 the user whose messages are being viewed
307  * @param object $user2 the user $user1 is talking to. If they are a contact
308  *                      they will have a variable called 'iscontact' added to their user object
309  * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
310  */
311 function message_get_contacts($user1=null, $user2=null) {
312     global $DB, $CFG, $USER;
314     if (empty($user1)) {
315         $user1 = $USER;
316     }
318     if (!empty($user2)) {
319         $user2->iscontact = false;
320     }
322     $timetoshowusers = 300; //Seconds default
323     if (isset($CFG->block_online_users_timetosee)) {
324         $timetoshowusers = $CFG->block_online_users_timetosee * 60;
325     }
327     // time which a user is counting as being active since
328     $timefrom = time()-$timetoshowusers;
330     // people in our contactlist who are online
331     $onlinecontacts  = array();
332     // people in our contactlist who are offline
333     $offlinecontacts = array();
334     // people who are not in our contactlist but have sent us a message
335     $strangers       = array();
337     $userfields = user_picture::fields('u', array('lastaccess'));
339     // get all in our contactlist who are not blocked in our contact list
340     // and count messages we have waiting from each of them
341     $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
342                      FROM {message_contacts} mc
343                      JOIN {user} u ON u.id = mc.contactid
344                      LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
345                     WHERE mc.userid = ? AND mc.blocked = 0
346                  GROUP BY $userfields
347                  ORDER BY u.firstname ASC";
349     $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
350     foreach ($rs as $rd) {
351         if ($rd->lastaccess >= $timefrom) {
352             // they have been active recently, so are counted online
353             $onlinecontacts[] = $rd;
355         } else {
356             $offlinecontacts[] = $rd;
357         }
359         if (!empty($user2) && $user2->id == $rd->id) {
360             $user2->iscontact = true;
361         }
362     }
363     $rs->close();
365     // get messages from anyone who isn't in our contact list and count the number
366     // of messages we have from each of them
367     $strangersql = "SELECT $userfields, count(m.id) as messagecount
368                       FROM {message} m
369                       JOIN {user} u  ON u.id = m.useridfrom
370                       LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
371                      WHERE mc.id IS NULL AND m.useridto = ?
372                   GROUP BY $userfields
373                   ORDER BY u.firstname ASC";
375     $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
376     foreach ($rs as $rd) {
377         $strangers[] = $rd;
378     }
379     $rs->close();
381     return array($onlinecontacts, $offlinecontacts, $strangers);
384 /**
385  * Print $user1's contacts. Called by message_print_contact_selector()
386  *
387  * @param array $onlinecontacts $user1's contacts which are online
388  * @param array $offlinecontacts $user1's contacts which are offline
389  * @param array $strangers users which are not contacts but who have messaged $user1
390  * @param string $contactselecturl the url to send the user to when a contact's name is clicked
391  * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
392  *                         Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
393  * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
394  * @param string $titletodisplay Optionally specify a title to display above the participants
395  * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
396  * @return void
397  */
398 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
399     global $CFG, $PAGE, $OUTPUT;
401     $countonlinecontacts  = count($onlinecontacts);
402     $countofflinecontacts = count($offlinecontacts);
403     $countstrangers       = count($strangers);
404     $isuserblocked = null;
406     if ($countonlinecontacts + $countofflinecontacts == 0) {
407         echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
408     }
410     echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
412     if (!empty($titletodisplay)) {
413         message_print_heading($titletodisplay);
414     }
416     if($countonlinecontacts) {
417         // Print out list of online contacts.
419         if (empty($titletodisplay)) {
420             message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
421         }
423         $isuserblocked = false;
424         $isusercontact = true;
425         foreach ($onlinecontacts as $contact) {
426             if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
427                 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
428             }
429         }
430     }
432     if ($countofflinecontacts) {
433         // Print out list of offline contacts.
435         if (empty($titletodisplay)) {
436             message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
437         }
439         $isuserblocked = false;
440         $isusercontact = true;
441         foreach ($offlinecontacts as $contact) {
442             if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
443                 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
444             }
445         }
447     }
449     // Print out list of incoming contacts.
450     if ($countstrangers) {
451         message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
453         $isuserblocked = false;
454         $isusercontact = false;
455         foreach ($strangers as $stranger) {
456             if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
457                 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
458             }
459         }
460     }
462     echo html_writer::end_tag('table');
464     if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) {  // Extra help
465         echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
466     }
469 /**
470  * Print a select box allowing the user to choose to view new messages, course participants etc.
471  *
472  * Called by message_print_contact_selector()
473  * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
474  * @param array $courses array of course objects. The courses the user is enrolled in.
475  * @param array $coursecontexts array of course contexts. Keyed on course id.
476  * @param int $countunreadtotal how many unread messages does the user have?
477  * @param int $countblocked how many users has the current user blocked?
478  * @param stdClass $user1 The user whose messages we are viewing.
479  * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
480  * @return void
481  */
482 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
483     $options = array();
485     if ($countunreadtotal>0) { //if there are unread messages
486         $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
487     }
489     $str = get_string('contacts', 'message');
490     $options[MESSAGE_VIEW_CONTACTS] = $str;
492     $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
493     $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
495     if (!empty($courses)) {
496         $courses_options = array();
498         foreach($courses as $course) {
499             if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
500                 //Not using short_text() as we want the end of the course name. Not the beginning.
501                 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
502                 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
503                     $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
504                 } else {
505                     $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
506                 }
507             }
508         }
510         if (!empty($courses_options)) {
511             $options[] = array(get_string('courses') => $courses_options);
512         }
513     }
515     if ($countblocked>0) {
516         $str = get_string('blockedusers','message', $countblocked);
517         $options[MESSAGE_VIEW_BLOCKED] = $str;
518     }
520     echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
521     echo html_writer::start_tag('fieldset');
522     if ( !empty($user1) && !empty($user1->id) ) {
523         echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id));
524     }
525     echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
526     echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
527     echo html_writer::end_tag('fieldset');
528     echo html_writer::end_tag('form');
531 /**
532  * Load the course contexts for all of the users courses
533  *
534  * @param array $courses array of course objects. The courses the user is enrolled in.
535  * @return array of course contexts
536  */
537 function message_get_course_contexts($courses) {
538     $coursecontexts = array();
540     foreach($courses as $course) {
541         $coursecontexts[$course->id] = context_course::instance($course->id);
542     }
544     return $coursecontexts;
547 /**
548  * strip off action parameters like 'removecontact'
549  *
550  * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
551  * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
552  */
553 function message_remove_url_params($moodleurl) {
554     $newurl = new moodle_url($moodleurl);
555     $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
556     return $newurl->out();
559 /**
560  * Count the number of messages with a field having a specified value.
561  * if $field is empty then return count of the whole array
562  * if $field is non-existent then return 0
563  *
564  * @param array $messagearray array of message objects
565  * @param string $field the field to inspect on the message objects
566  * @param string $value the value to test the field against
567  */
568 function message_count_messages($messagearray, $field='', $value='') {
569     if (!is_array($messagearray)) return 0;
570     if ($field == '' or empty($messagearray)) return count($messagearray);
572     $count = 0;
573     foreach ($messagearray as $message) {
574         $count += ($message->$field == $value) ? 1 : 0;
575     }
576     return $count;
579 /**
580  * Returns the count of unread messages for user. Either from a specific user or from all users.
581  *
582  * @param object $user1 the first user. Defaults to $USER
583  * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
584  * @return int the count of $user1's unread messages
585  */
586 function message_count_unread_messages($user1=null, $user2=null) {
587     global $USER, $DB;
589     if (empty($user1)) {
590         $user1 = $USER;
591     }
593     if (!empty($user2)) {
594         return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
595             array($user1->id, $user2->id), "COUNT('id')");
596     } else {
597         return $DB->count_records_select('message', "useridto = ?",
598             array($user1->id), "COUNT('id')");
599     }
602 /**
603  * Count the number of users blocked by $user1
604  *
605  * @param object $user1 user object
606  * @return int the number of blocked users
607  */
608 function message_count_blocked_users($user1=null) {
609     global $USER, $DB;
611     if (empty($user1)) {
612         $user1 = $USER;
613     }
615     $sql = "SELECT count(mc.id)
616             FROM {message_contacts} mc
617             WHERE mc.userid = :userid AND mc.blocked = 1";
618     $params = array('userid' => $user1->id);
620     return $DB->count_records_sql($sql, $params);
623 /**
624  * Print the search form and search results if a search has been performed
625  *
626  * @param  boolean $advancedsearch show basic or advanced search form
627  * @param  object $user1 the current user
628  * @return boolean true if a search was performed
629  */
630 function message_print_search($advancedsearch = false, $user1=null) {
631     $frm = data_submitted();
633     $doingsearch = false;
634     if ($frm) {
635         if (confirm_sesskey()) {
636             $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
637         } else {
638             $frm = false;
639         }
640     }
642     if (!empty($frm->combinedsearch)) {
643         $combinedsearchstring = $frm->combinedsearch;
644     } else {
645         //$combinedsearchstring = get_string('searchcombined','message').'...';
646         $combinedsearchstring = '';
647     }
649     if ($doingsearch) {
650         if ($advancedsearch) {
652             $messagesearch = '';
653             if (!empty($frm->keywords)) {
654                 $messagesearch = $frm->keywords;
655             }
656             $personsearch = '';
657             if (!empty($frm->name)) {
658                 $personsearch = $frm->name;
659             }
660             include('search_advanced.html');
661         } else {
662             include('search.html');
663         }
665         $showicontext = false;
666         message_print_search_results($frm, $showicontext, $user1);
668         return true;
669     } else {
671         if ($advancedsearch) {
672             $personsearch = $messagesearch = '';
673             include('search_advanced.html');
674         } else {
675             include('search.html');
676         }
677         return false;
678     }
681 /**
682  * Get the users recent conversations meaning all the people they've recently
683  * sent or received a message from plus the most recent message sent to or received from each other user
684  *
685  * @param object $user the current user
686  * @param int $limitfrom can be used for paging
687  * @param int $limitto can be used for paging
688  * @return array
689  */
690 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
691     global $DB;
693     $userfields = user_picture::fields('u', array('lastaccess'));
694     //This query retrieves the last message received from and sent to each user
695     //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
696     //It then joins with some other tables to get some additional data we need
698     //message ID is used instead of timecreated as it should sort the same and will be much faster
700     //There is a separate query for read and unread queries as they are stored in different tables
701     //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
702     $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
703               FROM {message_read} mr
704               JOIN (
705                     SELECT messages.userid AS userid, MAX(messages.mid) AS mid
706                       FROM (
707                            SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
708                              FROM {message_read} mr1
709                             WHERE mr1.useridfrom = :userid1
710                                   AND mr1.notification = 0
711                          GROUP BY mr1.useridto
712                                   UNION
713                            SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
714                              FROM {message_read} mr2
715                             WHERE mr2.useridto = :userid2
716                                   AND mr2.notification = 0
717                          GROUP BY mr2.useridfrom
718                            ) messages
719                   GROUP BY messages.userid
720                    ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
721               JOIN {user} u ON u.id = messages2.userid
722          LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
723              WHERE u.deleted = '0'
724           ORDER BY mr.id DESC";
725     $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
726     $read =  $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
728     $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
729               FROM {message} m
730               JOIN (
731                     SELECT messages.userid AS userid, MAX(messages.mid) AS mid
732                       FROM (
733                            SELECT m1.useridto AS userid, MAX(m1.id) AS mid
734                              FROM {message} m1
735                             WHERE m1.useridfrom = :userid1
736                                   AND m1.notification = 0
737                          GROUP BY m1.useridto
738                                   UNION
739                            SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
740                              FROM {message} m2
741                             WHERE m2.useridto = :userid2
742                                   AND m2.notification = 0
743                          GROUP BY m2.useridfrom
744                            ) messages
745                   GROUP BY messages.userid
746                    ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
747               JOIN {user} u ON u.id = messages2.userid
748          LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
749              WHERE u.deleted = '0'
750              ORDER BY m.id DESC";
751     $unread =  $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
753     $conversations = array();
755     //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
756     //$conversation->id (the array key) is the other user's ID
757     $conversation_arrays = array($unread, $read);
758     foreach ($conversation_arrays as $conversation_array) {
759         foreach ($conversation_array as $conversation) {
760             if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
761                 $conversations[$conversation->id] = $conversation;
762             }
763         }
764     }
766     // Sort the conversations by $conversation->timecreated, newest to oldest
767     // There may be multiple conversations with the same timecreated
768     // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
769     $result = collatorlib::asort_objects_by_property($conversations, 'timecreated', collatorlib::SORT_NUMERIC);
770     $conversations = array_reverse($conversations);
772     return $conversations;
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($user1 = null, $showicontext = false, $showactionlinks = true) {
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($user1)) {
812         $user1 = $USER;
813     }
815     $conversations = message_get_recent_conversations($user1);
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?user1={$user1->id}&user2={$conversation->id}");
820         $conversation->contexturlname = get_string('thisconversation', 'message');
821     }
823     $showotheruser = true;
824     message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
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, true);
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  * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
858  * @return void
859  */
860 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
861     global $OUTPUT;
862     static $dateformat;
864     if (empty($dateformat)) {
865         $dateformat = get_string('strftimedatetimeshort');
866     }
868     echo html_writer::start_tag('div', array('class' => 'messagerecent'));
869     foreach ($messages as $message) {
870         echo html_writer::start_tag('div', array('class' => 'singlemessage'));
872         if ($showotheruser) {
873             $strcontact = $strblock = $strhistory = null;
875             if ($showactionlinks) {
876                 if ( $message->contactlistid )  {
877                     if ($message->blocked == 0) { // The other user isn't blocked.
878                         $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
879                         $strblock   = message_contact_link($message->id, 'block', true, null, $showicontext);
880                     } else { // The other user is blocked.
881                         $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
882                         $strblock   = message_contact_link($message->id, 'unblock', true, null, $showicontext);
883                     }
884                 } else {
885                     $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
886                     $strblock   = message_contact_link($message->id, 'block', true, null, $showicontext);
887                 }
889                 //should we show just the icon or icon and text?
890                 $histicontext = 'icon';
891                 if ($showicontext) {
892                     $histicontext = 'both';
893                 }
894                 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
895             }
896             echo html_writer::start_tag('span', array('class' => 'otheruser'));
898             echo html_writer::start_tag('span', array('class' => 'pix'));
899             echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
900             echo html_writer::end_tag('span');
902             echo html_writer::start_tag('span', array('class' => 'contact'));
904             $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
905             $action = null;
906             echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
908             echo html_writer::end_tag('span');//end contact
910             if ($showactionlinks) {
911                 echo $strcontact.$strblock.$strhistory;
912             }
913             echo html_writer::end_tag('span');//end otheruser
914         }
915         $messagetoprint = null;
916         if (!empty($message->smallmessage)) {
917             $messagetoprint = $message->smallmessage;
918         } else {
919             $messagetoprint = $message->fullmessage;
920         }
922         echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
923         echo html_writer::tag('span', format_text($messagetoprint, $forcetexttohtml?FORMAT_MOODLE:FORMAT_HTML), array('class' => 'themessage'));
924         echo message_format_contexturl($message);
925         echo html_writer::end_tag('div');//end singlemessage
926     }
927     echo html_writer::end_tag('div');//end messagerecent
930 /**
931  * Add the selected user as a contact for the current user
932  *
933  * @param int $contactid the ID of the user to add as a contact
934  * @param int $blocked 1 if you wish to block the contact
935  * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
936  *                  Otherwise returns the result of update_record() or insert_record()
937  */
938 function message_add_contact($contactid, $blocked=0) {
939     global $USER, $DB;
941     if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
942         return false;
943     }
945     if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
946     // A record already exists. We may be changing blocking status.
948         if ($contact->blocked !== $blocked) {
949             // Blocking status has been changed.
950             $contact->blocked = $blocked;
951             return $DB->update_record('message_contacts', $contact);
952         } else {
953             // No change to blocking status.
954             return true;
955         }
957     } else {
958         // New contact record.
959         $contact = new stdClass();
960         $contact->userid = $USER->id;
961         $contact->contactid = $contactid;
962         $contact->blocked = $blocked;
963         return $DB->insert_record('message_contacts', $contact, false);
964     }
967 /**
968  * remove a contact
969  *
970  * @param int $contactid the user ID of the contact to remove
971  * @return bool returns the result of delete_records()
972  */
973 function message_remove_contact($contactid) {
974     global $USER, $DB;
975     return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
978 /**
979  * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
980  *
981  * @param int $contactid the user ID of the contact to unblock
982  * @return bool returns the result of delete_records()
983  */
984 function message_unblock_contact($contactid) {
985     global $USER, $DB;
986     return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
989 /**
990  * block a user
991  *
992  * @param int $contactid the user ID of the user to block
993  */
994 function message_block_contact($contactid) {
995     return message_add_contact($contactid, 1);
998 /**
999  * Load a user's contact record
1000  *
1001  * @param int $contactid the user ID of the user whose contact record you want
1002  * @return array message contacts
1003  */
1004 function message_get_contact($contactid) {
1005     global $USER, $DB;
1006     return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1009 /**
1010  * Print the results of a message search
1011  *
1012  * @param mixed $frm submitted form data
1013  * @param bool $showicontext show text next to action icons?
1014  * @param object $currentuser the current user
1015  * @return void
1016  */
1017 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1018     global $USER, $DB, $OUTPUT;
1020     if (empty($currentuser)) {
1021         $currentuser = $USER;
1022     }
1024     echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1026     $personsearch = false;
1027     $personsearchstring = null;
1028     if (!empty($frm->personsubmit) and !empty($frm->name)) {
1029         $personsearch = true;
1030         $personsearchstring = $frm->name;
1031     } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1032         $personsearch = true;
1033         $personsearchstring = $frm->combinedsearch;
1034     }
1036     // Search for person.
1037     if ($personsearch) {
1038         if (optional_param('mycourses', 0, PARAM_BOOL)) {
1039             $users = array();
1040             $mycourses = enrol_get_my_courses('id');
1041             $mycoursesids = array();
1042             foreach ($mycourses as $mycourse) {
1043                 $mycoursesids[] = $mycourse->id;
1044             }
1045             $susers = message_search_users($mycoursesids, $personsearchstring);
1046             foreach ($susers as $suser) {
1047                 $users[$suser->id] = $suser;
1048             }
1049         } else {
1050             $users = message_search_users(SITEID, $personsearchstring);
1051         }
1053         if (!empty($users)) {
1054             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1055             echo get_string('userssearchresults', 'message', count($users));
1056             echo html_writer::end_tag('p');
1058             echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1059             foreach ($users as $user) {
1061                 if ( $user->contactlistid )  {
1062                     if ($user->blocked == 0) { // User is not blocked.
1063                         $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1064                         $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
1065                     } else { // blocked
1066                         $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1067                         $strblock   = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1068                     }
1069                 } else {
1070                     $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1071                     $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
1072                 }
1074                 // Should we show just the icon or icon and text?
1075                 $histicontext = 'icon';
1076                 if ($showicontext) {
1077                     $histicontext = 'both';
1078                 }
1079                 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1081                 echo html_writer::start_tag('tr');
1083                 echo html_writer::start_tag('td', array('class' => 'pix'));
1084                 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1085                 echo html_writer::end_tag('td');
1087                 echo html_writer::start_tag('td',array('class' => 'contact'));
1088                 $action = null;
1089                 $link = new moodle_url("/message/index.php?id=$user->id");
1090                 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1091                 echo html_writer::end_tag('td');
1093                 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1094                 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1095                 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1097                 echo html_writer::end_tag('tr');
1098             }
1099             echo html_writer::end_tag('table');
1101         } else {
1102             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1103             echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1104             echo html_writer::end_tag('p');
1105         }
1106     }
1108     // search messages for keywords
1109     $messagesearch = false;
1110     $messagesearchstring = null;
1111     if (!empty($frm->keywords)) {
1112         $messagesearch = true;
1113         $messagesearchstring = clean_text(trim($frm->keywords));
1114     } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1115         $messagesearch = true;
1116         $messagesearchstring = clean_text(trim($frm->combinedsearch));
1117     }
1119     if ($messagesearch) {
1120         if ($messagesearchstring) {
1121             $keywords = explode(' ', $messagesearchstring);
1122         } else {
1123             $keywords = array();
1124         }
1125         $tome     = false;
1126         $fromme   = false;
1127         $courseid = 'none';
1129         if (empty($frm->keywordsoption)) {
1130             $frm->keywordsoption = 'allmine';
1131         }
1133         switch ($frm->keywordsoption) {
1134             case 'tome':
1135                 $tome   = true;
1136                 break;
1137             case 'fromme':
1138                 $fromme = true;
1139                 break;
1140             case 'allmine':
1141                 $tome   = true;
1142                 $fromme = true;
1143                 break;
1144             case 'allusers':
1145                 $courseid = SITEID;
1146                 break;
1147             case 'courseusers':
1148                 $courseid = $frm->courseid;
1149                 break;
1150             default:
1151                 $tome   = true;
1152                 $fromme = true;
1153         }
1155         if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1157             // Get a list of contacts.
1158             if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1159                 $contacts = array();
1160             }
1162             // Print heading with number of results.
1163             echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1164             $countresults = count($messages);
1165             if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1166                 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1167             } else {
1168                 echo get_string('keywordssearchresults', 'message', $countresults);
1169             }
1170             echo html_writer::end_tag('p');
1172             // Print table headings.
1173             echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1175             $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1176             $headertdend   = html_writer::end_tag('td');
1177             echo html_writer::start_tag('tr');
1178             echo $headertdstart.get_string('from').$headertdend;
1179             echo $headertdstart.get_string('to').$headertdend;
1180             echo $headertdstart.get_string('message', 'message').$headertdend;
1181             echo $headertdstart.get_string('timesent', 'message').$headertdend;
1182             echo html_writer::end_tag('tr');
1184             $blockedcount = 0;
1185             $dateformat = get_string('strftimedatetimeshort');
1186             $strcontext = get_string('context', 'message');
1187             foreach ($messages as $message) {
1189                 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1190                 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1191                       ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1192                       ( isset($contacts[$message->useridto]  ) and ($contacts[$message->useridto]->blocked   == 1))
1193                                                 )
1194                    ) {
1195                     $blockedcount ++;
1196                     continue;
1197                 }
1199                 // Load user-to record.
1200                 if ($message->useridto !== $USER->id) {
1201                     $userto = $DB->get_record('user', array('id' => $message->useridto));
1202                     $tocontact = (array_key_exists($message->useridto, $contacts) and
1203                                     ($contacts[$message->useridto]->blocked == 0) );
1204                     $toblocked = (array_key_exists($message->useridto, $contacts) and
1205                                     ($contacts[$message->useridto]->blocked == 1) );
1206                 } else {
1207                     $userto = false;
1208                     $tocontact = false;
1209                     $toblocked = false;
1210                 }
1212                 // Load user-from record.
1213                 if ($message->useridfrom !== $USER->id) {
1214                     $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1215                     $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1216                                     ($contacts[$message->useridfrom]->blocked == 0) );
1217                     $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1218                                     ($contacts[$message->useridfrom]->blocked == 1) );
1219                 } else {
1220                     $userfrom = false;
1221                     $fromcontact = false;
1222                     $fromblocked = false;
1223                 }
1225                 // Find date string for this message.
1226                 $date = usergetdate($message->timecreated);
1227                 $datestring = $date['year'].$date['mon'].$date['mday'];
1229                 // Print out message row.
1230                 echo html_writer::start_tag('tr', array('valign' => 'top'));
1232                 echo html_writer::start_tag('td', array('class' => 'contact'));
1233                 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1234                 echo html_writer::end_tag('td');
1236                 echo html_writer::start_tag('td', array('class' => 'contact'));
1237                 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1238                 echo html_writer::end_tag('td');
1240                 echo html_writer::start_tag('td', array('class' => 'summary'));
1241                 echo message_get_fragment($message->smallmessage, $keywords);
1242                 echo html_writer::start_tag('div', array('class' => 'link'));
1244                 // If the user clicks the context link display message sender on the left.
1245                 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1246                 $leftsideuserid = $rightsideuserid = null;
1247                 if ($currentuser->id == $message->useridto) {
1248                     $leftsideuserid = $message->useridto;
1249                     $rightsideuserid = $message->useridfrom;
1250                 } else {
1251                     $leftsideuserid = $message->useridfrom;
1252                     $rightsideuserid = $message->useridto;
1253                 }
1254                 message_history_link($leftsideuserid, $rightsideuserid, false,
1255                                      $messagesearchstring, 'm'.$message->id, $strcontext);
1256                 echo html_writer::end_tag('div');
1257                 echo html_writer::end_tag('td');
1259                 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1261                 echo html_writer::end_tag('tr');
1262             }
1265             if ($blockedcount > 0) {
1266                 echo html_writer::start_tag('tr');
1267                 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1268                 echo html_writer::end_tag('tr');
1269             }
1270             echo html_writer::end_tag('table');
1272         } else {
1273             echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1274         }
1275     }
1277     if (!$personsearch && !$messagesearch) {
1278         //they didn't enter any search terms
1279         echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1280     }
1282     echo html_writer::end_tag('div');
1285 /**
1286  * Print information on a user. Used when printing search results.
1287  *
1288  * @param object/bool $user the user to display or false if you just want $USER
1289  * @param bool $iscontact is the user being displayed a contact?
1290  * @param bool $isblocked is the user being displayed blocked?
1291  * @param bool $includeicontext include text next to the action icons?
1292  * @return void
1293  */
1294 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1295     global $USER, $OUTPUT;
1297     if ($user === false) {
1298         echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1299     } else {
1300         echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1302         $link = new moodle_url("/message/index.php?id=$user->id");
1303         echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1304                 get_string('sendmessageto', 'message', fullname($user))));
1306         $return = false;
1307         $script = null;
1308         if ($iscontact) {
1309             message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1310         } else {
1311             message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1312         }
1314         if ($isblocked) {
1315             message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1316         } else {
1317             message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1318         }
1319     }
1322 /**
1323  * Print a message contact link
1324  *
1325  * @param int $userid the ID of the user to apply to action to
1326  * @param string $linktype can be add, remove, block or unblock
1327  * @param bool $return if true return the link as a string. If false echo the link.
1328  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1329  * @param bool $text include text next to the icons?
1330  * @param bool $icon include a graphical icon?
1331  * @return string  if $return is true otherwise bool
1332  */
1333 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1334     global $OUTPUT, $PAGE;
1336     //hold onto the strings as we're probably creating a bunch of links
1337     static $str;
1339     if (empty($script)) {
1340         //strip off previous action params like 'removecontact'
1341         $script = message_remove_url_params($PAGE->url);
1342     }
1344     if (empty($str->blockcontact)) {
1345        $str = new stdClass();
1346        $str->blockcontact   =  get_string('blockcontact', 'message');
1347        $str->unblockcontact =  get_string('unblockcontact', 'message');
1348        $str->removecontact  =  get_string('removecontact', 'message');
1349        $str->addcontact     =  get_string('addcontact', 'message');
1350     }
1352     $command = $linktype.'contact';
1353     $string  = $str->{$command};
1355     $safealttext = s($string);
1357     $safestring = '';
1358     if (!empty($text)) {
1359         $safestring = $safealttext;
1360     }
1362     $img = '';
1363     if ($icon) {
1364         $iconpath = null;
1365         switch ($linktype) {
1366             case 'block':
1367                 $iconpath = 't/block';
1368                 break;
1369             case 'unblock':
1370                 $iconpath = 't/unblock';
1371                 break;
1372             case 'remove':
1373                 $iconpath = 't/removecontact';
1374                 break;
1375             case 'add':
1376             default:
1377                 $iconpath = 't/addcontact';
1378         }
1380         $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1381     }
1383     $output = '<span class="'.$linktype.'contact">'.
1384               '<a href="'.$script.'&amp;'.$command.'='.$userid.
1385               '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1386               $img.
1387               $safestring.'</a></span>';
1389     if ($return) {
1390         return $output;
1391     } else {
1392         echo $output;
1393         return true;
1394     }
1397 /**
1398  * echo or return a link to take the user to the full message history between themselves and another user
1399  *
1400  * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1401  * @param int $userid2 the ID of the other user
1402  * @param bool $return true to return the link as a string. False to echo the link.
1403  * @param string $keywords any keywords to highlight in the message history
1404  * @param string $position anchor name to jump to within the message history
1405  * @param string $linktext optionally specify the link text
1406  * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1407  */
1408 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1409     global $OUTPUT;
1410     static $strmessagehistory;
1412     if (empty($strmessagehistory)) {
1413         $strmessagehistory = get_string('messagehistory', 'message');
1414     }
1416     if ($position) {
1417         $position = "#$position";
1418     }
1419     if ($keywords) {
1420         $keywords = "&search=".urlencode($keywords);
1421     }
1423     if ($linktext == 'icon') {  // Icon only
1424         $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1425     } else if ($linktext == 'both') {  // Icon and standard name
1426         $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1427         $fulllink .= '&nbsp;'.$strmessagehistory;
1428     } else if ($linktext) {    // Custom name
1429         $fulllink = $linktext;
1430     } else {                   // Standard name only
1431         $fulllink = $strmessagehistory;
1432     }
1434     $popupoptions = array(
1435             'height' => 500,
1436             'width' => 500,
1437             'menubar' => false,
1438             'location' => false,
1439             'status' => true,
1440             'scrollbars' => true,
1441             'resizable' => true);
1443     $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1444     $action = null;
1445     $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1447     $str = '<span class="history">'.$str.'</span>';
1449     if ($return) {
1450         return $str;
1451     } else {
1452         echo $str;
1453         return true;
1454     }
1458 /**
1459  * Search through course users.
1460  *
1461  * If $courseids contains the site course then this function searches
1462  * through all undeleted and confirmed users.
1463  *
1464  * @param int|array $courseids Course ID or array of course IDs.
1465  * @param string $searchtext the text to search for.
1466  * @param string $sort the column name to order by.
1467  * @param string $exceptions comma separated list of user IDs to exclude
1468  * @return array An array of {@link $USER} records.
1469  */
1470 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1471     global $CFG, $USER, $DB;
1473     // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1474     if (!$courseids) {
1475         $courseids = array(SITEID);
1476     }
1478     // Allow an integer to be passed.
1479     if (!is_array($courseids)) {
1480         $courseids = array($courseids);
1481     }
1483     $fullname = $DB->sql_fullname();
1485     if (!empty($exceptions)) {
1486         $except = ' AND u.id NOT IN ('. $exceptions .') ';
1487     } else {
1488         $except = '';
1489     }
1491     if (!empty($sort)) {
1492         $order = ' ORDER BY '. $sort;
1493     } else {
1494         $order = '';
1495     }
1497     $ufields = user_picture::fields('u');
1499     if (in_array(SITEID, $courseids)) {
1500         // Search on site level.
1501         $params = array($USER->id, "%$searchtext%");
1502         return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1503                                        FROM {user} u
1504                                        LEFT JOIN {message_contacts} mc
1505                                             ON mc.contactid = u.id AND mc.userid = ?
1506                                       WHERE u.deleted = '0' AND u.confirmed = '1'
1507                                             AND (".$DB->sql_like($fullname, '?', false).")
1508                                             $except
1509                                      $order", $params);
1510     } else {
1511         // Search in courses.
1512         $params = array($USER->id, "%$searchtext%");
1514         // Getting the context IDs or each course.
1515         $contextids = array();
1516         foreach ($courseids as $courseid) {
1517             $context = context_course::instance($courseid);
1518             $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1519         }
1520         list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids));
1521         $params = array_merge($params, $contextparams);
1523         // Everyone who has a role assignment in this course or higher.
1524         // TODO: add enabled enrolment join here (skodak)
1525         $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1526                                          FROM {user} u
1527                                          JOIN {role_assignments} ra ON ra.userid = u.id
1528                                          LEFT JOIN {message_contacts} mc
1529                                               ON mc.contactid = u.id AND mc.userid = ?
1530                                         WHERE u.deleted = '0' AND u.confirmed = '1'
1531                                               AND (".$DB->sql_like($fullname, '?', false).")
1532                                               AND ra.contextid $contextwhere
1533                                               $except
1534                                        $order", $params);
1536         return $users;
1537     }
1540 /**
1541  * Search a user's messages
1542  *
1543  * Returns a list of posts found using an array of search terms
1544  * eg   word  +word -word
1545  *
1546  * @param array $searchterms an array of search terms (strings)
1547  * @param bool $fromme include messages from the user?
1548  * @param bool $tome include messages to the user?
1549  * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1550  * @param int $userid the user ID of the current user
1551  * @return mixed An array of messages or false if no matching messages were found
1552  */
1553 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1554     global $CFG, $USER, $DB;
1556     // If user is searching all messages check they are allowed to before doing anything else.
1557     if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1558         print_error('accessdenied','admin');
1559     }
1561     // If no userid sent then assume current user.
1562     if ($userid == 0) $userid = $USER->id;
1564     // Some differences in SQL syntax.
1565     if ($DB->sql_regex_supported()) {
1566         $REGEXP    = $DB->sql_regex(true);
1567         $NOTREGEXP = $DB->sql_regex(false);
1568     }
1570     $searchcond = array();
1571     $params = array();
1572     $i = 0;
1574     // Preprocess search terms to check whether we have at least 1 eligible search term.
1575     // If we do we can drop words around it like 'a'.
1576     $dropshortwords = false;
1577     foreach ($searchterms as $searchterm) {
1578         if (strlen($searchterm) >= 2) {
1579             $dropshortwords = true;
1580         }
1581     }
1583     foreach ($searchterms as $searchterm) {
1584         $i++;
1586         $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1588         if ($dropshortwords && strlen($searchterm) < 2) {
1589             continue;
1590         }
1591         // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1592         if (!$DB->sql_regex_supported()) {
1593             if (substr($searchterm, 0, 1) == '-') {
1594                 $NOT = true;
1595             }
1596             $searchterm = trim($searchterm, '+-');
1597         }
1599         if (substr($searchterm,0,1) == "+") {
1600             $searchterm = substr($searchterm,1);
1601             $searchterm = preg_quote($searchterm, '|');
1602             $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1603             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1605         } else if (substr($searchterm,0,1) == "-") {
1606             $searchterm = substr($searchterm,1);
1607             $searchterm = preg_quote($searchterm, '|');
1608             $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1609             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1611         } else {
1612             $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1613             $params['ss'.$i] = "%$searchterm%";
1614         }
1615     }
1617     if (empty($searchcond)) {
1618         $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1619         $params['ss1'] = "%";
1620     } else {
1621         $searchcond = implode(" AND ", $searchcond);
1622     }
1624     // There are several possibilities
1625     // 1. courseid = SITEID : The admin is searching messages by all users
1626     // 2. courseid = ??     : A teacher is searching messages by users in
1627     //                        one of their courses - currently disabled
1628     // 3. courseid = none   : User is searching their own messages;
1629     //    a.  Messages from user
1630     //    b.  Messages to user
1631     //    c.  Messages to and from user
1633     if ($courseid == SITEID) { // Admin is searching all messages.
1634         $m_read   = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1635                                             FROM {message_read} m
1636                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1637         $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1638                                             FROM {message} m
1639                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1641     } else if ($courseid !== 'none') {
1642         // This has not been implemented due to security concerns.
1643         $m_read   = array();
1644         $m_unread = array();
1646     } else {
1648         if ($fromme and $tome) {
1649             $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1650             $params['userid1'] = $userid;
1651             $params['userid2'] = $userid;
1653         } else if ($fromme) {
1654             $searchcond .= " AND m.useridfrom=:userid";
1655             $params['userid'] = $userid;
1657         } else if ($tome) {
1658             $searchcond .= " AND m.useridto=:userid";
1659             $params['userid'] = $userid;
1660         }
1662         $m_read   = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1663                                             FROM {message_read} m
1664                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1665         $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1666                                             FROM {message} m
1667                                            WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1669     }
1671     /// The keys may be duplicated in $m_read and $m_unread so we can't
1672     /// do a simple concatenation
1673     $messages = array();
1674     foreach ($m_read as $m) {
1675         $messages[] = $m;
1676     }
1677     foreach ($m_unread as $m) {
1678         $messages[] = $m;
1679     }
1681     return (empty($messages)) ? false : $messages;
1684 /**
1685  * Given a message object that we already know has a long message
1686  * this function truncates the message nicely to the first
1687  * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1688  *
1689  * @param string $message the message
1690  * @param int $minlength the minimum length to trim the message to
1691  * @return string the shortened message
1692  */
1693 function message_shorten_message($message, $minlength = 0) {
1694     $i = 0;
1695     $tag = false;
1696     $length = strlen($message);
1697     $count = 0;
1698     $stopzone = false;
1699     $truncate = 0;
1700     if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1703     for ($i=0; $i<$length; $i++) {
1704         $char = $message[$i];
1706         switch ($char) {
1707             case "<":
1708                 $tag = true;
1709                 break;
1710             case ">":
1711                 $tag = false;
1712                 break;
1713             default:
1714                 if (!$tag) {
1715                     if ($stopzone) {
1716                         if ($char == '.' or $char == ' ') {
1717                             $truncate = $i+1;
1718                             break 2;
1719                         }
1720                     }
1721                     $count++;
1722                 }
1723                 break;
1724         }
1725         if (!$stopzone) {
1726             if ($count > $minlength) {
1727                 $stopzone = true;
1728             }
1729         }
1730     }
1732     if (!$truncate) {
1733         $truncate = $i;
1734     }
1736     return substr($message, 0, $truncate);
1740 /**
1741  * Given a string and an array of keywords, this function looks
1742  * for the first keyword in the string, and then chops out a
1743  * small section from the text that shows that word in context.
1744  *
1745  * @param string $message the text to search
1746  * @param array $keywords array of keywords to find
1747  */
1748 function message_get_fragment($message, $keywords) {
1750     $fullsize = 160;
1751     $halfsize = (int)($fullsize/2);
1753     $message = strip_tags($message);
1755     foreach ($keywords as $keyword) {  // Just get the first one
1756         if ($keyword !== '') {
1757             break;
1758         }
1759     }
1760     if (empty($keyword)) {   // None found, so just return start of message
1761         return message_shorten_message($message, 30);
1762     }
1764     $leadin = $leadout = '';
1766 /// Find the start of the fragment
1767     $start = 0;
1768     $length = strlen($message);
1770     $pos = strpos($message, $keyword);
1771     if ($pos > $halfsize) {
1772         $start = $pos - $halfsize;
1773         $leadin = '...';
1774     }
1775 /// Find the end of the fragment
1776     $end = $start + $fullsize;
1777     if ($end > $length) {
1778         $end = $length;
1779     } else {
1780         $leadout = '...';
1781     }
1783 /// Pull out the fragment and format it
1785     $fragment = substr($message, $start, $end - $start);
1786     $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1787     return $fragment;
1790 /**
1791  * Retrieve the messages between two users
1792  *
1793  * @param object $user1 the current user
1794  * @param object $user2 the other user
1795  * @param int $limitnum the maximum number of messages to retrieve
1796  * @param bool $viewingnewmessages are we currently viewing new messages?
1797  */
1798 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1799     global $DB, $CFG;
1801     $messages = array();
1803     //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1804     //desc to get the last $limitnum messages then flip the order in php
1805     $sort = 'asc';
1806     if ($limitnum>0) {
1807         $sort = 'desc';
1808     }
1810     $notificationswhere = null;
1811     //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1812     if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1813         $notificationswhere = 'AND notification=0';
1814     }
1816     //prevent notifications of your own actions appearing in your own message history
1817     $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1819     if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1820                                                     (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1821                                                     array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1822                                                     "timecreated $sort", '*', 0, $limitnum)) {
1823         foreach ($messages_read as $message) {
1824             $messages[] = $message;
1825         }
1826     }
1827     if ($messages_new =  $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1828                                                     (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1829                                                     array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1830                                                     "timecreated $sort", '*', 0, $limitnum)) {
1831         foreach ($messages_new as $message) {
1832             $messages[] = $message;
1833         }
1834     }
1836     $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);
1838     //if we only want the last $limitnum messages
1839     $messagecount = count($messages);
1840     if ($limitnum > 0 && $messagecount > $limitnum) {
1841         $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1842     }
1844     return $messages;
1847 /**
1848  * Print the message history between two users
1849  *
1850  * @param object $user1 the current user
1851  * @param object $user2 the other user
1852  * @param string $search search terms to highlight
1853  * @param int $messagelimit maximum number of messages to return
1854  * @param string $messagehistorylink the html for the message history link or false
1855  * @param bool $viewingnewmessages are we currently viewing new messages?
1856  */
1857 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1858     global $CFG, $OUTPUT;
1860     echo $OUTPUT->box_start('center');
1861     echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1862     echo html_writer::start_tag('tr');
1864     echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1865     echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1866     echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1867     echo html_writer::end_tag('td');
1869     echo html_writer::start_tag('td', array('align' => 'center'));
1870     echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1871     echo html_writer::end_tag('td');
1873     echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1874     echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1875     echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1877     if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
1879         $script = null;
1880         $text = true;
1881         $icon = false;
1883         $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1884         $strblock   = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1885         $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1887         echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1888     }
1890     echo html_writer::end_tag('td');
1891     echo html_writer::end_tag('tr');
1892     echo html_writer::end_tag('table');
1893     echo $OUTPUT->box_end();
1895     if (!empty($messagehistorylink)) {
1896         echo $messagehistorylink;
1897     }
1899     /// Get all the messages and print them
1900     if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1901         $tablecontents = '';
1903         $current = new stdClass();
1904         $current->mday = '';
1905         $current->month = '';
1906         $current->year = '';
1907         $messagedate = get_string('strftimetime');
1908         $blockdate   = get_string('strftimedaydate');
1909         foreach ($messages as $message) {
1910             if ($message->notification) {
1911                 $notificationclass = ' notification';
1912             } else {
1913                 $notificationclass = null;
1914             }
1915             $date = usergetdate($message->timecreated);
1916             if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1917                 $current->mday = $date['mday'];
1918                 $current->month = $date['month'];
1919                 $current->year = $date['year'];
1921                 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1922                 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1924                 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1925             }
1927             $formatted_message = $side = null;
1928             if ($message->useridfrom == $user1->id) {
1929                 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1930                 $side = 'left';
1931             } else {
1932                 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1933                 $side = 'right';
1934             }
1935             $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1936         }
1938         echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1939     } else {
1940         echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1941     }
1944 /**
1945  * Format a message for display in the message history
1946  *
1947  * @param object $message the message object
1948  * @param string $format optional date format
1949  * @param string $keywords keywords to highlight
1950  * @param string $class CSS class to apply to the div around the message
1951  * @return string the formatted message
1952  */
1953 function message_format_message($message, $format='', $keywords='', $class='other') {
1955     static $dateformat;
1957     //if we haven't previously set the date format or they've supplied a new one
1958     if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1959         if ($format) {
1960             $dateformat = $format;
1961         } else {
1962             $dateformat = get_string('strftimedatetimeshort');
1963         }
1964     }
1965     $time = userdate($message->timecreated, $dateformat);
1966     $options = new stdClass();
1967     $options->para = false;
1969     //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1970     if (!empty($message->smallmessage)) {
1971         $messagetext = $message->smallmessage;
1972     } else {
1973         $messagetext = $message->fullmessage;
1974     }
1975     if ($message->fullmessageformat == FORMAT_HTML) {
1976         //dont escape html tags by calling s() if html format or they will display in the UI
1977         $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1978     } else {
1979         $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1980     }
1982     $messagetext .= message_format_contexturl($message);
1984     if ($keywords) {
1985         $messagetext = highlight($keywords, $messagetext);
1986     }
1988     return <<<TEMPLATE
1989 <div class='message $class'>
1990     <a name="m'.{$message->id}.'"></a>
1991     <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
1992 </div>
1993 TEMPLATE;
1996 /**
1997  * Format a the context url and context url name of a message for display
1998  *
1999  * @param object $message the message object
2000  * @return string the formatted string
2001  */
2002 function message_format_contexturl($message) {
2003     $s = null;
2005     if (!empty($message->contexturl)) {
2006         $displaytext = null;
2007         if (!empty($message->contexturlname)) {
2008             $displaytext= $message->contexturlname;
2009         } else {
2010             $displaytext= $message->contexturl;
2011         }
2012         $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2013             $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2014         $s .= html_writer::end_tag('div');
2015     }
2017     return $s;
2020 /**
2021  * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2022  *
2023  * @param object $userfrom the message sender
2024  * @param object $userto the message recipient
2025  * @param string $message the message
2026  * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2027  * @return int|false the ID of the new message or false
2028  */
2029 function message_post_message($userfrom, $userto, $message, $format) {
2030     global $SITE, $CFG, $USER;
2032     $eventdata = new stdClass();
2033     $eventdata->component        = 'moodle';
2034     $eventdata->name             = 'instantmessage';
2035     $eventdata->userfrom         = $userfrom;
2036     $eventdata->userto           = $userto;
2038     //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2039     $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2041     if ($format == FORMAT_HTML) {
2042         $eventdata->fullmessagehtml  = $message;
2043         //some message processors may revert to sending plain text even if html is supplied
2044         //so we keep both plain and html versions if we're intending to send html
2045         $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2046     } else {
2047         $eventdata->fullmessage      = $message;
2048         $eventdata->fullmessagehtml  = '';
2049     }
2051     $eventdata->fullmessageformat = $format;
2052     $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.
2054     $s = new stdClass();
2055     $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2056     $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2058     $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2059     if (!empty($eventdata->fullmessage)) {
2060         $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2061     }
2062     if (!empty($eventdata->fullmessagehtml)) {
2063         $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2064     }
2066     $eventdata->timecreated     = time();
2067     return message_send($eventdata);
2070 /**
2071  * Print a row of contactlist displaying user picture, messages waiting and
2072  * block links etc
2073  *
2074  * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2075  * @param bool $incontactlist is the user a contact of ours?
2076  * @param bool $isblocked is the user blocked?
2077  * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2078  * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2079  * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2080  * @return void
2081  */
2082 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2083     global $OUTPUT, $USER;
2084     $fullname  = fullname($contact);
2085     $fullnamelink  = $fullname;
2087     $linkclass = '';
2088     if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2089         $linkclass = 'messageselecteduser';
2090     }
2092     // Are there any unread messages for this contact?
2093     if ($contact->messagecount > 0 ){
2094         $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2095     }
2097     $strcontact = $strblock = $strhistory = null;
2099     if ($showactionlinks) {
2100         $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2101         $strblock   = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2102         $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2103     }
2105     echo html_writer::start_tag('tr');
2106     echo html_writer::start_tag('td', array('class' => 'pix'));
2107     echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2108     echo html_writer::end_tag('td');
2110     echo html_writer::start_tag('td', array('class' => 'contact'));
2112     $popupoptions = array(
2113             'height' => MESSAGE_DISCUSSION_HEIGHT,
2114             'width' => MESSAGE_DISCUSSION_WIDTH,
2115             'menubar' => false,
2116             'location' => false,
2117             'status' => true,
2118             'scrollbars' => true,
2119             'resizable' => true);
2121     $link = $action = null;
2122     if (!empty($selectcontacturl)) {
2123         $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2124     } else {
2125         //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2126         $link = new moodle_url("/message/index.php?id=$contact->id");
2127         $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2128     }
2129     echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2131     echo html_writer::end_tag('td');
2133     echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2135     echo html_writer::end_tag('tr');
2138 /**
2139  * Constructs the add/remove contact link to display next to other users
2140  *
2141  * @param bool $incontactlist is the user a contact
2142  * @param bool $isblocked is the user blocked
2143  * @param stdClass $contact contact object
2144  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2145  * @param bool $text include text next to the icons?
2146  * @param bool $icon include a graphical icon?
2147  * @return string
2148  */
2149 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2150     $strcontact = '';
2152     if($incontactlist){
2153         $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2154     } else if ($isblocked) {
2155         $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2156     } else{
2157         $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2158     }
2160     return $strcontact;
2163 /**
2164  * Constructs the block contact link to display next to other users
2165  *
2166  * @param bool $incontactlist is the user a contact?
2167  * @param bool $isblocked is the user blocked?
2168  * @param stdClass $contact contact object
2169  * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2170  * @param bool $text include text next to the icons?
2171  * @param bool $icon include a graphical icon?
2172  * @return string
2173  */
2174 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2175     $strblock   = '';
2177     //commented out to allow the user to block a contact without having to remove them first
2178     /*if ($incontactlist) {
2179         //$strblock = '';
2180     } else*/
2181     if ($isblocked) {
2182         $strblock   = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2183     } else{
2184         $strblock   = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2185     }
2187     return $strblock;
2190 /**
2191  * Moves messages from a particular user from the message table (unread messages) to message_read
2192  * This is typically only used when a user is deleted
2193  *
2194  * @param object $userid User id
2195  * @return boolean success
2196  */
2197 function message_move_userfrom_unread2read($userid) {
2198     global $DB;
2200     // move all unread messages from message table to message_read
2201     if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2202         foreach ($messages as $message) {
2203             message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2204         }
2205     }
2206     return true;
2209 /**
2210  * marks ALL messages being sent from $fromuserid to $touserid as read
2211  *
2212  * @param int $touserid the id of the message recipient
2213  * @param int $fromuserid the id of the message sender
2214  * @return void
2215  */
2216 function message_mark_messages_read($touserid, $fromuserid){
2217     global $DB;
2219     $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2220     $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2222     foreach ($messages as $message) {
2223         message_mark_message_read($message, time());
2224     }
2226     $messages->close();
2229 /**
2230  * Mark a single message as read
2231  *
2232  * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2233  * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2234  * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2235  * @return int the ID of the message in the message_read table
2236  */
2237 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2238     global $DB;
2240     $message->timeread = $timeread;
2242     $messageid = $message->id;
2243     unset($message->id);//unset because it will get a new id on insert into message_read
2245     //If any processors have pending actions abort them
2246     if (!$messageworkingempty) {
2247         $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2248     }
2249     $messagereadid = $DB->insert_record('message_read', $message);
2250     $DB->delete_records('message', array('id' => $messageid));
2251     return $messagereadid;
2254 /**
2255  * A helper function that prints a formatted heading
2256  *
2257  * @param string $title the heading to display
2258  * @param int $colspan
2259  * @return void
2260  */
2261 function message_print_heading($title, $colspan=3) {
2262     echo html_writer::start_tag('tr');
2263     echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2264     echo html_writer::end_tag('tr');
2267 /**
2268  * Get all message processors, validate corresponding plugin existance and
2269  * system configuration
2270  *
2271  * @param bool $ready only return ready-to-use processors
2272  * @return mixed $processors array of objects containing information on message processors
2273  */
2274 function get_message_processors($ready = false) {
2275     global $DB, $CFG;
2277     static $processors;
2279     if (empty($processors)) {
2280         // Get all processors, ensure the name column is the first so it will be the array key
2281         $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2282         foreach ($processors as &$processor){
2283             $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2284             if (is_readable($processorfile)) {
2285                 include_once($processorfile);
2286                 $processclass = 'message_output_' . $processor->name;
2287                 if (class_exists($processclass)) {
2288                     $pclass = new $processclass();
2289                     $processor->object = $pclass;
2290                     $processor->configured = 0;
2291                     if ($pclass->is_system_configured()) {
2292                         $processor->configured = 1;
2293                     }
2294                     $processor->hassettings = 0;
2295                     if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2296                         $processor->hassettings = 1;
2297                     }
2298                     $processor->available = 1;
2299                 } else {
2300                     print_error('errorcallingprocessor', 'message');
2301                 }
2302             } else {
2303                 $processor->available = 0;
2304             }
2305         }
2306     }
2307     if ($ready) {
2308         // Filter out enabled and system_configured processors
2309         $readyprocessors = $processors;
2310         foreach ($readyprocessors as $readyprocessor) {
2311             if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2312                 unset($readyprocessors[$readyprocessor->name]);
2313             }
2314         }
2315         return $readyprocessors;
2316     }
2318     return $processors;
2321 /**
2322  * Get all message providers, validate their plugin existance and
2323  * system configuration
2324  *
2325  * @return mixed $processors array of objects containing information on message processors
2326  */
2327 function get_message_providers() {
2328     global $CFG, $DB;
2329     require_once($CFG->libdir . '/pluginlib.php');
2330     $pluginman = plugin_manager::instance();
2332     $providers = $DB->get_records('message_providers', null, 'name');
2334     // Remove all the providers whose plugins are disabled or don't exist
2335     foreach ($providers as $providerid => $provider) {
2336         $plugin = $pluginman->get_plugin_info($provider->component);
2337         if ($plugin) {
2338             if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2339                 unset($providers[$providerid]);   // Plugins does not exist
2340                 continue;
2341             }
2342             if ($plugin->is_enabled() === false) {
2343                 unset($providers[$providerid]);   // Plugin disabled
2344                 continue;
2345             }
2346         }
2347     }
2348     return $providers;
2351 /**
2352  * Get an instance of the message_output class for one of the output plugins.
2353  * @param string $type the message output type. E.g. 'email' or 'jabber'.
2354  * @return message_output message_output the requested class.
2355  */
2356 function get_message_processor($type) {
2357     global $CFG;
2359     // Note, we cannot use the get_message_processors function here, becaues this
2360     // code is called during install after installing each messaging plugin, and
2361     // get_message_processors caches the list of installed plugins.
2363     $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2364     if (!is_readable($processorfile)) {
2365         throw new coding_exception('Unknown message processor type ' . $type);
2366     }
2368     include_once($processorfile);
2370     $processclass = 'message_output_' . $type;
2371     if (!class_exists($processclass)) {
2372         throw new coding_exception('Message processor ' . $type .
2373                 ' does not define the right class');
2374     }
2376     return new $processclass();
2379 /**
2380  * Get messaging outputs default (site) preferences
2381  *
2382  * @return object $processors object containing information on message processors
2383  */
2384 function get_message_output_default_preferences() {
2385     return get_config('message');
2388 /**
2389  * Translate message default settings from binary value to the array of string
2390  * representing the settings to be stored. Also validate the provided value and
2391  * use default if it is malformed.
2392  *
2393  * @param  int    $plugindefault Default setting suggested by plugin
2394  * @param  string $processorname The name of processor
2395  * @return array  $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2396  */
2397 function translate_message_default_setting($plugindefault, $processorname) {
2398     // Preset translation arrays
2399     $permittedvalues = array(
2400         0x04 => 'disallowed',
2401         0x08 => 'permitted',
2402         0x0c => 'forced',
2403     );
2405     $loggedinstatusvalues = array(
2406         0x00 => null, // use null if loggedin/loggedoff is not defined
2407         0x01 => 'loggedin',
2408         0x02 => 'loggedoff',
2409     );
2411     // define the default setting
2412     $processor = get_message_processor($processorname);
2413     $default = $processor->get_default_messaging_settings();
2415     // Validate the value. It should not exceed the maximum size
2416     if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2417         debugging(get_string('errortranslatingdefault', 'message'));
2418         $plugindefault = $default;
2419     }
2420     // Use plugin default setting of 'permitted' is 0
2421     if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2422         $plugindefault = $default;
2423     }
2425     $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2426     $loggedin = $loggedoff = null;
2428     if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2429         $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2430         $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2431     }
2433     return array($permitted, $loggedin, $loggedoff);
2436 /**
2437  * Return a list of page types
2438  * @param string $pagetype current page type
2439  * @param stdClass $parentcontext Block's parent context
2440  * @param stdClass $currentcontext Current context of block
2441  */
2442 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2443     return array('messages-*'=>get_string('page-message-x', 'message'));
2446 /**
2447  * Is $USER one of the supplied users?
2448  *
2449  * $user2 will be null if viewing a user's recent conversations
2450  *
2451  * @param stdClass the first user
2452  * @param stdClass the second user or null
2453  * @return bool True if the current user is one of either $user1 or $user2
2454  */
2455 function message_current_user_is_involved($user1, $user2) {
2456     global $USER;
2458     if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2459         throw new coding_exception('Invalid user object detected. Missing id.');
2460     }
2462     if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2463         return false;
2464     }
2465     return true;