Automatic installer.php lang files by installer_builder (20080223)
[moodle.git] / message / lib.php
blob2c6811d656415d074f504caf40a68b7dfca2e2b3
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 /><p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
210 /// $messagearray is an array of objects
211 /// $field is a valid property of object
212 /// $value is the value $field should equal to be counted
213 /// if $field is empty then return count of the whole array
214 /// if $field is non-existent then return 0;
215 function message_count_messages($messagearray, $field='', $value='') {
216 if (!is_array($messagearray)) return 0;
217 if ($field == '' or empty($messagearray)) return count($messagearray);
219 $count = 0;
220 foreach ($messagearray as $message) {
221 $count += ($message->$field == $value) ? 1 : 0;
223 return $count;
227 function message_print_search() {
228 global $USER;
230 if ($frm = data_submitted()) {
232 message_print_search_results($frm);
234 } else {
236 /// unfinished buggy code disabled in search.html anyway
237 // find all courses this use has readallmessages capabilities in
238 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
239 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
240 $cs = '<select name="courseselect">';
241 foreach ($teachers as $tcourse) {
242 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
244 $cs .= '</select>';
247 include('search.html');
251 function message_print_settings() {
252 global $USER;
254 if ($frm = data_submitted()) {
256 $pref = array();
257 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
258 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
259 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
260 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
261 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
262 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
263 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
264 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
266 set_user_preferences($pref);
268 redirect('index.php', get_string('settingssaved', 'message'), 1);
271 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
272 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
273 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
274 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
275 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
276 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
277 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
278 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
279 FORMAT_HTML => get_string('formathtml')),
280 'emailformat',
281 get_user_preferences('message_emailformat', FORMAT_PLAIN),
282 false, '', '0', true );
284 include('settings.html');
289 function message_add_contact($contactid, $blocked=0) {
290 global $USER;
292 if (!record_exists('user', 'id', $contactid)) { // invalid userid
293 return false;
296 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
297 /// record already exists - we may be changing blocking status
299 if ($contact->blocked !== $blocked) {
300 /// change to blocking status
301 $contact->blocked = $blocked;
302 return update_record('message_contacts', $contact);
303 } else {
304 /// no changes to blocking status
305 return true;
308 } else {
309 /// new contact record
310 unset($contact);
311 $contact->userid = $USER->id;
312 $contact->contactid = $contactid;
313 $contact->blocked = $blocked;
314 return insert_record('message_contacts', $contact, false);
318 function message_remove_contact($contactid) {
319 global $USER;
320 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
323 function message_unblock_contact($contactid) {
324 global $USER;
325 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
328 function message_block_contact($contactid) {
329 return message_add_contact($contactid, 1);
332 function message_get_contact($contactid) {
333 global $USER;
334 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
339 function message_print_search_results($frm) {
340 global $USER, $CFG;
342 echo '<div align="center">';
344 /// search for person
345 if (!empty($frm->personsubmit) and !empty($frm->name)) {
347 if ($frm->mycourses) {
348 $users = array();
349 $mycourses = get_my_courses($USER->id);
350 foreach ($mycourses as $mycourse) {
351 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
352 foreach ($susers as $suser) $users[$suser->id] = $suser;
355 } else {
356 $users = message_search_users(SITEID, $frm->name);
359 if (!empty($users)) {
360 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
361 echo '<table class="message_users">';
362 foreach ($users as $user) {
364 if (($contact = message_get_contact($user->id)) !== false) {
365 if ($contact->blocked == 0) { /// not blocked
366 $strcontact = message_contact_link($user->id, 'remove', true);
367 $strblock = message_contact_link($user->id, 'block', true);
368 } else { // blocked
369 $strcontact = message_contact_link($user->id, 'add', true);
370 $strblock = message_contact_link($user->id, 'unblock', true);
372 } else {
373 $strcontact = message_contact_link($user->id, 'add', true);
374 $strblock = message_contact_link($user->id, 'block', true);
376 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
378 echo '<tr><td class="pix">';
379 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
380 echo '</td>';
381 echo '<td class="contact">';
382 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
383 500, 500, get_string('sendmessageto', 'message', fullname($user)),
384 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
385 echo '</td>';
387 echo '<td class="link">'.$strcontact.'</td>';
388 echo '<td class="link">'.$strblock.'</td>';
389 echo '<td class="link">'.$strhistory.'</td>';
390 echo '</tr>';
392 echo '</table>';
394 } else {
395 notify(get_string('nosearchresults', 'message'));
399 /// search messages for keywords
400 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
401 $keywordstring = clean_text(trim($frm->keywords));
402 $keywords = explode(' ', $keywordstring);
403 $tome = false;
404 $fromme = false;
405 $courseid = 'none';
407 switch ($frm->keywordsoption) {
408 case 'tome':
409 $tome = true;
410 break;
411 case 'fromme':
412 $fromme = true;
413 break;
414 case 'allmine':
415 $tome = true;
416 $fromme = true;
417 break;
418 case 'allusers':
419 $courseid = SITEID;
420 break;
421 case 'courseusers':
422 $courseid = $frm->courseid;
423 break;
424 default:
425 $tome = true;
426 $fromme = true;
429 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
431 /// get a list of contacts
432 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
433 $contacts = array();
436 /// print heading with number of results
437 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
439 /// print table headings
440 echo '<table class="searchresults" cellspacing="0">';
441 echo '<tr>';
442 echo '<td><strong>'.get_string('from').'</strong></td>';
443 echo '<td><strong>'.get_string('to').'</strong></td>';
444 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
445 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
446 echo "</tr>\n";
448 $blockedcount = 0;
449 $dateformat = get_string('strftimedatetime');
450 $strcontext = get_string('context', 'message');
451 foreach ($messages as $message) {
453 /// ignore messages to and from blocked users unless $frm->includeblocked is set
454 if ((!$frm->includeblocked) and (
455 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
456 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
459 $blockedcount ++;
460 continue;
463 /// load up user to record
464 if ($message->useridto !== $USER->id) {
465 $userto = get_record('user', 'id', $message->useridto);
466 $tocontact = (array_key_exists($message->useridto, $contacts) and
467 ($contacts[$message->useridto]->blocked == 0) );
468 $toblocked = (array_key_exists($message->useridto, $contacts) and
469 ($contacts[$message->useridto]->blocked == 1) );
470 } else {
471 $userto = false;
472 $tocontact = false;
473 $toblocked = false;
476 /// load up user from record
477 if ($message->useridfrom !== $USER->id) {
478 $userfrom = get_record('user', 'id', $message->useridfrom);
479 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
480 ($contacts[$message->useridfrom]->blocked == 0) );
481 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
482 ($contacts[$message->useridfrom]->blocked == 1) );
483 } else {
484 $userfrom = false;
485 $fromcontact = false;
486 $fromblocked = false;
489 /// find date string for this message
490 $date = usergetdate($message->timecreated);
491 $datestring = $date['year'].$date['mon'].$date['mday'];
493 /// print out message row
494 echo '<tr valign="top">';
495 echo '<td class="contact">';
496 message_print_user($userfrom, $fromcontact, $fromblocked);
497 echo '</td>';
498 echo '<td class="contact">';
499 message_print_user($userto, $tocontact, $toblocked);
500 echo '</td>';
501 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
502 echo '<br /><div class="link">';
503 message_history_link($message->useridto, $message->useridfrom, false,
504 $keywordstring, 'm'.$message->id, $strcontext);
505 echo '</div>';
506 echo '</td>';
507 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
508 echo "</tr>\n";
512 if ($blockedcount > 0) {
513 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
515 echo '</table>';
517 } else {
518 notify(get_string('nosearchresults', 'message'));
522 /// what the ????, probably an empty search string, duh!
523 } else {
524 notify(get_string('emptysearchstring', 'message'));
527 echo '<br />';
528 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
530 echo '</div>';
534 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
535 global $USER;
536 if ($user === false) {
537 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
538 } else {
539 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
540 echo '&nbsp;';
541 if ($iscontact) {
542 message_contact_link($user->id, 'remove');
543 } else {
544 message_contact_link($user->id, 'add');
546 echo '&nbsp;';
547 if ($isblocked) {
548 message_contact_link($user->id, 'unblock');
549 } else {
550 message_contact_link($user->id, 'block');
552 echo '<br />';
553 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
554 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
555 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
560 /// linktype can be: add, remove, block, unblock
561 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
562 global $USER, $CFG;
564 static $str;
566 if (empty($str->blockcontact)) {
567 $str->blockcontact = get_string('blockcontact', 'message');
568 $str->unblockcontact = get_string('unblockcontact', 'message');
569 $str->removecontact = get_string('removecontact', 'message');
570 $str->addcontact = get_string('addcontact', 'message');
573 $command = $linktype.'contact';
574 $string = $str->{$command};
575 $text = $text ? '&nbsp;'.$string : '';
577 switch ($linktype) {
578 case 'block':
579 $icon = '/t/go.gif';
580 break;
581 case 'unblock':
582 $icon = '/t/stop.gif';
583 break;
584 case 'remove':
585 $icon = '/t/user.gif';
586 break;
587 case 'add':
588 default:
589 $icon = '/t/usernot.gif';
592 $output = '<span class="'.$linktype.'">'.
593 '<a href="'.$script.'&amp;'.$command.'='.$userid.
594 '&amp;sesskey='.sesskey().'" title="'.$string.'">'.
595 '<img src="'.$CFG->pixpath.$icon.'" height="11" width="11" border="0">'.
596 $text.'</a></span>';
598 if ($return) {
599 return $output;
600 } else {
601 echo $output;
602 return true;
606 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
607 global $USER, $CFG;
609 static $strmessagehistory;
611 if (empty($strmessagehistory)) {
612 $strmessagehistory = get_string('messagehistory', 'message');
615 if (!$userid2) {
616 $userid2 = $USER->id;
618 if ($position) {
619 $position = "#$position";
621 if ($keywords) {
622 $keywords = "&search=".urlencode($keywords);
625 if ($linktext == 'icon') { // Icon only
626 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">';
627 } else if ($linktext == 'both') { // Icon and standard name
628 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">';
629 $fulllink .= '&nbsp;'.$strmessagehistory;
630 } else if ($linktext) { // Custom name
631 $fulllink = $linktext;
632 } else { // Standard name only
633 $fulllink = $strmessagehistory;
636 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$keywords$position",
637 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
638 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
640 $str = '<span class="history">'.$str.'</span>';
642 if ($returnstr) {
643 return $str;
644 } else {
645 echo $str;
646 return true;
652 * Search through course users
654 * If $coursid specifies the site course then this function searches
655 * through all undeleted and confirmed users
657 * @uses $CFG
658 * @uses SITEID
659 * @param int $courseid The course in question.
660 * @param string $searchtext ?
661 * @param string $sort ?
662 * @param string $exceptions ?
663 * @return array An array of {@link $USER} records.
664 * @todo Finish documenting this function
666 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
667 global $CFG;
669 $fullname = sql_fullname();
670 $LIKE = sql_ilike();
672 if (!empty($exceptions)) {
673 $except = ' AND u.id NOT IN ('. $exceptions .') ';
674 } else {
675 $except = '';
678 if (!empty($sort)) {
679 $order = ' ORDER BY '. $sort;
680 } else {
681 $order = '';
684 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
685 $fields = 'u.id, u.firstname, u.lastname, u.picture';
687 if (!$courseid or $courseid == SITEID) {
688 return get_records_sql("SELECT $fields
689 FROM {$CFG->prefix}user u
690 WHERE $select
691 AND ($fullname $LIKE '%$searchtext%')
692 $except $order");
693 } else {
695 $context = get_context_instance(CONTEXT_COURSE, $courseid);
696 $contextlists = get_related_contexts_string($context);
698 // everyone who has a role assignement in this course or higher
699 $users = get_records_sql("SELECT $fields
700 FROM {$CFG->prefix}user u,
701 {$CFG->prefix}role_assignments ra
702 WHERE $select
703 AND ra.contextid $contextlists
704 AND u.id = ra.userid
705 AND ($fullname $LIKE '%$searchtext%')
706 $except $order");
708 return $users;
715 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
716 /// Returns a list of posts found using an array of search terms
717 /// eg word +word -word
720 global $CFG, $USER;
722 /// If no userid sent then assume current user
723 if ($userid == 0) $userid = $USER->id;
725 /// Some differences in SQL syntax
726 $LIKE = sql_ilike();
727 $NOTLIKE = 'NOT ' . $LIKE;
728 if ($CFG->dbtype == "postgres7") {
729 $REGEXP = "~*";
730 $NOTREGEXP = "!~*";
731 } else {
732 $REGEXP = "REGEXP";
733 $NOTREGEXP = "NOT REGEXP";
736 $messagesearch = "";
738 foreach ($searchterms as $searchterm) {
739 if (strlen($searchterm) < 2) {
740 continue;
742 /// Under Oracle and MSSQL, trim the + and - operators and perform
743 /// simpler LIKE search
744 if ($CFG->dbtype == 'oci8po' || $CFG->dbtype == 'mssql' || $CFG->dbtype == 'mssql_n' || $CFG->dbtype == 'odbc_mssql') {
745 $searchterm = trim($searchterm, '+-');
748 if ($messagesearch) {
749 $messagesearch .= " AND ";
752 if (substr($searchterm,0,1) == "+") {
753 $searchterm = substr($searchterm,1);
754 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
755 } else if (substr($searchterm,0,1) == "-") {
756 $searchterm = substr($searchterm,1);
757 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
758 } else {
759 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
763 if ($messagesearch == '') { // if only 1 letter words searched
764 return false;
767 $messagesearch = "($messagesearch) ";
770 /// There are several possibilities
771 /// 1. courseid = SITEID : The admin is searching messages by all users
772 /// 2. courseid = ?? : A teacher is searching messages by users in
773 /// one of their courses - currently disabled
774 /// 3. courseid = none : User is searching their own messages;
775 /// a. Messages from user
776 /// b. Messages to user
777 /// c. Messages to and from user
779 if ($courseid == SITEID) { /// admin is searching all messages
780 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
781 FROM {$CFG->prefix}message_read m
782 WHERE $messagesearch");
783 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
784 FROM {$CFG->prefix}message m
785 WHERE $messagesearch");
787 if ($m_read === false) $m_read = array();
788 if ($m_unread === false) $m_unread = array();
790 } elseif ($courseid !== 'none') {
791 /// This has not been implemented due to security concerns
793 } else {
795 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
796 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
797 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
799 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
800 FROM {$CFG->prefix}message_read m
801 WHERE $messagesearch");
802 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
803 FROM {$CFG->prefix}message m
804 WHERE $messagesearch");
806 if ($m_read === false) $m_read = array();
807 if ($m_unread === false) $m_unread = array();
811 /// The keys may be duplicated in $m_read and $m_unread so we can't
812 /// do a simple concatenation
813 $message = array();
814 foreach ($m_read as $m) $messages[] = $m;
815 foreach ($m_unread as $m) $messages[] = $m;
818 return (empty($messages)) ? false : $messages;
823 /// Borrowed with changes from mod/forum/lib.php
824 function message_shorten_message($message, $minlength=0) {
825 // Given a post object that we already know has a long message
826 // this function truncates the message nicely to the first
827 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
829 $i = 0;
830 $tag = false;
831 $length = strlen($message);
832 $count = 0;
833 $stopzone = false;
834 $truncate = 0;
835 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
838 for ($i=0; $i<$length; $i++) {
839 $char = $message[$i];
841 switch ($char) {
842 case "<":
843 $tag = true;
844 break;
845 case ">":
846 $tag = false;
847 break;
848 default:
849 if (!$tag) {
850 if ($stopzone) {
851 if ($char == '.' or $char == ' ') {
852 $truncate = $i+1;
853 break 2;
856 $count++;
858 break;
860 if (!$stopzone) {
861 if ($count > $minlength) {
862 $stopzone = true;
867 if (!$truncate) {
868 $truncate = $i;
871 return substr($message, 0, $truncate);
876 * Given a string and an array of keywords, this function looks
877 * for the first keyword in the string, and then chops out a
878 * small section from the text that shows that word in context.
880 function message_get_fragment($message, $keywords) {
882 $fullsize = 120;
883 $halfsize = (int)($fullsize/2);
885 $message = strip_tags($message);
887 foreach ($keywords as $keyword) { // Just get the first one
888 if ($keyword !== '') {
889 break;
892 if (empty($keyword)) { // None found, so just return start of message
893 return message_shorten_message($message, 30);
896 $leadin = $leadout = '';
898 /// Find the start of the fragment
899 $start = 0;
900 $length = strlen($message);
902 $pos = strpos($message, $keyword);
903 if ($pos > $halfsize) {
904 $start = $pos - $halfsize;
905 $leadin = '...';
907 /// Find the end of the fragment
908 $end = $start + $fullsize;
909 if ($end > $length) {
910 $end = $length;
911 } else {
912 $leadout = '...';
915 /// Pull out the fragment and format it
917 $fragment = substr($message, $start, $end - $start);
918 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
919 return $fragment;
923 function message_get_history($user1, $user2) {
924 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
925 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
926 'timecreated');
927 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
928 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
929 'timecreated')) {
930 foreach ($messages_new as $message) {
931 $messages[] = $message;
934 return $messages;
937 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
939 static $dateformat;
941 if (empty($dateformat)) {
942 if ($format) {
943 $dateformat = $format;
944 } else {
945 $format = get_string('strftimedaytime');
948 $time = userdate($message->timecreated, $dateformat);
949 $options->para = false;
950 $messagetext = format_text($message->message, $message->format, $options);
951 if ($keywords) {
952 $messagetext = highlight($keywords, $messagetext);
954 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>';
958 * Inserts a message into the database, but also forwards it
959 * via other means if appropriate.
961 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
963 global $CFG, $SITE;
965 /// Save the new message in the database
967 $savemessage = NULL;
968 $savemessage->useridfrom = $userfrom->id;
969 $savemessage->useridto = $userto->id;
970 $savemessage->message = $message;
971 $savemessage->format = $format;
972 $savemessage->timecreated = time();
973 $savemessage->messagetype = 'direct';
975 if (!$savemessage->id = insert_record('message', $savemessage)) {
976 return false;
980 /// Check to see if anything else needs to be done with it
982 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
984 if (!isset($preference->message_emailmessages) or $preference->message_emailmessages) { // Receiver wants mail forwarding
985 if (!isset($preference->message_emailtimenosee)) {
986 $preference->message_emailtimenosee = 10;
988 if (!isset($preference->message_emailformat)) {
989 $preference->message_emailformat = FORMAT_HTML;
991 if ((time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
993 $message = stripslashes_safe($message);
994 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
996 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
997 $messagesubject = str_replace("\n", ' ', $messagesubject); // make sure it's all on one line
999 $messagetext = format_text_email($message, $format).
1000 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1002 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
1003 $messagehtml = format_text($message, $format);
1004 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1005 } else {
1006 $messagehtml = NULL;
1009 if (!empty($preference->message_emailaddress)) {
1010 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1012 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
1016 return $savemessage->id;
1021 * Returns a list of all user ids who have used messaging in the site
1022 * This was the simple way to code the SQL ... is it going to blow up
1023 * on large datasets?
1025 function message_get_participants() {
1027 global $CFG;
1029 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1030 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1031 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1032 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1033 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1034 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");