MDL-13766, trim api_key
[moodle.git] / message / lib.php
CommitLineData
172186b8 1<?php
2/// library functions for messaging
3
3b120e46 4require_once($CFG->libdir.'/eventslib.php');
5
e8e2d7f1 6
7define ('MESSAGE_SHORTLENGTH', 300);
fd7006f6 8define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
9
05753d2b 10if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
2a38a6be 11 $CFG->message_contacts_refresh = 60;
fd7006f6 12}
5d6b319b 13if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
14 $CFG->message_chat_refresh = 5;
fd7006f6 15}
f520438c 16if (!isset($CFG->message_offline_time)) {
17 $CFG->message_offline_time = 300;
18}
172186b8 19
20
21function message_print_contacts() {
fd1cb1e8 22 global $USER, $CFG, $DB;
e8e2d7f1 23
24 $timetoshowusers = 300; //Seconds default
25 if (isset($CFG->block_online_users_timetosee)) {
26 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
27 }
e8e2d7f1 28
f46b6587 29 // time which a user is counting as being active since
30 $timefrom = time()-$timetoshowusers;
531e58f1 31
f46b6587 32 // people in our contactlist who are online
33 $onlinecontacts = array();
34 // people in our contactlist who are offline
35 $offlinecontacts = array();
36 // people who are not in our contactlist but have sent us a message
37 $strangers = array();
38
39
40 // get all in our contactlist who are not blocked in our contact list
41 // and count messages we have waiting from each of them
42 $contactsql = "SELECT u.id, u.firstname, u.lastname, u.picture,
43 u.imagealt, u.lastaccess, count(m.id) as messagecount
fd1cb1e8 44 FROM {message_contacts} mc
45 JOIN {user} u ON u.id = mc.contactid
46 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
47 WHERE mc.userid = ? AND mc.blocked = 0
48 GROUP BY u.id, u.firstname, u.lastname, u.picture,
49 u.imagealt, u.lastaccess
50 ORDER BY u.firstname ASC;";
51
52 if ($rs = $DB->get_recordset_sql($contactsql, array($USER->id, $USER->id))){
53 foreach($rs as $rd){
f46b6587 54
55 if($rd->lastaccess >= $timefrom){
56 // they have been active recently, so are counted online
57 $onlinecontacts[] = $rd;
58 }else{
59 $offlinecontacts[] = $rd;
e8e2d7f1 60 }
61 }
f46b6587 62 unset($rd);
fd1cb1e8 63 $rs->close();
f46b6587 64 }
65
66
67 // get messages from anyone who isn't in our contact list and count the number
68 // of messages we have from each of them
69 $strangersql = "SELECT u.id, u.firstname, u.lastname, u.picture,
70 u.imagealt, u.lastaccess, count(m.id) as messagecount
fd1cb1e8 71 FROM {message} m
72 JOIN {user} u ON u.id = m.useridfrom
73 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
74 WHERE mc.id IS NULL AND m.useridto = ?
75 GROUP BY u.id, u.firstname, u.lastname, u.picture,
76 u.imagealt, u.lastaccess
77 ORDER BY u.firstname ASC;";
78
79 if($rs = $DB->get_recordset_sql($strangersql, array($USER->id))){
80 foreach($rs as $rd){
f46b6587 81 $strangers[] = $rd;
82 }
83 unset($rd);
fd1cb1e8 84 $rs->close();
e8e2d7f1 85 }
86
f46b6587 87 $countonlinecontacts = count($onlinecontacts);
88 $countofflinecontacts = count($offlinecontacts);
89 $countstrangers = count($strangers);
90
a1157dda 91 if ($countonlinecontacts + $countofflinecontacts == 0) {
669be60c 92 echo '<div class="heading">';
65ef518b 93 print_string('contactlistempty', 'message');
a1157dda 94 echo '</div>';
669be60c 95 echo '<div class="note">';
65ef518b 96 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
a1157dda 97 echo '</div>';
65ef518b 98 }
99
04b687e8 100 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
531e58f1 101
f46b6587 102 if($countonlinecontacts) {
103 /// print out list of online contacts
531e58f1 104
f46b6587 105 echo '<tr><td colspan="3" class="heading">';
106 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
107 echo '</td></tr>';
531e58f1 108
f46b6587 109 foreach ($onlinecontacts as $contact) {
110 message_print_contactlist_user($contact);
65ef518b 111 }
f46b6587 112 }
113 echo '<tr><td colspan="3">&nbsp;</td></tr>';
531e58f1 114
f46b6587 115 if ($countofflinecontacts) {
116 /// print out list of offline contacts
531e58f1 117
f46b6587 118 echo '<tr><td colspan="3" class="heading">';
119 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
120 echo '</td></tr>';
576ad290 121
f46b6587 122 foreach ($offlinecontacts as $contact) {
123 message_print_contactlist_user($contact);
65ef518b 124 }
f46b6587 125 echo '<tr><td colspan="3">&nbsp;</td></tr>';
126 }
65ef518b 127
f46b6587 128 /// print out list of incoming contacts
129 if ($countstrangers) {
130 echo '<tr><td colspan="3" class="heading">';
131 echo get_string('incomingcontacts', 'message', $countstrangers);
132 echo '</td></tr>';
531e58f1 133
f46b6587 134 foreach ($strangers as $stranger) {
135 message_print_contactlist_user($stranger, false);
669be60c 136 }
f46b6587 137 }
531e58f1 138
f46b6587 139 echo '</table>';
65ef518b 140
f46b6587 141 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
142 echo '<div class="note">(';
143 print_string('addsomecontactsincoming', 'message');
144 echo ')</div>';
65ef518b 145 }
b9ee0638 146
531e58f1 147 echo '<br />';
a9d9b46a 148
531e58f1 149 $autorefresh = '<p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
4702be4e 150 $autorefresh = addslashes_js($autorefresh); // js escaping
531e58f1 151
152 // gracefully degrade JS autorefresh
153 echo '<script type="text/javascript">
154//<![CDATA[
155document.write("'.$autorefresh.'")
156//]]>
157</script>';
04b687e8 158 echo '<noscript><div class="button aligncenter">';
6ee78cee 159 echo print_single_button('index.php', false, get_string('refresh'));
531e58f1 160 echo '</div></noscript>';
e8e2d7f1 161}
162
163
e8e2d7f1 164/// $messagearray is an array of objects
165/// $field is a valid property of object
166/// $value is the value $field should equal to be counted
167/// if $field is empty then return count of the whole array
168/// if $field is non-existent then return 0;
169function message_count_messages($messagearray, $field='', $value='') {
170 if (!is_array($messagearray)) return 0;
171 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 172
e8e2d7f1 173 $count = 0;
174 foreach ($messagearray as $message) {
175 $count += ($message->$field == $value) ? 1 : 0;
176 }
177 return $count;
172186b8 178}
179
e8e2d7f1 180
172186b8 181function message_print_search() {
9ae3253e 182 global $USER;
531e58f1 183
294ce987 184 if ($frm = data_submitted()) {
531e58f1 185
172186b8 186 message_print_search_results($frm);
531e58f1 187
172186b8 188 } else {
1ac41751 189/*
531e58f1 190/// unfinished buggy code disabled in search.html anyway
d76a5a7f 191 // find all courses this use has readallmessages capabilities in
192 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
172186b8 193 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
194 $cs = '<select name="courseselect">';
195 foreach ($teachers as $tcourse) {
d76a5a7f 196 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
172186b8 197 }
198 $cs .= '</select>';
199 }
1ac41751 200*/
172186b8 201 include('search.html');
202 }
203}
204
205function message_print_settings() {
9ae3253e 206 global $USER;
531e58f1 207
294ce987 208 if ($frm = data_submitted()) {
acef58f4 209
e8e2d7f1 210 $pref = array();
211 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
212 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
3f85157b 213 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
e49617af 214 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
531e58f1 215 $pref['message_noframesjs'] = (isset($frm->noframesjs)) ? '1' : '0';
e8e2d7f1 216 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
acef58f4 217 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
e8e2d7f1 218 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
219 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
e8e2d7f1 220
221 set_user_preferences($pref);
531e58f1 222
9ae3253e 223 redirect('index.php', get_string('settingssaved', 'message'), 1);
e8e2d7f1 224 }
225
226 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
fd7006f6 227 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
3f85157b 228 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
9aa959f2 229 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
531e58f1 230 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ? 'checked="checked"' : '';
e8e2d7f1 231 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
232 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
233 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
234 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
235 FORMAT_HTML => get_string('formathtml')),
236 'emailformat',
237 get_user_preferences('message_emailformat', FORMAT_PLAIN),
238 false, '', '0', true );
531e58f1 239
e8e2d7f1 240 include('settings.html');
241}
242
243
244
245function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 246 global $USER, $DB;
531e58f1 247
fd1cb1e8 248 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
e8e2d7f1 249 return false;
250 }
531e58f1 251
fd1cb1e8 252 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
e8e2d7f1 253 /// record already exists - we may be changing blocking status
531e58f1 254
e8e2d7f1 255 if ($contact->blocked !== $blocked) {
256 /// change to blocking status
257 $contact->blocked = $blocked;
fd1cb1e8 258 return $DB->update_record('message_contacts', $contact);
e8e2d7f1 259 } else {
260 /// no changes to blocking status
261 return true;
262 }
531e58f1 263
172186b8 264 } else {
e8e2d7f1 265 /// new contact record
266 unset($contact);
267 $contact->userid = $USER->id;
268 $contact->contactid = $contactid;
269 $contact->blocked = $blocked;
fd1cb1e8 270 return $DB->insert_record('message_contacts', $contact, false);
172186b8 271 }
272}
273
e8e2d7f1 274function message_remove_contact($contactid) {
fd1cb1e8 275 global $USER, $DB;
276 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 277}
278
279function message_unblock_contact($contactid) {
fd1cb1e8 280 global $USER, $DB;
281 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 282}
283
284function message_block_contact($contactid) {
285 return message_add_contact($contactid, 1);
286}
287
288function message_get_contact($contactid) {
fd1cb1e8 289 global $USER, $DB;
290 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 291}
531e58f1 292
e8e2d7f1 293
294
172186b8 295function message_print_search_results($frm) {
fd1cb1e8 296 global $USER, $CFG, $DB;
e8e2d7f1 297
298 echo '<div align="center">';
299
300 /// search for person
301 if (!empty($frm->personsubmit) and !empty($frm->name)) {
531e58f1 302
b71d4dd2 303 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 304 $users = array();
305 $mycourses = get_my_courses($USER->id);
306 foreach ($mycourses as $mycourse) {
307 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
308 foreach ($susers as $suser) $users[$suser->id] = $suser;
309 }
310 }
311 } else {
312 $users = message_search_users(SITEID, $frm->name);
313 }
314
315 if (!empty($users)) {
316 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
317 echo '<table class="message_users">';
318 foreach ($users as $user) {
531e58f1 319
7390832c 320 if ( $user->contactlistid ) {
321 if ($user->blocked == 0) { /// not blocked
082864f9 322 $strcontact = message_contact_link($user->id, 'remove', true);
323 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 324 } else { // blocked
082864f9 325 $strcontact = message_contact_link($user->id, 'add', true);
326 $strblock = message_contact_link($user->id, 'unblock', true);
e8e2d7f1 327 }
e8e2d7f1 328 } else {
082864f9 329 $strcontact = message_contact_link($user->id, 'add', true);
330 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 331 }
f520438c 332 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
531e58f1 333
669be60c 334 echo '<tr><td class="pix">';
7390832c 335 print_user_picture($user, SITEID, $user->picture, 20, false, true, 'userwindow');
e8e2d7f1 336 echo '</td>';
669be60c 337 echo '<td class="contact">';
531e58f1 338 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
405f01ee 339 500, 500, get_string('sendmessageto', 'message', fullname($user)),
340 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
576ad290 341
e8e2d7f1 342 echo '</td>';
531e58f1 343
669be60c 344 echo '<td class="link">'.$strcontact.'</td>';
345 echo '<td class="link">'.$strblock.'</td>';
346 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 347 echo '</tr>';
348 }
349 echo '</table>';
531e58f1 350
e8e2d7f1 351 } else {
352 notify(get_string('nosearchresults', 'message'));
353 }
531e58f1 354
355
e8e2d7f1 356 /// search messages for keywords
357 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
38c6a928 358 $keywordstring = clean_text(trim($frm->keywords));
359 $keywords = explode(' ', $keywordstring);
e8e2d7f1 360 $tome = false;
361 $fromme = false;
362 $courseid = 'none';
363
364 switch ($frm->keywordsoption) {
365 case 'tome':
366 $tome = true;
367 break;
368 case 'fromme':
369 $fromme = true;
370 break;
371 case 'allmine':
372 $tome = true;
373 $fromme = true;
374 break;
375 case 'allusers':
376 $courseid = SITEID;
377 break;
378 case 'courseusers':
379 $courseid = $frm->courseid;
380 break;
381 default:
382 $tome = true;
383 $fromme = true;
384 }
385
386 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 387
e8e2d7f1 388 /// get a list of contacts
fd1cb1e8 389 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
082864f9 390 $contacts = array();
391 }
e8e2d7f1 392
082864f9 393 /// print heading with number of results
669be60c 394 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
082864f9 395
396 /// print table headings
669be60c 397 echo '<table class="searchresults" cellspacing="0">';
082864f9 398 echo '<tr>';
fd7006f6 399 echo '<td><strong>'.get_string('from').'</strong></td>';
400 echo '<td><strong>'.get_string('to').'</strong></td>';
401 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
402 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
082864f9 403 echo "</tr>\n";
404
405 $blockedcount = 0;
54d8f804 406 $dateformat = get_string('strftimedatetimeshort');
38c6a928 407 $strcontext = get_string('context', 'message');
e8e2d7f1 408 foreach ($messages as $message) {
082864f9 409
410 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 411 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 412 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
413 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
414 )
415 ) {
416 $blockedcount ++;
e8e2d7f1 417 continue;
418 }
531e58f1 419
082864f9 420 /// load up user to record
421 if ($message->useridto !== $USER->id) {
fd1cb1e8 422 $userto = $DB->get_record('user', array('id'=>$message->useridto));
531e58f1 423 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 424 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 425 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 426 ($contacts[$message->useridto]->blocked == 1) );
427 } else {
428 $userto = false;
429 $tocontact = false;
430 $toblocked = false;
431 }
531e58f1 432
082864f9 433 /// load up user from record
434 if ($message->useridfrom !== $USER->id) {
fd1cb1e8 435 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
531e58f1 436 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 437 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 438 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 439 ($contacts[$message->useridfrom]->blocked == 1) );
440 } else {
441 $userfrom = false;
442 $fromcontact = false;
443 $fromblocked = false;
444 }
445
e520509a 446 /// find date string for this message
447 $date = usergetdate($message->timecreated);
448 $datestring = $date['year'].$date['mon'].$date['mday'];
449
082864f9 450 /// print out message row
451 echo '<tr valign="top">';
669be60c 452 echo '<td class="contact">';
b9ee0638 453 message_print_user($userfrom, $fromcontact, $fromblocked);
e8e2d7f1 454 echo '</td>';
669be60c 455 echo '<td class="contact">';
b9ee0638 456 message_print_user($userto, $tocontact, $toblocked);
e8e2d7f1 457 echo '</td>';
669be60c 458 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
459 echo '<br /><div class="link">';
531e58f1 460 message_history_link($message->useridto, $message->useridfrom, false,
2973ec18 461 $keywordstring, 'm'.$message->id, $strcontext);
f520438c 462 echo '</div>';
e520509a 463 echo '</td>';
669be60c 464 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 465 echo "</tr>\n";
466 }
531e58f1 467
e8e2d7f1 468
e520509a 469 if ($blockedcount > 0) {
470 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
471 }
e8e2d7f1 472 echo '</table>';
531e58f1 473
e8e2d7f1 474 } else {
475 notify(get_string('nosearchresults', 'message'));
476 }
477
478
479 /// what the ????, probably an empty search string, duh!
480 } else {
481 notify(get_string('emptysearchstring', 'message'));
482 }
483
082864f9 484 echo '<br />';
9ae3253e 485 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
e8e2d7f1 486
487 echo '</div>';
488}
489
490
082864f9 491function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
492 global $USER;
493 if ($user === false) {
b4d80abe 494 print_user_picture($USER, SITEID, $USER->picture, 20, false, true, 'userwindow');
082864f9 495 } else {
b4d80abe 496 print_user_picture($user, SITEID, $user->picture, 20, false, true, 'userwindow');
e520509a 497 echo '&nbsp;';
082864f9 498 if ($iscontact) {
499 message_contact_link($user->id, 'remove');
500 } else {
501 message_contact_link($user->id, 'add');
502 }
503 echo '&nbsp;';
504 if ($isblocked) {
505 message_contact_link($user->id, 'unblock');
506 } else {
507 message_contact_link($user->id, 'block');
508 }
e520509a 509 echo '<br />';
576ad290 510
531e58f1 511 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
405f01ee 512 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
513 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
082864f9 514 }
515}
516
517
518/// linktype can be: add, remove, block, unblock
5d6b319b 519function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
e520509a 520 global $USER, $CFG;
521
522 static $str;
523
524 if (empty($str->blockcontact)) {
525 $str->blockcontact = get_string('blockcontact', 'message');
526 $str->unblockcontact = get_string('unblockcontact', 'message');
527 $str->removecontact = get_string('removecontact', 'message');
528 $str->addcontact = get_string('addcontact', 'message');
529 }
530
5d6b319b 531 $command = $linktype.'contact';
532 $string = $str->{$command};
d53f1cdb 533 $alttext = $text ? '' : $string;
5d6b319b 534 $text = $text ? '&nbsp;'.$string : '';
535
082864f9 536 switch ($linktype) {
537 case 'block':
5d6b319b 538 $icon = '/t/go.gif';
082864f9 539 break;
540 case 'unblock':
5d6b319b 541 $icon = '/t/stop.gif';
082864f9 542 break;
543 case 'remove':
5d6b319b 544 $icon = '/t/user.gif';
082864f9 545 break;
546 case 'add':
547 default:
5d6b319b 548 $icon = '/t/usernot.gif';
082864f9 549 }
5d6b319b 550
551 $output = '<span class="'.$linktype.'">'.
552 '<a href="'.$script.'&amp;'.$command.'='.$userid.
0d3bb48d 553 '&amp;sesskey='.sesskey().'" title="'.s($string).'">'.
0d905d9f 554 '<img src="'.$CFG->pixpath.$icon.'" class="iconsmall" alt="'.s($alttext).'" />'.
5d6b319b 555 $text.'</a></span>';
556
e520509a 557 if ($return) {
558 return $output;
082864f9 559 } else {
e520509a 560 echo $output;
082864f9 561 return true;
562 }
563}
564
38c6a928 565function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
fd7006f6 566 global $USER, $CFG;
62119d65 567
830d0af6 568 static $strmessagehistory;
569
570 if (empty($strmessagehistory)) {
571 $strmessagehistory = get_string('messagehistory', 'message');
572 }
2514081c 573
62119d65 574 if (!$userid2) {
575 $userid2 = $USER->id;
576 }
e520509a 577 if ($position) {
578 $position = "#$position";
579 }
38c6a928 580 if ($keywords) {
581 $keywords = "&search=".urlencode($keywords);
582 }
62119d65 583
830d0af6 584 if ($linktext == 'icon') { // Icon only
0d905d9f 585 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 586 } else if ($linktext == 'both') { // Icon and standard name
0d905d9f 587 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" class="iconsmall" alt="" />';
830d0af6 588 $fulllink .= '&nbsp;'.$strmessagehistory;
589 } else if ($linktext) { // Custom name
590 $fulllink = $linktext;
591 } else { // Standard name only
592 $fulllink = $strmessagehistory;
fd7006f6 593 }
594
531e58f1 595 $str = link_to_popup_window("/message/history.php?user1=$userid1&amp;user2=$userid2$keywords$position",
596 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
5fb86983 597 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
62119d65 598
5d6b319b 599 $str = '<span class="history">'.$str.'</span>';
600
62119d65 601 if ($returnstr) {
602 return $str;
603 } else {
604 echo $str;
605 return true;
606 }
607}
e8e2d7f1 608
609
610/**
611 * Search through course users
612 *
531e58f1 613 * If $coursid specifies the site course then this function searches
e8e2d7f1 614 * through all undeleted and confirmed users
615 *
7390832c 616 * @uses $CFG, $USER
e8e2d7f1 617 * @uses SITEID
618 * @param int $courseid The course in question.
619 * @param string $searchtext ?
620 * @param string $sort ?
531e58f1 621 * @param string $exceptions ?
e8e2d7f1 622 * @return array An array of {@link $USER} records.
623 * @todo Finish documenting this function
624 */
625function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 626 global $CFG, $USER, $DB;
e8e2d7f1 627
245ac557 628 $fullname = $DB->sql_fullname();
629 $LIKE = $DB->sql_ilike();
e8e2d7f1 630
631 if (!empty($exceptions)) {
632 $except = ' AND u.id NOT IN ('. $exceptions .') ';
633 } else {
634 $except = '';
635 }
636
637 if (!empty($sort)) {
638 $order = ' ORDER BY '. $sort;
639 } else {
640 $order = '';
641 }
642
643 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
7390832c 644 $fields = 'u.id, u.firstname, u.lastname, u.picture, u.imagealt, mc.id as contactlistid, mc.blocked';
e8e2d7f1 645
646 if (!$courseid or $courseid == SITEID) {
fd1cb1e8 647 $params = array($USER->id, "%$searchtext%");
648 return $DB->get_records_sql("SELECT $fields
d9eef08a 649 FROM {user} u
fd1cb1e8 650 LEFT JOIN {message_contacts} mc
651 ON mc.contactid = u.id AND mc.userid = ?
652 WHERE $select
653 AND ($fullname $LIKE ?)
654 $except
655 $order", $params);
e8e2d7f1 656 } else {
657
d76a5a7f 658 $context = get_context_instance(CONTEXT_COURSE, $courseid);
659 $contextlists = get_related_contexts_string($context);
531e58f1 660
d76a5a7f 661 // everyone who has a role assignement in this course or higher
fd1cb1e8 662 $params = array($USER->id, "%$searchtext%");
663 $users = $DB->get_records_sql("SELECT $fields
664 FROM {user} u
665 JOIN {role_assignments} ra ON ra.userid = u.id
666 LEFT JOIN {message_contacts} mc
667 ON mc.contactid = u.id AND mc.userid = ?
668 WHERE $select
669 AND ra.contextid $contextlists
670 AND ($fullname $LIKE ?)
671 $except
672 $order", $params);
d76a5a7f 673
674 return $users;
e8e2d7f1 675 }
676}
677
678
679
680
082864f9 681function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 682/// Returns a list of posts found using an array of search terms
683/// eg word +word -word
684///
fd1cb1e8 685 global $CFG, $USER, $DB;
e8e2d7f1 686
082864f9 687 /// If no userid sent then assume current user
531e58f1 688 if ($userid == 0) $userid = $USER->id;
082864f9 689
6eb7722f 690 /// Some differences in SQL syntax
d9eef08a 691 if ($DB->sql_regex_supported()) {
692 $REGEXP = $DB->sql_regex(true);
693 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 694 }
695
d9eef08a 696 $LIKE = $DB->sql_ilike();
697
698 $searchcond = array();
699 $params = array();
700 $i = 0;
e8e2d7f1 701
702 foreach ($searchterms as $searchterm) {
d9eef08a 703 $i++;
704
705 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
706
e8e2d7f1 707 if (strlen($searchterm) < 2) {
708 continue;
709 }
6bb4875f 710 /// Under Oracle and MSSQL, trim the + and - operators and perform
711 /// simpler LIKE search
d9eef08a 712 if (!$DB->sql_regex_supported()) {
713 if (substr($searchterm, 0, 1) == '-') {
714 $NOT = ' NOT ';
715 }
6bb4875f 716 $searchterm = trim($searchterm, '+-');
717 }
718
e8e2d7f1 719 if (substr($searchterm,0,1) == "+") {
720 $searchterm = substr($searchterm,1);
d9eef08a 721 $searchterm = preg_quote($searchterm, '|');
722 $searchcond[] = "m.message $REGEXP :ss$i";
723 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
724
e8e2d7f1 725 } else if (substr($searchterm,0,1) == "-") {
726 $searchterm = substr($searchterm,1);
d9eef08a 727 $searchterm = preg_quote($searchterm, '|');
728 $searchcond[] = "m.message $NOTREGEXP :ss$i";
729 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
730
e8e2d7f1 731 } else {
d9eef08a 732 $searchcond[] = "m.message $NOT $LIKE :ss$i";
733 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 734 }
172186b8 735 }
736
d9eef08a 737 if (empty($searchcond)) {
738 return array();
8a51efe9 739 }
e8e2d7f1 740
d9eef08a 741 $searchcond = implode(" AND ", $searchcond);
e8e2d7f1 742
743
082864f9 744 /// There are several possibilities
745 /// 1. courseid = SITEID : The admin is searching messages by all users
746 /// 2. courseid = ?? : A teacher is searching messages by users in
747 /// one of their courses - currently disabled
748 /// 3. courseid = none : User is searching their own messages;
749 /// a. Messages from user
750 /// b. Messages to user
751 /// c. Messages to and from user
752
753 if ($courseid == SITEID) { /// admin is searching all messages
d9eef08a 754 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
755 FROM {message_read} m
756 WHERE $searchcond", $params);
757 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
758 FROM {message} m
759 WHERE $searchcond", $params);
760
761 } else if ($courseid !== 'none') {
082864f9 762 /// This has not been implemented due to security concerns
d9eef08a 763 $m_read = array();
764 $m_unread = array();
e8e2d7f1 765
082864f9 766 } else {
531e58f1 767
d9eef08a 768 if ($fromme and $tome) {
769 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
770 $params['userid1'] = $userid;
771 $params['userid2'] = $userid;
772
773 } else if ($fromme) {
774 $searchcond .= " AND m.useridfrom=:userid";
775 $params['userid'] = $userid;
531e58f1 776
d9eef08a 777 } else if ($tome) {
778 $searchcond .= " AND m.useridto=:userid";
779 $params['userid'] = $userid;
780 }
531e58f1 781
d9eef08a 782 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
783 FROM {message_read} m
784 WHERE $searchcond", $params);
785 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
786 FROM {message} m
787 WHERE $searchcond", $params);
531e58f1 788
e8e2d7f1 789 }
790
082864f9 791 /// The keys may be duplicated in $m_read and $m_unread so we can't
792 /// do a simple concatenation
793 $message = array();
d9eef08a 794 foreach ($m_read as $m) {
795 $messages[] = $m;
796 }
797 foreach ($m_unread as $m) {
798 $messages[] = $m;
799 }
e8e2d7f1 800
801 return (empty($messages)) ? false : $messages;
172186b8 802}
803
e8e2d7f1 804
805
806/// Borrowed with changes from mod/forum/lib.php
807function message_shorten_message($message, $minlength=0) {
808// Given a post object that we already know has a long message
809// this function truncates the message nicely to the first
810// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
811
812 $i = 0;
813 $tag = false;
814 $length = strlen($message);
815 $count = 0;
816 $stopzone = false;
817 $truncate = 0;
818 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 819
e8e2d7f1 820
821 for ($i=0; $i<$length; $i++) {
822 $char = $message[$i];
823
824 switch ($char) {
825 case "<":
826 $tag = true;
827 break;
828 case ">":
829 $tag = false;
830 break;
831 default:
832 if (!$tag) {
833 if ($stopzone) {
834 if ($char == '.' or $char == ' ') {
835 $truncate = $i+1;
836 break 2;
837 }
838 }
839 $count++;
840 }
841 break;
842 }
843 if (!$stopzone) {
844 if ($count > $minlength) {
845 $stopzone = true;
846 }
847 }
848 }
849
850 if (!$truncate) {
851 $truncate = $i;
852 }
853
854 return substr($message, 0, $truncate);
855}
856
38c6a928 857
d9eef08a 858/**
38c6a928 859 * Given a string and an array of keywords, this function looks
860 * for the first keyword in the string, and then chops out a
861 * small section from the text that shows that word in context.
862 */
863function message_get_fragment($message, $keywords) {
864
865 $fullsize = 120;
866 $halfsize = (int)($fullsize/2);
867
868 $message = strip_tags($message);
869
870 foreach ($keywords as $keyword) { // Just get the first one
871 if ($keyword !== '') {
872 break;
873 }
874 }
875 if (empty($keyword)) { // None found, so just return start of message
876 return message_shorten_message($message, 30);
877 }
878
879 $leadin = $leadout = '';
880
881/// Find the start of the fragment
882 $start = 0;
883 $length = strlen($message);
884
885 $pos = strpos($message, $keyword);
886 if ($pos > $halfsize) {
887 $start = $pos - $halfsize;
888 $leadin = '...';
889 }
890/// Find the end of the fragment
891 $end = $start + $fullsize;
892 if ($end > $length) {
893 $end = $length;
894 } else {
895 $leadout = '...';
896 }
897
898/// Pull out the fragment and format it
899
900 $fragment = substr($message, $start, $end - $start);
901 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
902 return $fragment;
903}
904
905
b9ee0638 906function message_get_history($user1, $user2) {
fd1cb1e8 907 global $DB;
908
909 $messages = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
910 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
b9ee0638 911 'timecreated');
fd1cb1e8 912 if ($messages_new = $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
913 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
b9ee0638 914 'timecreated')) {
915 foreach ($messages_new as $message) {
916 $messages[] = $message;
917 }
918 }
919 return $messages;
920}
921
030e3e03 922function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 923
924 static $dateformat;
925
926 if (empty($dateformat)) {
927 if ($format) {
928 $dateformat = $format;
929 } else {
54d8f804 930 $format = get_string('strftimedatetimeshort');
acd21a2d 931 }
b9ee0638 932 }
acd21a2d 933 $time = userdate($message->timecreated, $dateformat);
fd1cb1e8 934 $options = new object();
ff6048dd 935 $options->para = false;
936 $messagetext = format_text($message->message, $message->format, $options);
38c6a928 937 if ($keywords) {
938 $messagetext = highlight($keywords, $messagetext);
939 }
030e3e03 940 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>';
b9ee0638 941}
e8e2d7f1 942
fd1cb1e8 943/**
405f01ee 944 * Inserts a message into the database, but also forwards it
945 * via other means if appropriate.
946 */
947function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
fd1cb1e8 948 global $CFG, $SITE, $USER, $DB;
f49edc81 949
950/// Set up current language to suit the receiver of the message
951 $savelang = $USER->lang;
952
953 if (!empty($userto->lang)) {
954 $USER->lang = $userto->lang;
955 }
3b120e46 956
957 $eventdata = new object();
958 $eventdata->modulename = 'moodle';
959 $eventdata->userfrom = $userfrom;
960 $eventdata->userto = $userto;
961 $eventdata->subject = "MESSAGE";
962 $eventdata->fullmessage = $message;
963 $eventdata->fullmessageformat = FORMAT_PLAIN;
964 $eventdata->fullmessagehtml = '';
965 $eventdata->smallmessage = '';
966 events_trigger('message_send', $eventdata);
967
405f01ee 968
969/// Save the new message in the database
970
971 $savemessage = NULL;
972 $savemessage->useridfrom = $userfrom->id;
973 $savemessage->useridto = $userto->id;
974 $savemessage->message = $message;
975 $savemessage->format = $format;
976 $savemessage->timecreated = time();
977 $savemessage->messagetype = 'direct';
978
576ad290 979 if ($CFG->messaging) {
3b120e46 980 //if (!$savemessage->id = $DB->insert_record('message', $savemessage)) {
981 // return false;
982 //}
576ad290 983 $emailforced = false;
984 } else { // $CFG->messaging is not on, we need to force sending of emails
985 $emailforced = true;
986 $savemessage->id = true;
405f01ee 987 }
988
405f01ee 989/// Check to see if anything else needs to be done with it
990
991 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
992
576ad290 993 if ($emailforced || (!isset($preference->message_emailmessages) || $preference->message_emailmessages)) { // Receiver wants mail forwarding
54bf5de8 994 if (!isset($preference->message_emailtimenosee)) {
995 $preference->message_emailtimenosee = 10;
996 }
7c8b82a9 997 if (!isset($preference->message_emailformat)) {
998 $preference->message_emailformat = FORMAT_HTML;
999 }
576ad290 1000 if ($emailforced || (time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
405f01ee 1001
405f01ee 1002 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
531e58f1 1003
59c0c3f9 1004 $messagesubject = preg_replace('/\s+/', ' ', strip_tags($message)); // make sure it's all on one line
1005 $messagesubject = message_shorten_message($messagesubject, 30).'...';
405f01ee 1006
1007 $messagetext = format_text_email($message, $format).
1008 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1009
49487025 1010 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
405f01ee 1011 $messagehtml = format_text($message, $format);
576ad290 1012 // MDL-10294, do not print link if messaging is disabled
1013 if ($CFG->messaging) {
1014 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1015 }
405f01ee 1016 } else {
1017 $messagehtml = NULL;
1018 }
1019
54bf5de8 1020 if (!empty($preference->message_emailaddress)) {
1021 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1022 }
576ad290 1023
3aa3cf3d 1024 if (email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml)) {
1025 $CFG->messagewasjustemailed = true;
1026 }
576ad290 1027
4603b8d6 1028 sleep(3);
405f01ee 1029 }
1030 }
1031
f49edc81 1032 $USER->lang = $savelang; // restore original language
1033
2973ec18 1034 return $savemessage->id;
405f01ee 1035}
e8e2d7f1 1036
c135a425 1037
fd1cb1e8 1038/**
c135a425 1039 * Returns a list of all user ids who have used messaging in the site
1040 * This was the simple way to code the SQL ... is it going to blow up
1041 * on large datasets?
1042 */
1043function message_get_participants() {
fd1cb1e8 1044 global $CFG, $DB;
1045
76b0191c 1046 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1047 UNION SELECT useridto as id,1 FROM {message}
1048 UNION SELECT useridfrom as id,1 FROM {message_read}
1049 UNION SELECT useridto as id,1 FROM {message_read}
1050 UNION SELECT userid as id,1 FROM {message_contacts}
1051 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1052}
1053
f46b6587 1054/**
1055 * Print a row of contactlist displaying user picture, messages waiting and
1056 * block links etc
1057 * @param $contact contact object containing all fields required for print_user_picture()
1058 * @param $incontactlist is the user a contact of ours?
1059 */
1060function message_print_contactlist_user($contact, $incontactlist = true){
1061 $fullname = fullname($contact);
1062 $fullnamelink = $fullname;
1063
1064 /// are there any unread messages for this contact?
1065 if ($contact->messagecount > 0 ){
1066 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1067 }
1068
1069
1070 if($incontactlist){
1071 $strcontact = message_contact_link($contact->id, 'remove', true);
1072 $strblock = '';
1073 }else{
1074 $strcontact = message_contact_link($contact->id, 'add', true);
1075 $strblock = '&nbsp;'. message_contact_link($contact->id, 'block', true);
1076 }
1077
1078 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
1079
1080 echo '<tr><td class="pix">';
1081 print_user_picture($contact, SITEID, $contact->picture, 20, false, true, 'userwindow');
1082 echo '</td>';
1083 echo '<td class="contact">';
1084
1085 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
1086 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
1087 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
1088
1089 echo '</td>';
1090 echo '<td class="link">&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory.'</td>';
1091 echo '</tr>';
1092}
1093
172186b8 1094?>