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