MDL-12296:
[moodle-linuxchix.git] / message / lib.php
blob5c8c4452aebb406d02f54b0c92ce627ad244e0e1
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">';
117 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
118 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
119 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
121 echo '</td>';
122 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
123 echo '</tr>';
126 echo '<tr><td colspan="3">&nbsp;</td></tr>';
129 if (!empty($offlinecontacts)) {
130 /// print out list of offline contacts
132 echo '<tr><td colspan="3" class="heading">';
133 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
134 echo '</td></tr>';
136 foreach ($offlinecontacts as $contact) {
137 if ($contact->blocked == 1) continue;
138 $fullname = fullname($contact);
139 $fullnamelink = $fullname;
140 /// are there any unread messages for this contact?
141 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
142 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
144 /// link to remove from contact list
145 $strcontact = message_contact_link($contact->id, 'remove', true);
146 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
148 echo '<tr><td class="pix">';
149 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
150 echo '</td>';
151 echo '<td class="contact">';
152 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
153 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
154 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
156 echo '</td>';
157 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
158 echo '</tr>';
160 echo '<tr><td colspan="3">&nbsp;</td></tr>';
164 /// print out list of incoming contacts
165 if (!empty($unknownmessages)) {
166 echo '<tr><td colspan="3" class="heading">';
167 echo get_string('incomingcontacts', 'message', count($unknownmessages));
168 echo '</td></tr>';
170 foreach ($unknownmessages as $messageuser) {
171 $fullname = fullname($messageuser);
172 $fullnamelink = $fullname;
173 if ($messageuser->count) {
174 $fullnamelink = '<strong>'.$fullnamelink.' ('.$messageuser->count.')</strong>';
176 /// link to add to contact list
178 $strcontact = message_contact_link($messageuser->useridfrom, 'add', true);
179 $strblock = message_contact_link($messageuser->useridfrom, 'block', true);
180 $strhistory = message_history_link($messageuser->useridfrom, 0, true, '', '', 'icon');
182 echo '<tr><td class="pix">';
183 print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, true, 'userwindow');
184 echo '</td>';
185 echo '<td class="contact">';
187 link_to_popup_window("/message/discussion.php?id=$messageuser->useridfrom", "message_$messageuser->useridfrom",
188 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
189 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
191 echo '</td>';
192 echo '<td class="link">&nbsp;'.$strcontact.'&nbsp;'.$strblock.'&nbsp;'.$strhistory.'</td>';
193 echo '</tr>';
197 echo '</table>';
199 if (!empty($unknownmessages) && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
200 echo '<div class="note">(';
201 print_string('addsomecontactsincoming', 'message');
202 echo ')</div>';
208 echo '<br />';
210 $autorefresh = '<p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
211 $autorefresh = addslashes_js($autorefresh); // js escaping
213 // gracefully degrade JS autorefresh
214 echo '<script type="text/javascript">
215 //<![CDATA[
216 document.write("'.$autorefresh.'")
217 //]]>
218 </script>';
219 echo '<noscript><div align="center">';
220 echo print_single_button('index.php', false, get_string('refresh'));
221 echo '</div></noscript>';
227 /// $messagearray is an array of objects
228 /// $field is a valid property of object
229 /// $value is the value $field should equal to be counted
230 /// if $field is empty then return count of the whole array
231 /// if $field is non-existent then return 0;
232 function message_count_messages($messagearray, $field='', $value='') {
233 if (!is_array($messagearray)) return 0;
234 if ($field == '' or empty($messagearray)) return count($messagearray);
236 $count = 0;
237 foreach ($messagearray as $message) {
238 $count += ($message->$field == $value) ? 1 : 0;
240 return $count;
244 function message_print_search() {
245 global $USER;
247 if ($frm = data_submitted()) {
249 message_print_search_results($frm);
251 } else {
253 /// unfinished buggy code disabled in search.html anyway
254 // find all courses this use has readallmessages capabilities in
255 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
256 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
257 $cs = '<select name="courseselect">';
258 foreach ($teachers as $tcourse) {
259 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
261 $cs .= '</select>';
264 include('search.html');
268 function message_print_settings() {
269 global $USER;
271 if ($frm = data_submitted()) {
273 $pref = array();
274 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
275 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
276 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
277 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
278 $pref['message_noframesjs'] = (isset($frm->noframesjs)) ? '1' : '0';
279 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
280 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
281 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
282 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
284 set_user_preferences($pref);
286 redirect('index.php', get_string('settingssaved', 'message'), 1);
289 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
290 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
291 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
292 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
293 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ? 'checked="checked"' : '';
294 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
295 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
296 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
297 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
298 FORMAT_HTML => get_string('formathtml')),
299 'emailformat',
300 get_user_preferences('message_emailformat', FORMAT_PLAIN),
301 false, '', '0', true );
303 include('settings.html');
308 function message_add_contact($contactid, $blocked=0) {
309 global $USER;
311 if (!record_exists('user', 'id', $contactid)) { // invalid userid
312 return false;
315 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
316 /// record already exists - we may be changing blocking status
318 if ($contact->blocked !== $blocked) {
319 /// change to blocking status
320 $contact->blocked = $blocked;
321 return update_record('message_contacts', $contact);
322 } else {
323 /// no changes to blocking status
324 return true;
327 } else {
328 /// new contact record
329 unset($contact);
330 $contact->userid = $USER->id;
331 $contact->contactid = $contactid;
332 $contact->blocked = $blocked;
333 return insert_record('message_contacts', $contact, false);
337 function message_remove_contact($contactid) {
338 global $USER;
339 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
342 function message_unblock_contact($contactid) {
343 global $USER;
344 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
347 function message_block_contact($contactid) {
348 return message_add_contact($contactid, 1);
351 function message_get_contact($contactid) {
352 global $USER;
353 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
358 function message_print_search_results($frm) {
359 global $USER, $CFG;
361 echo '<div align="center">';
363 /// search for person
364 if (!empty($frm->personsubmit) and !empty($frm->name)) {
366 if (optional_param('mycourses', 0, PARAM_BOOL)) {
367 $users = array();
368 $mycourses = get_my_courses($USER->id);
369 foreach ($mycourses as $mycourse) {
370 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
371 foreach ($susers as $suser) $users[$suser->id] = $suser;
374 } else {
375 $users = message_search_users(SITEID, $frm->name);
378 if (!empty($users)) {
379 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
380 echo '<table class="message_users">';
381 foreach ($users as $user) {
383 if (($contact = message_get_contact($user->id)) !== false) {
384 if ($contact->blocked == 0) { /// not blocked
385 $strcontact = message_contact_link($user->id, 'remove', true);
386 $strblock = message_contact_link($user->id, 'block', true);
387 } else { // blocked
388 $strcontact = message_contact_link($user->id, 'add', true);
389 $strblock = message_contact_link($user->id, 'unblock', true);
391 } else {
392 $strcontact = message_contact_link($user->id, 'add', true);
393 $strblock = message_contact_link($user->id, 'block', true);
395 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
397 echo '<tr><td class="pix">';
398 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
399 echo '</td>';
400 echo '<td class="contact">';
401 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
402 500, 500, get_string('sendmessageto', 'message', fullname($user)),
403 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
405 echo '</td>';
407 echo '<td class="link">'.$strcontact.'</td>';
408 echo '<td class="link">'.$strblock.'</td>';
409 echo '<td class="link">'.$strhistory.'</td>';
410 echo '</tr>';
412 echo '</table>';
414 } else {
415 notify(get_string('nosearchresults', 'message'));
419 /// search messages for keywords
420 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
421 $keywordstring = clean_text(trim($frm->keywords));
422 $keywords = explode(' ', $keywordstring);
423 $tome = false;
424 $fromme = false;
425 $courseid = 'none';
427 switch ($frm->keywordsoption) {
428 case 'tome':
429 $tome = true;
430 break;
431 case 'fromme':
432 $fromme = true;
433 break;
434 case 'allmine':
435 $tome = true;
436 $fromme = true;
437 break;
438 case 'allusers':
439 $courseid = SITEID;
440 break;
441 case 'courseusers':
442 $courseid = $frm->courseid;
443 break;
444 default:
445 $tome = true;
446 $fromme = true;
449 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
451 /// get a list of contacts
452 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
453 $contacts = array();
456 /// print heading with number of results
457 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
459 /// print table headings
460 echo '<table class="searchresults" cellspacing="0">';
461 echo '<tr>';
462 echo '<td><strong>'.get_string('from').'</strong></td>';
463 echo '<td><strong>'.get_string('to').'</strong></td>';
464 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
465 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
466 echo "</tr>\n";
468 $blockedcount = 0;
469 $dateformat = get_string('strftimedatetime');
470 $strcontext = get_string('context', 'message');
471 foreach ($messages as $message) {
473 /// ignore messages to and from blocked users unless $frm->includeblocked is set
474 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
475 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
476 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
479 $blockedcount ++;
480 continue;
483 /// load up user to record
484 if ($message->useridto !== $USER->id) {
485 $userto = get_record('user', 'id', $message->useridto);
486 $tocontact = (array_key_exists($message->useridto, $contacts) and
487 ($contacts[$message->useridto]->blocked == 0) );
488 $toblocked = (array_key_exists($message->useridto, $contacts) and
489 ($contacts[$message->useridto]->blocked == 1) );
490 } else {
491 $userto = false;
492 $tocontact = false;
493 $toblocked = false;
496 /// load up user from record
497 if ($message->useridfrom !== $USER->id) {
498 $userfrom = get_record('user', 'id', $message->useridfrom);
499 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
500 ($contacts[$message->useridfrom]->blocked == 0) );
501 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
502 ($contacts[$message->useridfrom]->blocked == 1) );
503 } else {
504 $userfrom = false;
505 $fromcontact = false;
506 $fromblocked = false;
509 /// find date string for this message
510 $date = usergetdate($message->timecreated);
511 $datestring = $date['year'].$date['mon'].$date['mday'];
513 /// print out message row
514 echo '<tr valign="top">';
515 echo '<td class="contact">';
516 message_print_user($userfrom, $fromcontact, $fromblocked);
517 echo '</td>';
518 echo '<td class="contact">';
519 message_print_user($userto, $tocontact, $toblocked);
520 echo '</td>';
521 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
522 echo '<br /><div class="link">';
523 message_history_link($message->useridto, $message->useridfrom, false,
524 $keywordstring, 'm'.$message->id, $strcontext);
525 echo '</div>';
526 echo '</td>';
527 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
528 echo "</tr>\n";
532 if ($blockedcount > 0) {
533 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
535 echo '</table>';
537 } else {
538 notify(get_string('nosearchresults', 'message'));
542 /// what the ????, probably an empty search string, duh!
543 } else {
544 notify(get_string('emptysearchstring', 'message'));
547 echo '<br />';
548 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
550 echo '</div>';
554 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
555 global $USER;
556 if ($user === false) {
557 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
558 } else {
559 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
560 echo '&nbsp;';
561 if ($iscontact) {
562 message_contact_link($user->id, 'remove');
563 } else {
564 message_contact_link($user->id, 'add');
566 echo '&nbsp;';
567 if ($isblocked) {
568 message_contact_link($user->id, 'unblock');
569 } else {
570 message_contact_link($user->id, 'block');
572 echo '<br />';
574 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
575 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
576 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
581 /// linktype can be: add, remove, block, unblock
582 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
583 global $USER, $CFG;
585 static $str;
587 if (empty($str->blockcontact)) {
588 $str->blockcontact = get_string('blockcontact', 'message');
589 $str->unblockcontact = get_string('unblockcontact', 'message');
590 $str->removecontact = get_string('removecontact', 'message');
591 $str->addcontact = get_string('addcontact', 'message');
594 $command = $linktype.'contact';
595 $string = $str->{$command};
596 $alttext = $text ? '' : $string;
597 $text = $text ? '&nbsp;'.$string : '';
599 switch ($linktype) {
600 case 'block':
601 $icon = '/t/go.gif';
602 break;
603 case 'unblock':
604 $icon = '/t/stop.gif';
605 break;
606 case 'remove':
607 $icon = '/t/user.gif';
608 break;
609 case 'add':
610 default:
611 $icon = '/t/usernot.gif';
614 $output = '<span class="'.$linktype.'">'.
615 '<a href="'.$script.'&amp;'.$command.'='.$userid.
616 '&amp;sesskey='.sesskey().'" title="'.s($string).'">'.
617 '<img src="'.$CFG->pixpath.$icon.'" class="iconsmall" alt="'.s($alttext).'" />'.
618 $text.'</a></span>';
620 if ($return) {
621 return $output;
622 } else {
623 echo $output;
624 return true;
628 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
629 global $USER, $CFG;
631 static $strmessagehistory;
633 if (empty($strmessagehistory)) {
634 $strmessagehistory = get_string('messagehistory', 'message');
637 if (!$userid2) {
638 $userid2 = $USER->id;
640 if ($position) {
641 $position = "#$position";
643 if ($keywords) {
644 $keywords = "&search=".urlencode($keywords);
647 if ($linktext == 'icon') { // Icon only
648 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="'.$strmessagehistory.'" />';
649 } else if ($linktext == 'both') { // Icon and standard name
650 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="" />';
651 $fulllink .= '&nbsp;'.$strmessagehistory;
652 } else if ($linktext) { // Custom name
653 $fulllink = $linktext;
654 } else { // Standard name only
655 $fulllink = $strmessagehistory;
658 $str = link_to_popup_window("/message/history.php?user1=$userid1&amp;user2=$userid2$keywords$position",
659 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
660 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
662 $str = '<span class="history">'.$str.'</span>';
664 if ($returnstr) {
665 return $str;
666 } else {
667 echo $str;
668 return true;
674 * Search through course users
676 * If $coursid specifies the site course then this function searches
677 * through all undeleted and confirmed users
679 * @uses $CFG
680 * @uses SITEID
681 * @param int $courseid The course in question.
682 * @param string $searchtext ?
683 * @param string $sort ?
684 * @param string $exceptions ?
685 * @return array An array of {@link $USER} records.
686 * @todo Finish documenting this function
688 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
689 global $CFG;
691 $fullname = sql_fullname();
692 $LIKE = sql_ilike();
694 if (!empty($exceptions)) {
695 $except = ' AND u.id NOT IN ('. $exceptions .') ';
696 } else {
697 $except = '';
700 if (!empty($sort)) {
701 $order = ' ORDER BY '. $sort;
702 } else {
703 $order = '';
706 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
707 $fields = 'u.id, u.firstname, u.lastname, u.picture';
709 if (!$courseid or $courseid == SITEID) {
710 return get_records_sql("SELECT $fields
711 FROM {$CFG->prefix}user u
712 WHERE $select
713 AND ($fullname $LIKE '%$searchtext%')
714 $except $order");
715 } else {
717 $context = get_context_instance(CONTEXT_COURSE, $courseid);
718 $contextlists = get_related_contexts_string($context);
720 // everyone who has a role assignement in this course or higher
721 $users = get_records_sql("SELECT $fields
722 FROM {$CFG->prefix}user u,
723 {$CFG->prefix}role_assignments ra
724 WHERE $select
725 AND ra.contextid $contextlists
726 AND u.id = ra.userid
727 AND ($fullname $LIKE '%$searchtext%')
728 $except $order");
730 return $users;
737 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
738 /// Returns a list of posts found using an array of search terms
739 /// eg word +word -word
742 global $CFG, $USER;
744 /// If no userid sent then assume current user
745 if ($userid == 0) $userid = $USER->id;
747 /// Some differences in SQL syntax
748 $LIKE = sql_ilike();
749 $NOTLIKE = 'NOT ' . $LIKE;
750 if ($CFG->dbfamily == "postgres") {
751 $REGEXP = "~*";
752 $NOTREGEXP = "!~*";
753 } else {
754 $REGEXP = "REGEXP";
755 $NOTREGEXP = "NOT REGEXP";
758 $messagesearch = "";
760 foreach ($searchterms as $searchterm) {
761 if (strlen($searchterm) < 2) {
762 continue;
764 /// Under Oracle and MSSQL, trim the + and - operators and perform
765 /// simpler LIKE search
766 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
767 $searchterm = trim($searchterm, '+-');
770 if ($messagesearch) {
771 $messagesearch .= " AND ";
774 if (substr($searchterm,0,1) == "+") {
775 $searchterm = substr($searchterm,1);
776 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
777 } else if (substr($searchterm,0,1) == "-") {
778 $searchterm = substr($searchterm,1);
779 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
780 } else {
781 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
785 if ($messagesearch == '') { // if only 1 letter words searched
786 return false;
789 $messagesearch = "($messagesearch) ";
792 /// There are several possibilities
793 /// 1. courseid = SITEID : The admin is searching messages by all users
794 /// 2. courseid = ?? : A teacher is searching messages by users in
795 /// one of their courses - currently disabled
796 /// 3. courseid = none : User is searching their own messages;
797 /// a. Messages from user
798 /// b. Messages to user
799 /// c. Messages to and from user
801 if ($courseid == SITEID) { /// admin is searching all messages
802 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
803 FROM {$CFG->prefix}message_read m
804 WHERE $messagesearch");
805 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
806 FROM {$CFG->prefix}message m
807 WHERE $messagesearch");
809 if ($m_read === false) $m_read = array();
810 if ($m_unread === false) $m_unread = array();
812 } elseif ($courseid !== 'none') {
813 /// This has not been implemented due to security concerns
815 } else {
817 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
818 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
819 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
821 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
822 FROM {$CFG->prefix}message_read m
823 WHERE $messagesearch");
824 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
825 FROM {$CFG->prefix}message m
826 WHERE $messagesearch");
828 if ($m_read === false) $m_read = array();
829 if ($m_unread === false) $m_unread = array();
833 /// The keys may be duplicated in $m_read and $m_unread so we can't
834 /// do a simple concatenation
835 $message = array();
836 foreach ($m_read as $m) $messages[] = $m;
837 foreach ($m_unread as $m) $messages[] = $m;
840 return (empty($messages)) ? false : $messages;
845 /// Borrowed with changes from mod/forum/lib.php
846 function message_shorten_message($message, $minlength=0) {
847 // Given a post object that we already know has a long message
848 // this function truncates the message nicely to the first
849 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
851 $i = 0;
852 $tag = false;
853 $length = strlen($message);
854 $count = 0;
855 $stopzone = false;
856 $truncate = 0;
857 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
860 for ($i=0; $i<$length; $i++) {
861 $char = $message[$i];
863 switch ($char) {
864 case "<":
865 $tag = true;
866 break;
867 case ">":
868 $tag = false;
869 break;
870 default:
871 if (!$tag) {
872 if ($stopzone) {
873 if ($char == '.' or $char == ' ') {
874 $truncate = $i+1;
875 break 2;
878 $count++;
880 break;
882 if (!$stopzone) {
883 if ($count > $minlength) {
884 $stopzone = true;
889 if (!$truncate) {
890 $truncate = $i;
893 return substr($message, 0, $truncate);
898 * Given a string and an array of keywords, this function looks
899 * for the first keyword in the string, and then chops out a
900 * small section from the text that shows that word in context.
902 function message_get_fragment($message, $keywords) {
904 $fullsize = 120;
905 $halfsize = (int)($fullsize/2);
907 $message = strip_tags($message);
909 foreach ($keywords as $keyword) { // Just get the first one
910 if ($keyword !== '') {
911 break;
914 if (empty($keyword)) { // None found, so just return start of message
915 return message_shorten_message($message, 30);
918 $leadin = $leadout = '';
920 /// Find the start of the fragment
921 $start = 0;
922 $length = strlen($message);
924 $pos = strpos($message, $keyword);
925 if ($pos > $halfsize) {
926 $start = $pos - $halfsize;
927 $leadin = '...';
929 /// Find the end of the fragment
930 $end = $start + $fullsize;
931 if ($end > $length) {
932 $end = $length;
933 } else {
934 $leadout = '...';
937 /// Pull out the fragment and format it
939 $fragment = substr($message, $start, $end - $start);
940 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
941 return $fragment;
945 function message_get_history($user1, $user2) {
946 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
947 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
948 'timecreated');
949 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
950 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
951 'timecreated')) {
952 foreach ($messages_new as $message) {
953 $messages[] = $message;
956 return $messages;
959 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
961 static $dateformat;
963 if (empty($dateformat)) {
964 if ($format) {
965 $dateformat = $format;
966 } else {
967 $format = get_string('strftimedaytime');
970 $time = userdate($message->timecreated, $dateformat);
971 $options->para = false;
972 $messagetext = format_text($message->message, $message->format, $options);
973 if ($keywords) {
974 $messagetext = highlight($keywords, $messagetext);
976 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>';
980 * Inserts a message into the database, but also forwards it
981 * via other means if appropriate.
983 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
985 global $CFG, $SITE;
987 /// Save the new message in the database
989 $savemessage = NULL;
990 $savemessage->useridfrom = $userfrom->id;
991 $savemessage->useridto = $userto->id;
992 $savemessage->message = $message;
993 $savemessage->format = $format;
994 $savemessage->timecreated = time();
995 $savemessage->messagetype = 'direct';
997 if ($CFG->messaging) {
998 if (!$savemessage->id = insert_record('message', $savemessage)) {
999 return false;
1001 $emailforced = false;
1002 } else { // $CFG->messaging is not on, we need to force sending of emails
1003 $emailforced = true;
1004 $savemessage->id = true;
1007 /// Check to see if anything else needs to be done with it
1009 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
1011 if ($emailforced || (!isset($preference->message_emailmessages) || $preference->message_emailmessages)) { // Receiver wants mail forwarding
1012 if (!isset($preference->message_emailtimenosee)) {
1013 $preference->message_emailtimenosee = 10;
1015 if (!isset($preference->message_emailformat)) {
1016 $preference->message_emailformat = FORMAT_HTML;
1018 if ($emailforced || (time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
1020 $message = stripslashes_safe($message);
1021 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
1023 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
1025 $messagetext = format_text_email($message, $format).
1026 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1028 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
1029 $messagehtml = format_text($message, $format);
1030 // MDL-10294, do not print link if messaging is disabled
1031 if ($CFG->messaging) {
1032 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1034 } else {
1035 $messagehtml = NULL;
1038 if (!empty($preference->message_emailaddress)) {
1039 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1042 if (email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml)) {
1043 $CFG->messagewasjustemailed = true;
1046 sleep(3);
1050 return $savemessage->id;
1055 * Returns a list of all user ids who have used messaging in the site
1056 * This was the simple way to code the SQL ... is it going to blow up
1057 * on large datasets?
1059 function message_get_participants() {
1061 global $CFG;
1063 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1064 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1065 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1066 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1067 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1068 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");