MDL-9628 More category collapse updates
[moodle-pu.git] / message / lib.php
blobdd94482721a59cf0540dc577bb974abf10e70b66
1 <?php
2 /// library functions for messaging
5 define ('MESSAGE_SHORTLENGTH', 300);
6 define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
8 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
9 $CFG->message_contacts_refresh = 60;
11 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
12 $CFG->message_chat_refresh = 5;
14 if (!isset($CFG->message_offline_time)) {
15 $CFG->message_offline_time = 300;
19 function message_print_contacts() {
20 global $USER, $CFG;
22 $timetoshowusers = 300; //Seconds default
23 if (isset($CFG->block_online_users_timetosee)) {
24 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
26 $timefrom = time()-$timetoshowusers;
29 /// get lists of contacts and unread messages
30 $onlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
31 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
32 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess>=$timefrom
33 AND mc.blocked='0'
34 ORDER BY u.firstname ASC");
36 $offlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
37 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
38 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess<$timefrom
39 AND mc.blocked='0'
40 ORDER BY u.firstname ASC");
42 $unreadmessages = get_records_sql("SELECT m.id, m.useridfrom, u.firstname, u.lastname, u.picture
43 FROM {$CFG->prefix}user u, {$CFG->prefix}message m
44 WHERE m.useridto='$USER->id' AND u.id=m.useridfrom");
46 $blockedcontacts = get_records_select('message_contacts', "userid='$USER->id' AND blocked='1'", '', 'contactid, id');
49 $countonlinecontacts = (is_array($onlinecontacts)) ? count($onlinecontacts) : 0;
50 $countofflinecontacts = (is_array($offlinecontacts)) ? count($offlinecontacts) : 0;
52 /// Cycle through messages and extract those that are from unknown contacts
53 /// We can take advantage of the keys for $onlinecontacts and $offlinecontacts
54 /// which are set to the userid and therefore we just need to see if the key
55 /// exists in either of those arrays
56 /// We can also discard any messages from users in our blocked contact list
57 $unknownmessages = array();
58 if (!empty($unreadmessages)) {
59 /// make sure we have valid arrays to test against - they may be boolean false
60 if (empty($onlinecontacts)) $onlinecontacts = array();
61 if (empty($offlinecontacts)) $offlinecontacts = array();
62 if (empty($blockedcontacts)) $blockedcontacts = array();
63 foreach ($unreadmessages as $unreadmessage) {
64 if (array_key_exists($unreadmessage->useridfrom, $onlinecontacts) or
65 array_key_exists($unreadmessage->useridfrom, $offlinecontacts) or
66 array_key_exists($unreadmessage->useridfrom, $blockedcontacts) ) {
67 continue;
69 if (!isset($unknownmessages[$unreadmessage->useridfrom])) {
70 $message = $unreadmessage;
71 $message->count = 1;
72 $unknownmessages[$unreadmessage->useridfrom] = $message;
73 } else {
74 $unknownmessages[$unreadmessage->useridfrom]->count++;
79 if ($countonlinecontacts + $countofflinecontacts == 0) {
80 echo '<div class="heading">';
81 print_string('contactlistempty', 'message');
82 echo '</div>';
83 echo '<div class="note">';
84 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
85 echo '</div>';
88 if(!empty($onlinecontacts) || !empty($offlinecontacts) || !empty($unknownmessages)) {
90 echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0" border="0">';
92 if(!empty($onlinecontacts)) {
93 /// print out list of online contacts
95 echo '<tr><td colspan="3" class="heading">';
96 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
97 echo '</td></tr>';
99 if (!empty($onlinecontacts)) {
100 foreach ($onlinecontacts as $contact) {
101 if ($contact->blocked == 1) continue;
102 $fullname = fullname($contact);
103 $fullnamelink = $fullname;
104 /// are there any unread messages for this contact?
105 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
106 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
108 /// link to remove from contact list
109 $strcontact = message_contact_link($contact->id, 'remove', true);
110 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
112 echo '<tr><td class="pix">';
113 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
114 echo '</td>';
115 echo '<td class="contact">';
116 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
117 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
118 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
119 echo '</td>';
120 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
121 echo '</tr>';
124 echo '<tr><td colspan="3">&nbsp;</td></tr>';
127 if (!empty($offlinecontacts)) {
128 /// print out list of offline contacts
130 echo '<tr><td colspan="3" class="heading">';
131 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
132 echo '</td></tr>';
134 foreach ($offlinecontacts as $contact) {
135 if ($contact->blocked == 1) continue;
136 $fullname = fullname($contact);
137 $fullnamelink = $fullname;
138 /// are there any unread messages for this contact?
139 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
140 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
142 /// link to remove from contact list
143 $strcontact = message_contact_link($contact->id, 'remove', true);
144 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
146 echo '<tr><td class="pix">';
147 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
148 echo '</td>';
149 echo '<td class="contact">';
150 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
151 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
152 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
153 echo '</td>';
154 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
155 echo '</tr>';
157 echo '<tr><td colspan="3">&nbsp;</td></tr>';
161 /// print out list of incoming contacts
162 if (!empty($unknownmessages)) {
163 echo '<tr><td colspan="3" class="heading">';
164 echo get_string('incomingcontacts', 'message', count($unknownmessages));
165 echo '</td></tr>';
167 foreach ($unknownmessages as $messageuser) {
168 $fullname = fullname($messageuser);
169 $fullnamelink = $fullname;
170 if ($messageuser->count) {
171 $fullnamelink = '<strong>'.$fullnamelink.' ('.$messageuser->count.')</strong>';
173 /// link to add to contact list
175 $strcontact = message_contact_link($messageuser->useridfrom, 'add', true);
176 $strblock = message_contact_link($messageuser->useridfrom, 'block', true);
177 $strhistory = message_history_link($messageuser->useridfrom, 0, true, '', '', 'icon');
179 echo '<tr><td class="pix">';
180 print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, true, 'userwindow');
181 echo '</td>';
182 echo '<td class="contact">';
183 link_to_popup_window("/message/discussion.php?id=$messageuser->useridfrom", "message_$messageuser->useridfrom",
184 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
185 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
186 echo '</td>';
187 echo '<td class="link">&nbsp;'.$strcontact.'&nbsp;'.$strblock.'&nbsp;'.$strhistory.'</td>';
188 echo '</tr>';
192 echo '</table>';
194 if (!empty($unknownmessages) && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
195 echo '<div class="note">(';
196 print_string('addsomecontactsincoming', 'message');
197 echo ')</div>';
203 echo '<br />';
205 $autorefresh = '<p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
206 $autorefresh = addslashes_js($autorefresh); // js escaping
208 // gracefully degrade JS autorefresh
209 echo '<script type="text/javascript">
210 //<![CDATA[
211 document.write("'.$autorefresh.'")
212 //]]>
213 </script>';
214 echo '<noscript><div align="center">';
215 echo print_single_button('index.php', false, get_string('refresh'));
216 echo '</div></noscript>';
222 /// $messagearray is an array of objects
223 /// $field is a valid property of object
224 /// $value is the value $field should equal to be counted
225 /// if $field is empty then return count of the whole array
226 /// if $field is non-existent then return 0;
227 function message_count_messages($messagearray, $field='', $value='') {
228 if (!is_array($messagearray)) return 0;
229 if ($field == '' or empty($messagearray)) return count($messagearray);
231 $count = 0;
232 foreach ($messagearray as $message) {
233 $count += ($message->$field == $value) ? 1 : 0;
235 return $count;
239 function message_print_search() {
240 global $USER;
242 if ($frm = data_submitted()) {
244 message_print_search_results($frm);
246 } else {
248 /// unfinished buggy code disabled in search.html anyway
249 // find all courses this use has readallmessages capabilities in
250 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
251 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
252 $cs = '<select name="courseselect">';
253 foreach ($teachers as $tcourse) {
254 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
256 $cs .= '</select>';
259 include('search.html');
263 function message_print_settings() {
264 global $USER;
266 if ($frm = data_submitted()) {
268 $pref = array();
269 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
270 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
271 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
272 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
273 $pref['message_noframesjs'] = (isset($frm->noframesjs)) ? '1' : '0';
274 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
275 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
276 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
277 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
279 set_user_preferences($pref);
281 redirect('index.php', get_string('settingssaved', 'message'), 1);
284 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
285 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
286 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
287 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
288 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ? 'checked="checked"' : '';
289 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
290 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
291 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
292 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
293 FORMAT_HTML => get_string('formathtml')),
294 'emailformat',
295 get_user_preferences('message_emailformat', FORMAT_PLAIN),
296 false, '', '0', true );
298 include('settings.html');
303 function message_add_contact($contactid, $blocked=0) {
304 global $USER;
306 if (!record_exists('user', 'id', $contactid)) { // invalid userid
307 return false;
310 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
311 /// record already exists - we may be changing blocking status
313 if ($contact->blocked !== $blocked) {
314 /// change to blocking status
315 $contact->blocked = $blocked;
316 return update_record('message_contacts', $contact);
317 } else {
318 /// no changes to blocking status
319 return true;
322 } else {
323 /// new contact record
324 unset($contact);
325 $contact->userid = $USER->id;
326 $contact->contactid = $contactid;
327 $contact->blocked = $blocked;
328 return insert_record('message_contacts', $contact, false);
332 function message_remove_contact($contactid) {
333 global $USER;
334 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
337 function message_unblock_contact($contactid) {
338 global $USER;
339 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
342 function message_block_contact($contactid) {
343 return message_add_contact($contactid, 1);
346 function message_get_contact($contactid) {
347 global $USER;
348 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
353 function message_print_search_results($frm) {
354 global $USER, $CFG;
356 echo '<div align="center">';
358 /// search for person
359 if (!empty($frm->personsubmit) and !empty($frm->name)) {
361 if (optional_param('mycourses', 0, PARAM_BOOL)) {
362 $users = array();
363 $mycourses = get_my_courses($USER->id);
364 foreach ($mycourses as $mycourse) {
365 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
366 foreach ($susers as $suser) $users[$suser->id] = $suser;
369 } else {
370 $users = message_search_users(SITEID, $frm->name);
373 if (!empty($users)) {
374 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
375 echo '<table class="message_users">';
376 foreach ($users as $user) {
378 if (($contact = message_get_contact($user->id)) !== false) {
379 if ($contact->blocked == 0) { /// not blocked
380 $strcontact = message_contact_link($user->id, 'remove', true);
381 $strblock = message_contact_link($user->id, 'block', true);
382 } else { // blocked
383 $strcontact = message_contact_link($user->id, 'add', true);
384 $strblock = message_contact_link($user->id, 'unblock', true);
386 } else {
387 $strcontact = message_contact_link($user->id, 'add', true);
388 $strblock = message_contact_link($user->id, 'block', true);
390 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
392 echo '<tr><td class="pix">';
393 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
394 echo '</td>';
395 echo '<td class="contact">';
396 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
397 500, 500, get_string('sendmessageto', 'message', fullname($user)),
398 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
399 echo '</td>';
401 echo '<td class="link">'.$strcontact.'</td>';
402 echo '<td class="link">'.$strblock.'</td>';
403 echo '<td class="link">'.$strhistory.'</td>';
404 echo '</tr>';
406 echo '</table>';
408 } else {
409 notify(get_string('nosearchresults', 'message'));
413 /// search messages for keywords
414 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
415 $keywordstring = clean_text(trim($frm->keywords));
416 $keywords = explode(' ', $keywordstring);
417 $tome = false;
418 $fromme = false;
419 $courseid = 'none';
421 switch ($frm->keywordsoption) {
422 case 'tome':
423 $tome = true;
424 break;
425 case 'fromme':
426 $fromme = true;
427 break;
428 case 'allmine':
429 $tome = true;
430 $fromme = true;
431 break;
432 case 'allusers':
433 $courseid = SITEID;
434 break;
435 case 'courseusers':
436 $courseid = $frm->courseid;
437 break;
438 default:
439 $tome = true;
440 $fromme = true;
443 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
445 /// get a list of contacts
446 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
447 $contacts = array();
450 /// print heading with number of results
451 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
453 /// print table headings
454 echo '<table class="searchresults" cellspacing="0">';
455 echo '<tr>';
456 echo '<td><strong>'.get_string('from').'</strong></td>';
457 echo '<td><strong>'.get_string('to').'</strong></td>';
458 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
459 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
460 echo "</tr>\n";
462 $blockedcount = 0;
463 $dateformat = get_string('strftimedatetime');
464 $strcontext = get_string('context', 'message');
465 foreach ($messages as $message) {
467 /// ignore messages to and from blocked users unless $frm->includeblocked is set
468 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
469 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
470 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
473 $blockedcount ++;
474 continue;
477 /// load up user to record
478 if ($message->useridto !== $USER->id) {
479 $userto = get_record('user', 'id', $message->useridto);
480 $tocontact = (array_key_exists($message->useridto, $contacts) and
481 ($contacts[$message->useridto]->blocked == 0) );
482 $toblocked = (array_key_exists($message->useridto, $contacts) and
483 ($contacts[$message->useridto]->blocked == 1) );
484 } else {
485 $userto = false;
486 $tocontact = false;
487 $toblocked = false;
490 /// load up user from record
491 if ($message->useridfrom !== $USER->id) {
492 $userfrom = get_record('user', 'id', $message->useridfrom);
493 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
494 ($contacts[$message->useridfrom]->blocked == 0) );
495 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
496 ($contacts[$message->useridfrom]->blocked == 1) );
497 } else {
498 $userfrom = false;
499 $fromcontact = false;
500 $fromblocked = false;
503 /// find date string for this message
504 $date = usergetdate($message->timecreated);
505 $datestring = $date['year'].$date['mon'].$date['mday'];
507 /// print out message row
508 echo '<tr valign="top">';
509 echo '<td class="contact">';
510 message_print_user($userfrom, $fromcontact, $fromblocked);
511 echo '</td>';
512 echo '<td class="contact">';
513 message_print_user($userto, $tocontact, $toblocked);
514 echo '</td>';
515 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
516 echo '<br /><div class="link">';
517 message_history_link($message->useridto, $message->useridfrom, false,
518 $keywordstring, 'm'.$message->id, $strcontext);
519 echo '</div>';
520 echo '</td>';
521 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
522 echo "</tr>\n";
526 if ($blockedcount > 0) {
527 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
529 echo '</table>';
531 } else {
532 notify(get_string('nosearchresults', 'message'));
536 /// what the ????, probably an empty search string, duh!
537 } else {
538 notify(get_string('emptysearchstring', 'message'));
541 echo '<br />';
542 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
544 echo '</div>';
548 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
549 global $USER;
550 if ($user === false) {
551 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
552 } else {
553 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
554 echo '&nbsp;';
555 if ($iscontact) {
556 message_contact_link($user->id, 'remove');
557 } else {
558 message_contact_link($user->id, 'add');
560 echo '&nbsp;';
561 if ($isblocked) {
562 message_contact_link($user->id, 'unblock');
563 } else {
564 message_contact_link($user->id, 'block');
566 echo '<br />';
567 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
568 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
569 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
574 /// linktype can be: add, remove, block, unblock
575 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
576 global $USER, $CFG;
578 static $str;
580 if (empty($str->blockcontact)) {
581 $str->blockcontact = get_string('blockcontact', 'message');
582 $str->unblockcontact = get_string('unblockcontact', 'message');
583 $str->removecontact = get_string('removecontact', 'message');
584 $str->addcontact = get_string('addcontact', 'message');
587 $command = $linktype.'contact';
588 $string = $str->{$command};
589 $alttext = $text ? '' : $string;
590 $text = $text ? '&nbsp;'.$string : '';
592 switch ($linktype) {
593 case 'block':
594 $icon = '/t/go.gif';
595 break;
596 case 'unblock':
597 $icon = '/t/stop.gif';
598 break;
599 case 'remove':
600 $icon = '/t/user.gif';
601 break;
602 case 'add':
603 default:
604 $icon = '/t/usernot.gif';
607 $output = '<span class="'.$linktype.'">'.
608 '<a href="'.$script.'&amp;'.$command.'='.$userid.
609 '&amp;sesskey='.sesskey().'" title="'.s($string).'">'.
610 '<img src="'.$CFG->pixpath.$icon.'" class="iconsmall" alt="'.s($alttext).'" />'.
611 $text.'</a></span>';
613 if ($return) {
614 return $output;
615 } else {
616 echo $output;
617 return true;
621 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
622 global $USER, $CFG;
624 static $strmessagehistory;
626 if (empty($strmessagehistory)) {
627 $strmessagehistory = get_string('messagehistory', 'message');
630 if (!$userid2) {
631 $userid2 = $USER->id;
633 if ($position) {
634 $position = "#$position";
636 if ($keywords) {
637 $keywords = "&search=".urlencode($keywords);
640 if ($linktext == 'icon') { // Icon only
641 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="'.$strmessagehistory.'" />';
642 } else if ($linktext == 'both') { // Icon and standard name
643 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="" />';
644 $fulllink .= '&nbsp;'.$strmessagehistory;
645 } else if ($linktext) { // Custom name
646 $fulllink = $linktext;
647 } else { // Standard name only
648 $fulllink = $strmessagehistory;
651 $str = link_to_popup_window("/message/history.php?user1=$userid1&amp;user2=$userid2$keywords$position",
652 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
653 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
655 $str = '<span class="history">'.$str.'</span>';
657 if ($returnstr) {
658 return $str;
659 } else {
660 echo $str;
661 return true;
667 * Search through course users
669 * If $coursid specifies the site course then this function searches
670 * through all undeleted and confirmed users
672 * @uses $CFG
673 * @uses SITEID
674 * @param int $courseid The course in question.
675 * @param string $searchtext ?
676 * @param string $sort ?
677 * @param string $exceptions ?
678 * @return array An array of {@link $USER} records.
679 * @todo Finish documenting this function
681 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
682 global $CFG;
684 $fullname = sql_fullname();
685 $LIKE = sql_ilike();
687 if (!empty($exceptions)) {
688 $except = ' AND u.id NOT IN ('. $exceptions .') ';
689 } else {
690 $except = '';
693 if (!empty($sort)) {
694 $order = ' ORDER BY '. $sort;
695 } else {
696 $order = '';
699 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
700 $fields = 'u.id, u.firstname, u.lastname, u.picture';
702 if (!$courseid or $courseid == SITEID) {
703 return get_records_sql("SELECT $fields
704 FROM {$CFG->prefix}user u
705 WHERE $select
706 AND ($fullname $LIKE '%$searchtext%')
707 $except $order");
708 } else {
710 $context = get_context_instance(CONTEXT_COURSE, $courseid);
711 $contextlists = get_related_contexts_string($context);
713 // everyone who has a role assignement in this course or higher
714 $users = get_records_sql("SELECT $fields
715 FROM {$CFG->prefix}user u,
716 {$CFG->prefix}role_assignments ra
717 WHERE $select
718 AND ra.contextid $contextlists
719 AND u.id = ra.userid
720 AND ($fullname $LIKE '%$searchtext%')
721 $except $order");
723 return $users;
730 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
731 /// Returns a list of posts found using an array of search terms
732 /// eg word +word -word
735 global $CFG, $USER;
737 /// If no userid sent then assume current user
738 if ($userid == 0) $userid = $USER->id;
740 /// Some differences in SQL syntax
741 $LIKE = sql_ilike();
742 $NOTLIKE = 'NOT ' . $LIKE;
743 if ($CFG->dbfamily == "postgres") {
744 $REGEXP = "~*";
745 $NOTREGEXP = "!~*";
746 } else {
747 $REGEXP = "REGEXP";
748 $NOTREGEXP = "NOT REGEXP";
751 $messagesearch = "";
753 foreach ($searchterms as $searchterm) {
754 if (strlen($searchterm) < 2) {
755 continue;
757 /// Under Oracle and MSSQL, trim the + and - operators and perform
758 /// simpler LIKE search
759 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
760 $searchterm = trim($searchterm, '+-');
763 if ($messagesearch) {
764 $messagesearch .= " AND ";
767 if (substr($searchterm,0,1) == "+") {
768 $searchterm = substr($searchterm,1);
769 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
770 } else if (substr($searchterm,0,1) == "-") {
771 $searchterm = substr($searchterm,1);
772 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
773 } else {
774 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
778 if ($messagesearch == '') { // if only 1 letter words searched
779 return false;
782 $messagesearch = "($messagesearch) ";
785 /// There are several possibilities
786 /// 1. courseid = SITEID : The admin is searching messages by all users
787 /// 2. courseid = ?? : A teacher is searching messages by users in
788 /// one of their courses - currently disabled
789 /// 3. courseid = none : User is searching their own messages;
790 /// a. Messages from user
791 /// b. Messages to user
792 /// c. Messages to and from user
794 if ($courseid == SITEID) { /// admin is searching all messages
795 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
796 FROM {$CFG->prefix}message_read m
797 WHERE $messagesearch");
798 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
799 FROM {$CFG->prefix}message m
800 WHERE $messagesearch");
802 if ($m_read === false) $m_read = array();
803 if ($m_unread === false) $m_unread = array();
805 } elseif ($courseid !== 'none') {
806 /// This has not been implemented due to security concerns
808 } else {
810 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
811 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
812 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
814 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
815 FROM {$CFG->prefix}message_read m
816 WHERE $messagesearch");
817 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
818 FROM {$CFG->prefix}message m
819 WHERE $messagesearch");
821 if ($m_read === false) $m_read = array();
822 if ($m_unread === false) $m_unread = array();
826 /// The keys may be duplicated in $m_read and $m_unread so we can't
827 /// do a simple concatenation
828 $message = array();
829 foreach ($m_read as $m) $messages[] = $m;
830 foreach ($m_unread as $m) $messages[] = $m;
833 return (empty($messages)) ? false : $messages;
838 /// Borrowed with changes from mod/forum/lib.php
839 function message_shorten_message($message, $minlength=0) {
840 // Given a post object that we already know has a long message
841 // this function truncates the message nicely to the first
842 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
844 $i = 0;
845 $tag = false;
846 $length = strlen($message);
847 $count = 0;
848 $stopzone = false;
849 $truncate = 0;
850 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
853 for ($i=0; $i<$length; $i++) {
854 $char = $message[$i];
856 switch ($char) {
857 case "<":
858 $tag = true;
859 break;
860 case ">":
861 $tag = false;
862 break;
863 default:
864 if (!$tag) {
865 if ($stopzone) {
866 if ($char == '.' or $char == ' ') {
867 $truncate = $i+1;
868 break 2;
871 $count++;
873 break;
875 if (!$stopzone) {
876 if ($count > $minlength) {
877 $stopzone = true;
882 if (!$truncate) {
883 $truncate = $i;
886 return substr($message, 0, $truncate);
891 * Given a string and an array of keywords, this function looks
892 * for the first keyword in the string, and then chops out a
893 * small section from the text that shows that word in context.
895 function message_get_fragment($message, $keywords) {
897 $fullsize = 120;
898 $halfsize = (int)($fullsize/2);
900 $message = strip_tags($message);
902 foreach ($keywords as $keyword) { // Just get the first one
903 if ($keyword !== '') {
904 break;
907 if (empty($keyword)) { // None found, so just return start of message
908 return message_shorten_message($message, 30);
911 $leadin = $leadout = '';
913 /// Find the start of the fragment
914 $start = 0;
915 $length = strlen($message);
917 $pos = strpos($message, $keyword);
918 if ($pos > $halfsize) {
919 $start = $pos - $halfsize;
920 $leadin = '...';
922 /// Find the end of the fragment
923 $end = $start + $fullsize;
924 if ($end > $length) {
925 $end = $length;
926 } else {
927 $leadout = '...';
930 /// Pull out the fragment and format it
932 $fragment = substr($message, $start, $end - $start);
933 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
934 return $fragment;
938 function message_get_history($user1, $user2) {
939 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
940 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
941 'timecreated');
942 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
943 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
944 'timecreated')) {
945 foreach ($messages_new as $message) {
946 $messages[] = $message;
949 return $messages;
952 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
954 static $dateformat;
956 if (empty($dateformat)) {
957 if ($format) {
958 $dateformat = $format;
959 } else {
960 $format = get_string('strftimedaytime');
963 $time = userdate($message->timecreated, $dateformat);
964 $options->para = false;
965 $messagetext = format_text($message->message, $message->format, $options);
966 if ($keywords) {
967 $messagetext = highlight($keywords, $messagetext);
969 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a><span class="author">'.s(fullname($user)).'</span> <span class="time">['.$time.']</span>: <span class="content">'.$messagetext.'</span></div>';
973 * Inserts a message into the database, but also forwards it
974 * via other means if appropriate.
976 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
978 global $CFG, $SITE;
980 /// Save the new message in the database
982 $savemessage = NULL;
983 $savemessage->useridfrom = $userfrom->id;
984 $savemessage->useridto = $userto->id;
985 $savemessage->message = $message;
986 $savemessage->format = $format;
987 $savemessage->timecreated = time();
988 $savemessage->messagetype = 'direct';
990 if (!$savemessage->id = insert_record('message', $savemessage)) {
991 return false;
994 /// Check to see if anything else needs to be done with it
996 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
998 if (!isset($preference->message_emailmessages) || $preference->message_emailmessages) { // Receiver wants mail forwarding
999 if (!isset($preference->message_emailtimenosee)) {
1000 $preference->message_emailtimenosee = 10;
1002 if (!isset($preference->message_emailformat)) {
1003 $preference->message_emailformat = FORMAT_HTML;
1005 if ((time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
1007 $message = stripslashes_safe($message);
1008 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
1010 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
1012 $messagetext = format_text_email($message, $format).
1013 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1015 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
1016 $messagehtml = format_text($message, $format);
1017 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1018 } else {
1019 $messagehtml = NULL;
1022 if (!empty($preference->message_emailaddress)) {
1023 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1025 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
1026 debugging('Mail was sent', DEBUG_NORMAL);
1027 echo "mail was sent";
1028 sleep(3);
1032 return $savemessage->id;
1037 * Returns a list of all user ids who have used messaging in the site
1038 * This was the simple way to code the SQL ... is it going to blow up
1039 * on large datasets?
1041 function message_get_participants() {
1043 global $CFG;
1045 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1046 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1047 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1048 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1049 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1050 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");